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/CodeGen/Analysis.h"
35 #include "llvm/IR/DiagnosticInfo.h"
36 #include "llvm/IR/Function.h"
37 
38 using namespace llvm;
39 
40 static cl::opt<bool> EnableVGPRIndexMode(
41   "amdgpu-vgpr-index-mode",
42   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
43   cl::init(false));
44 
45 
46 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
47   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
48   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
49     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
50       return AMDGPU::SGPR0 + Reg;
51     }
52   }
53   llvm_unreachable("Cannot allocate sgpr");
54 }
55 
56 SITargetLowering::SITargetLowering(const TargetMachine &TM,
57                                    const SISubtarget &STI)
58     : AMDGPUTargetLowering(TM, STI) {
59   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
60   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
61 
62   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
63   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
64 
65   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
66   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
67   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
68 
69   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
70   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
71 
72   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
73   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
74 
75   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
76   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
77 
78   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
79   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
80 
81   if (Subtarget->has16BitInsts()) {
82     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
83     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
84   }
85 
86   computeRegisterProperties(STI.getRegisterInfo());
87 
88   // We need to custom lower vector stores from local memory
89   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
90   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
91   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
92   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
93   setOperationAction(ISD::LOAD, MVT::i1, Custom);
94 
95   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
96   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
97   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
98   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
99   setOperationAction(ISD::STORE, MVT::i1, Custom);
100 
101   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
102   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
104 
105   setOperationAction(ISD::SELECT, MVT::i1, Promote);
106   setOperationAction(ISD::SELECT, MVT::i64, Custom);
107   setOperationAction(ISD::SELECT, MVT::f64, Promote);
108   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
109 
110   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
111   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
112   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
113   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
114   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
115 
116   setOperationAction(ISD::SETCC, MVT::i1, Promote);
117   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
118   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
119 
120   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
121   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
122 
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
130 
131   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
132   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
133   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
134 
135   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
136   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
137   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
138   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
139   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
140   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
141 
142   // We only support LOAD/STORE and vector manipulation ops for vectors
143   // with > 4 elements.
144   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
145     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
146       switch (Op) {
147       case ISD::LOAD:
148       case ISD::STORE:
149       case ISD::BUILD_VECTOR:
150       case ISD::BITCAST:
151       case ISD::EXTRACT_VECTOR_ELT:
152       case ISD::INSERT_VECTOR_ELT:
153       case ISD::INSERT_SUBVECTOR:
154       case ISD::EXTRACT_SUBVECTOR:
155       case ISD::SCALAR_TO_VECTOR:
156         break;
157       case ISD::CONCAT_VECTORS:
158         setOperationAction(Op, VT, Custom);
159         break;
160       default:
161         setOperationAction(Op, VT, Expand);
162         break;
163       }
164     }
165   }
166 
167   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
168   // is expanded to avoid having two separate loops in case the index is a VGPR.
169 
170   // Most operations are naturally 32-bit vector operations. We only support
171   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
172   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
173     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
174     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
175 
176     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
177     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
178 
179     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
180     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
181 
182     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
183     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
184   }
185 
186   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
187   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
188   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
189   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
190 
191   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
192   // and output demarshalling
193   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
194   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
195 
196   // We can't return success/failure, only the old value,
197   // let LLVM add the comparison
198   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
199   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
200 
201   if (getSubtarget()->hasFlatAddressSpace()) {
202     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
203     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
204   }
205 
206   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
207   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
208 
209   // On SI this is s_memtime and s_memrealtime on VI.
210   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
211   setOperationAction(ISD::TRAP, MVT::Other, Custom);
212 
213   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
214   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
215 
216   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
217     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
218     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
219     setOperationAction(ISD::FRINT, MVT::f64, Legal);
220   }
221 
222   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
223 
224   setOperationAction(ISD::FSIN, MVT::f32, Custom);
225   setOperationAction(ISD::FCOS, MVT::f32, Custom);
226   setOperationAction(ISD::FDIV, MVT::f32, Custom);
227   setOperationAction(ISD::FDIV, MVT::f64, Custom);
228 
229   if (Subtarget->has16BitInsts()) {
230     setOperationAction(ISD::Constant, MVT::i16, Legal);
231 
232     setOperationAction(ISD::SMIN, MVT::i16, Legal);
233     setOperationAction(ISD::SMAX, MVT::i16, Legal);
234 
235     setOperationAction(ISD::UMIN, MVT::i16, Legal);
236     setOperationAction(ISD::UMAX, MVT::i16, Legal);
237 
238     setOperationAction(ISD::SETCC, MVT::i16, Promote);
239     AddPromotedToType(ISD::SETCC, MVT::i16, MVT::i32);
240 
241     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
242     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
243 
244     setOperationAction(ISD::ROTR, MVT::i16, Promote);
245     setOperationAction(ISD::ROTL, MVT::i16, Promote);
246 
247     setOperationAction(ISD::SDIV, MVT::i16, Promote);
248     setOperationAction(ISD::UDIV, MVT::i16, Promote);
249     setOperationAction(ISD::SREM, MVT::i16, Promote);
250     setOperationAction(ISD::UREM, MVT::i16, Promote);
251 
252     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
253     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
254 
255     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
256     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
257     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
258     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
259 
260     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
261 
262     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
263 
264     setOperationAction(ISD::LOAD, MVT::i16, Custom);
265 
266     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
267 
268     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
269     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
270     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
271     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
272 
273     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
274     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
275     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
276     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
277 
278     // F16 - Constant Actions.
279     setOperationAction(ISD::ConstantFP, MVT::f16, Custom);
280 
281     // F16 - Load/Store Actions.
282     setOperationAction(ISD::LOAD, MVT::f16, Promote);
283     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
284     setOperationAction(ISD::STORE, MVT::f16, Promote);
285     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
286 
287     // F16 - VOP1 Actions.
288     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
289     setOperationAction(ISD::FCOS, MVT::f16, Promote);
290     setOperationAction(ISD::FSIN, MVT::f16, Promote);
291     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
292     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
293     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
294     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
295 
296     // F16 - VOP2 Actions.
297     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
298     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
299     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
300     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
301     setOperationAction(ISD::FDIV, MVT::f16, Promote);
302 
303     // F16 - VOP3 Actions.
304     setOperationAction(ISD::FMA, MVT::f16, Legal);
305     if (!Subtarget->hasFP16Denormals())
306       setOperationAction(ISD::FMAD, MVT::f16, Legal);
307   }
308 
309   setTargetDAGCombine(ISD::FADD);
310   setTargetDAGCombine(ISD::FSUB);
311   setTargetDAGCombine(ISD::FMINNUM);
312   setTargetDAGCombine(ISD::FMAXNUM);
313   setTargetDAGCombine(ISD::SMIN);
314   setTargetDAGCombine(ISD::SMAX);
315   setTargetDAGCombine(ISD::UMIN);
316   setTargetDAGCombine(ISD::UMAX);
317   setTargetDAGCombine(ISD::SETCC);
318   setTargetDAGCombine(ISD::AND);
319   setTargetDAGCombine(ISD::OR);
320   setTargetDAGCombine(ISD::XOR);
321   setTargetDAGCombine(ISD::SINT_TO_FP);
322   setTargetDAGCombine(ISD::UINT_TO_FP);
323   setTargetDAGCombine(ISD::FCANONICALIZE);
324 
325   // All memory operations. Some folding on the pointer operand is done to help
326   // matching the constant offsets in the addressing modes.
327   setTargetDAGCombine(ISD::LOAD);
328   setTargetDAGCombine(ISD::STORE);
329   setTargetDAGCombine(ISD::ATOMIC_LOAD);
330   setTargetDAGCombine(ISD::ATOMIC_STORE);
331   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
332   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
333   setTargetDAGCombine(ISD::ATOMIC_SWAP);
334   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
335   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
336   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
337   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
338   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
339   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
340   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
341   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
342   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
343   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
344 
345   setSchedulingPreference(Sched::RegPressure);
346 }
347 
348 const SISubtarget *SITargetLowering::getSubtarget() const {
349   return static_cast<const SISubtarget *>(Subtarget);
350 }
351 
352 //===----------------------------------------------------------------------===//
353 // TargetLowering queries
354 //===----------------------------------------------------------------------===//
355 
356 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
357                                           const CallInst &CI,
358                                           unsigned IntrID) const {
359   switch (IntrID) {
360   case Intrinsic::amdgcn_atomic_inc:
361   case Intrinsic::amdgcn_atomic_dec:
362     Info.opc = ISD::INTRINSIC_W_CHAIN;
363     Info.memVT = MVT::getVT(CI.getType());
364     Info.ptrVal = CI.getOperand(0);
365     Info.align = 0;
366     Info.vol = false;
367     Info.readMem = true;
368     Info.writeMem = true;
369     return true;
370   default:
371     return false;
372   }
373 }
374 
375 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
376                                           EVT) const {
377   // SI has some legal vector types, but no legal vector operations. Say no
378   // shuffles are legal in order to prefer scalarizing some vector operations.
379   return false;
380 }
381 
382 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
383   // Flat instructions do not have offsets, and only have the register
384   // address.
385   return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
386 }
387 
388 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
389   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
390   // additionally can do r + r + i with addr64. 32-bit has more addressing
391   // mode options. Depending on the resource constant, it can also do
392   // (i64 r0) + (i32 r1) * (i14 i).
393   //
394   // Private arrays end up using a scratch buffer most of the time, so also
395   // assume those use MUBUF instructions. Scratch loads / stores are currently
396   // implemented as mubuf instructions with offen bit set, so slightly
397   // different than the normal addr64.
398   if (!isUInt<12>(AM.BaseOffs))
399     return false;
400 
401   // FIXME: Since we can split immediate into soffset and immediate offset,
402   // would it make sense to allow any immediate?
403 
404   switch (AM.Scale) {
405   case 0: // r + i or just i, depending on HasBaseReg.
406     return true;
407   case 1:
408     return true; // We have r + r or r + i.
409   case 2:
410     if (AM.HasBaseReg) {
411       // Reject 2 * r + r.
412       return false;
413     }
414 
415     // Allow 2 * r as r + r
416     // Or  2 * r + i is allowed as r + r + i.
417     return true;
418   default: // Don't allow n * r
419     return false;
420   }
421 }
422 
423 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
424                                              const AddrMode &AM, Type *Ty,
425                                              unsigned AS) const {
426   // No global is ever allowed as a base.
427   if (AM.BaseGV)
428     return false;
429 
430   switch (AS) {
431   case AMDGPUAS::GLOBAL_ADDRESS: {
432     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
433       // Assume the we will use FLAT for all global memory accesses
434       // on VI.
435       // FIXME: This assumption is currently wrong.  On VI we still use
436       // MUBUF instructions for the r + i addressing mode.  As currently
437       // implemented, the MUBUF instructions only work on buffer < 4GB.
438       // It may be possible to support > 4GB buffers with MUBUF instructions,
439       // by setting the stride value in the resource descriptor which would
440       // increase the size limit to (stride * 4GB).  However, this is risky,
441       // because it has never been validated.
442       return isLegalFlatAddressingMode(AM);
443     }
444 
445     return isLegalMUBUFAddressingMode(AM);
446   }
447   case AMDGPUAS::CONSTANT_ADDRESS: {
448     // If the offset isn't a multiple of 4, it probably isn't going to be
449     // correctly aligned.
450     // FIXME: Can we get the real alignment here?
451     if (AM.BaseOffs % 4 != 0)
452       return isLegalMUBUFAddressingMode(AM);
453 
454     // There are no SMRD extloads, so if we have to do a small type access we
455     // will use a MUBUF load.
456     // FIXME?: We also need to do this if unaligned, but we don't know the
457     // alignment here.
458     if (DL.getTypeStoreSize(Ty) < 4)
459       return isLegalMUBUFAddressingMode(AM);
460 
461     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
462       // SMRD instructions have an 8-bit, dword offset on SI.
463       if (!isUInt<8>(AM.BaseOffs / 4))
464         return false;
465     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
466       // On CI+, this can also be a 32-bit literal constant offset. If it fits
467       // in 8-bits, it can use a smaller encoding.
468       if (!isUInt<32>(AM.BaseOffs / 4))
469         return false;
470     } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) {
471       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
472       if (!isUInt<20>(AM.BaseOffs))
473         return false;
474     } else
475       llvm_unreachable("unhandled generation");
476 
477     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
478       return true;
479 
480     if (AM.Scale == 1 && AM.HasBaseReg)
481       return true;
482 
483     return false;
484   }
485 
486   case AMDGPUAS::PRIVATE_ADDRESS:
487     return isLegalMUBUFAddressingMode(AM);
488 
489   case AMDGPUAS::LOCAL_ADDRESS:
490   case AMDGPUAS::REGION_ADDRESS: {
491     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
492     // field.
493     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
494     // an 8-bit dword offset but we don't know the alignment here.
495     if (!isUInt<16>(AM.BaseOffs))
496       return false;
497 
498     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
499       return true;
500 
501     if (AM.Scale == 1 && AM.HasBaseReg)
502       return true;
503 
504     return false;
505   }
506   case AMDGPUAS::FLAT_ADDRESS:
507   case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
508     // For an unknown address space, this usually means that this is for some
509     // reason being used for pure arithmetic, and not based on some addressing
510     // computation. We don't have instructions that compute pointers with any
511     // addressing modes, so treat them as having no offset like flat
512     // instructions.
513     return isLegalFlatAddressingMode(AM);
514 
515   default:
516     llvm_unreachable("unhandled address space");
517   }
518 }
519 
520 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
521                                                       unsigned AddrSpace,
522                                                       unsigned Align,
523                                                       bool *IsFast) const {
524   if (IsFast)
525     *IsFast = false;
526 
527   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
528   // which isn't a simple VT.
529   // Until MVT is extended to handle this, simply check for the size and
530   // rely on the condition below: allow accesses if the size is a multiple of 4.
531   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
532                            VT.getStoreSize() > 16)) {
533     return false;
534   }
535 
536   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
537       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
538     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
539     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
540     // with adjacent offsets.
541     bool AlignedBy4 = (Align % 4 == 0);
542     if (IsFast)
543       *IsFast = AlignedBy4;
544 
545     return AlignedBy4;
546   }
547 
548   // FIXME: We have to be conservative here and assume that flat operations
549   // will access scratch.  If we had access to the IR function, then we
550   // could determine if any private memory was used in the function.
551   if (!Subtarget->hasUnalignedScratchAccess() &&
552       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
553        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
554     return false;
555   }
556 
557   if (Subtarget->hasUnalignedBufferAccess()) {
558     // If we have an uniform constant load, it still requires using a slow
559     // buffer instruction if unaligned.
560     if (IsFast) {
561       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ?
562         (Align % 4 == 0) : true;
563     }
564 
565     return true;
566   }
567 
568   // Smaller than dword value must be aligned.
569   if (VT.bitsLT(MVT::i32))
570     return false;
571 
572   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
573   // byte-address are ignored, thus forcing Dword alignment.
574   // This applies to private, global, and constant memory.
575   if (IsFast)
576     *IsFast = true;
577 
578   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
579 }
580 
581 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
582                                           unsigned SrcAlign, bool IsMemset,
583                                           bool ZeroMemset,
584                                           bool MemcpyStrSrc,
585                                           MachineFunction &MF) const {
586   // FIXME: Should account for address space here.
587 
588   // The default fallback uses the private pointer size as a guess for a type to
589   // use. Make sure we switch these to 64-bit accesses.
590 
591   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
592     return MVT::v4i32;
593 
594   if (Size >= 8 && DstAlign >= 4)
595     return MVT::v2i32;
596 
597   // Use the default.
598   return MVT::Other;
599 }
600 
601 static bool isFlatGlobalAddrSpace(unsigned AS) {
602   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
603     AS == AMDGPUAS::FLAT_ADDRESS ||
604     AS == AMDGPUAS::CONSTANT_ADDRESS;
605 }
606 
607 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
608                                            unsigned DestAS) const {
609   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
610 }
611 
612 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
613   const MemSDNode *MemNode = cast<MemSDNode>(N);
614   const Value *Ptr = MemNode->getMemOperand()->getValue();
615 
616   // UndefValue means this is a load of a kernel input.  These are uniform.
617   // Sometimes LDS instructions have constant pointers.
618   // If Ptr is null, then that means this mem operand contains a
619   // PseudoSourceValue like GOT.
620   if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) ||
621       isa<Constant>(Ptr) || isa<GlobalValue>(Ptr))
622     return true;
623 
624   const Instruction *I = dyn_cast<Instruction>(Ptr);
625   return I && I->getMetadata("amdgpu.uniform");
626 }
627 
628 TargetLoweringBase::LegalizeTypeAction
629 SITargetLowering::getPreferredVectorAction(EVT VT) const {
630   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
631     return TypeSplitVector;
632 
633   return TargetLoweringBase::getPreferredVectorAction(VT);
634 }
635 
636 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
637                                                          Type *Ty) const {
638   // FIXME: Could be smarter if called for vector constants.
639   return true;
640 }
641 
642 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
643 
644   // i16 is not desirable unless it is a load or a store.
645   if (VT == MVT::i16 && Op != ISD::LOAD && Op != ISD::STORE)
646     return false;
647 
648   // SimplifySetCC uses this function to determine whether or not it should
649   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
650   if (VT == MVT::i1 && Op == ISD::SETCC)
651     return false;
652 
653   return TargetLowering::isTypeDesirableForOp(Op, VT);
654 }
655 
656 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
657                                             const SDLoc &SL, SDValue Chain,
658                                             unsigned Offset) const {
659   const DataLayout &DL = DAG.getDataLayout();
660   MachineFunction &MF = DAG.getMachineFunction();
661   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
662   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
663 
664   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
665   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
666   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
667                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
668   return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
669                      DAG.getConstant(Offset, SL, PtrVT));
670 }
671 
672 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
673                                          const SDLoc &SL, SDValue Chain,
674                                          unsigned Offset, bool Signed) const {
675   const DataLayout &DL = DAG.getDataLayout();
676   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
677   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
678   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
679 
680   unsigned Align = DL.getABITypeAlignment(Ty);
681 
682   SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
683   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
684                              MachineMemOperand::MONonTemporal |
685                              MachineMemOperand::MODereferenceable |
686                              MachineMemOperand::MOInvariant);
687 
688   SDValue Val;
689   if (MemVT.isFloatingPoint())
690     Val = getFPExtOrFPTrunc(DAG, Load, SL, VT);
691   else if (Signed)
692     Val = DAG.getSExtOrTrunc(Load, SL, VT);
693   else
694     Val = DAG.getZExtOrTrunc(Load, SL, VT);
695 
696   SDValue Ops[] = {
697     Val,
698     Load.getValue(1)
699   };
700 
701   return DAG.getMergeValues(Ops, SL);
702 }
703 
704 SDValue SITargetLowering::LowerFormalArguments(
705     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
706     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
707     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
708   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
709 
710   MachineFunction &MF = DAG.getMachineFunction();
711   FunctionType *FType = MF.getFunction()->getFunctionType();
712   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
713   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
714 
715   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
716     const Function *Fn = MF.getFunction();
717     DiagnosticInfoUnsupported NoGraphicsHSA(
718         *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
719     DAG.getContext()->diagnose(NoGraphicsHSA);
720     return DAG.getEntryNode();
721   }
722 
723   // Create stack objects that are used for emitting debugger prologue if
724   // "amdgpu-debugger-emit-prologue" attribute was specified.
725   if (ST.debuggerEmitPrologue())
726     createDebuggerPrologueStackObjects(MF);
727 
728   SmallVector<ISD::InputArg, 16> Splits;
729   BitVector Skipped(Ins.size());
730 
731   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
732     const ISD::InputArg &Arg = Ins[i];
733 
734     // First check if it's a PS input addr
735     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
736         !Arg.Flags.isByVal() && PSInputNum <= 15) {
737 
738       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
739         // We can safely skip PS inputs
740         Skipped.set(i);
741         ++PSInputNum;
742         continue;
743       }
744 
745       Info->markPSInputAllocated(PSInputNum);
746       if (Arg.Used)
747         Info->PSInputEna |= 1 << PSInputNum;
748 
749       ++PSInputNum;
750     }
751 
752     if (AMDGPU::isShader(CallConv)) {
753       // Second split vertices into their elements
754       if (Arg.VT.isVector()) {
755         ISD::InputArg NewArg = Arg;
756         NewArg.Flags.setSplit();
757         NewArg.VT = Arg.VT.getVectorElementType();
758 
759         // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
760         // three or five element vertex only needs three or five registers,
761         // NOT four or eight.
762         Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
763         unsigned NumElements = ParamType->getVectorNumElements();
764 
765         for (unsigned j = 0; j != NumElements; ++j) {
766           Splits.push_back(NewArg);
767           NewArg.PartOffset += NewArg.VT.getStoreSize();
768         }
769       } else {
770         Splits.push_back(Arg);
771       }
772     }
773   }
774 
775   SmallVector<CCValAssign, 16> ArgLocs;
776   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
777                  *DAG.getContext());
778 
779   // At least one interpolation mode must be enabled or else the GPU will hang.
780   //
781   // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
782   // PSInputAddr, the user wants to enable some bits after the compilation
783   // based on run-time states. Since we can't know what the final PSInputEna
784   // will look like, so we shouldn't do anything here and the user should take
785   // responsibility for the correct programming.
786   //
787   // Otherwise, the following restrictions apply:
788   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
789   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
790   //   enabled too.
791   if (CallConv == CallingConv::AMDGPU_PS &&
792       ((Info->getPSInputAddr() & 0x7F) == 0 ||
793        ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
794     CCInfo.AllocateReg(AMDGPU::VGPR0);
795     CCInfo.AllocateReg(AMDGPU::VGPR1);
796     Info->markPSInputAllocated(0);
797     Info->PSInputEna |= 1;
798   }
799 
800   if (!AMDGPU::isShader(CallConv)) {
801     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
802   } else {
803     assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() &&
804            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
805            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
806            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
807            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
808            !Info->hasWorkItemIDZ());
809   }
810 
811   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
812   if (Info->hasPrivateSegmentBuffer()) {
813     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
814     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
815     CCInfo.AllocateReg(PrivateSegmentBufferReg);
816   }
817 
818   if (Info->hasDispatchPtr()) {
819     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
820     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
821     CCInfo.AllocateReg(DispatchPtrReg);
822   }
823 
824   if (Info->hasQueuePtr()) {
825     unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
826     MF.addLiveIn(QueuePtrReg, &AMDGPU::SReg_64RegClass);
827     CCInfo.AllocateReg(QueuePtrReg);
828   }
829 
830   if (Info->hasKernargSegmentPtr()) {
831     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
832     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
833     CCInfo.AllocateReg(InputPtrReg);
834   }
835 
836   if (Info->hasDispatchID()) {
837     unsigned DispatchIDReg = Info->addDispatchID(*TRI);
838     MF.addLiveIn(DispatchIDReg, &AMDGPU::SReg_64RegClass);
839     CCInfo.AllocateReg(DispatchIDReg);
840   }
841 
842   if (Info->hasFlatScratchInit()) {
843     unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
844     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass);
845     CCInfo.AllocateReg(FlatScratchInitReg);
846   }
847 
848   if (!AMDGPU::isShader(CallConv))
849     analyzeFormalArgumentsCompute(CCInfo, Ins);
850   else
851     AnalyzeFormalArguments(CCInfo, Splits);
852 
853   SmallVector<SDValue, 16> Chains;
854 
855   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
856 
857     const ISD::InputArg &Arg = Ins[i];
858     if (Skipped[i]) {
859       InVals.push_back(DAG.getUNDEF(Arg.VT));
860       continue;
861     }
862 
863     CCValAssign &VA = ArgLocs[ArgIdx++];
864     MVT VT = VA.getLocVT();
865 
866     if (VA.isMemLoc()) {
867       VT = Ins[i].VT;
868       EVT MemVT = VA.getLocVT();
869       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
870                               VA.getLocMemOffset();
871       // The first 36 bytes of the input buffer contains information about
872       // thread group and global sizes.
873       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
874                                    Offset, Ins[i].Flags.isSExt());
875       Chains.push_back(Arg.getValue(1));
876 
877       auto *ParamTy =
878         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
879       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
880           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
881         // On SI local pointers are just offsets into LDS, so they are always
882         // less than 16-bits.  On CI and newer they could potentially be
883         // real pointers, so we can't guarantee their size.
884         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
885                           DAG.getValueType(MVT::i16));
886       }
887 
888       InVals.push_back(Arg);
889       Info->setABIArgOffset(Offset + MemVT.getStoreSize());
890       continue;
891     }
892     assert(VA.isRegLoc() && "Parameter must be in a register!");
893 
894     unsigned Reg = VA.getLocReg();
895 
896     if (VT == MVT::i64) {
897       // For now assume it is a pointer
898       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
899                                      &AMDGPU::SReg_64RegClass);
900       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
901       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
902       InVals.push_back(Copy);
903       continue;
904     }
905 
906     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
907 
908     Reg = MF.addLiveIn(Reg, RC);
909     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
910 
911     if (Arg.VT.isVector()) {
912 
913       // Build a vector from the registers
914       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
915       unsigned NumElements = ParamType->getVectorNumElements();
916 
917       SmallVector<SDValue, 4> Regs;
918       Regs.push_back(Val);
919       for (unsigned j = 1; j != NumElements; ++j) {
920         Reg = ArgLocs[ArgIdx++].getLocReg();
921         Reg = MF.addLiveIn(Reg, RC);
922 
923         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
924         Regs.push_back(Copy);
925       }
926 
927       // Fill up the missing vector elements
928       NumElements = Arg.VT.getVectorNumElements() - NumElements;
929       Regs.append(NumElements, DAG.getUNDEF(VT));
930 
931       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
932       continue;
933     }
934 
935     InVals.push_back(Val);
936   }
937 
938   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
939   // these from the dispatch pointer.
940 
941   // Start adding system SGPRs.
942   if (Info->hasWorkGroupIDX()) {
943     unsigned Reg = Info->addWorkGroupIDX();
944     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
945     CCInfo.AllocateReg(Reg);
946   }
947 
948   if (Info->hasWorkGroupIDY()) {
949     unsigned Reg = Info->addWorkGroupIDY();
950     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
951     CCInfo.AllocateReg(Reg);
952   }
953 
954   if (Info->hasWorkGroupIDZ()) {
955     unsigned Reg = Info->addWorkGroupIDZ();
956     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
957     CCInfo.AllocateReg(Reg);
958   }
959 
960   if (Info->hasWorkGroupInfo()) {
961     unsigned Reg = Info->addWorkGroupInfo();
962     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
963     CCInfo.AllocateReg(Reg);
964   }
965 
966   if (Info->hasPrivateSegmentWaveByteOffset()) {
967     // Scratch wave offset passed in system SGPR.
968     unsigned PrivateSegmentWaveByteOffsetReg;
969 
970     if (AMDGPU::isShader(CallConv)) {
971       PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
972       Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
973     } else
974       PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
975 
976     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
977     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
978   }
979 
980   // Now that we've figured out where the scratch register inputs are, see if
981   // should reserve the arguments and use them directly.
982   bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
983   // Record that we know we have non-spill stack objects so we don't need to
984   // check all stack objects later.
985   if (HasStackObjects)
986     Info->setHasNonSpillStackObjects(true);
987 
988   // Everything live out of a block is spilled with fast regalloc, so it's
989   // almost certain that spilling will be required.
990   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
991     HasStackObjects = true;
992 
993   if (ST.isAmdCodeObjectV2()) {
994     if (HasStackObjects) {
995       // If we have stack objects, we unquestionably need the private buffer
996       // resource. For the Code Object V2 ABI, this will be the first 4 user
997       // SGPR inputs. We can reserve those and use them directly.
998 
999       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
1000         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1001       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
1002 
1003       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
1004         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1005       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1006     } else {
1007       unsigned ReservedBufferReg
1008         = TRI->reservedPrivateSegmentBufferReg(MF);
1009       unsigned ReservedOffsetReg
1010         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1011 
1012       // We tentatively reserve the last registers (skipping the last two
1013       // which may contain VCC). After register allocation, we'll replace
1014       // these with the ones immediately after those which were really
1015       // allocated. In the prologue copies will be inserted from the argument
1016       // to these reserved registers.
1017       Info->setScratchRSrcReg(ReservedBufferReg);
1018       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1019     }
1020   } else {
1021     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
1022 
1023     // Without HSA, relocations are used for the scratch pointer and the
1024     // buffer resource setup is always inserted in the prologue. Scratch wave
1025     // offset is still in an input SGPR.
1026     Info->setScratchRSrcReg(ReservedBufferReg);
1027 
1028     if (HasStackObjects) {
1029       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
1030         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1031       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1032     } else {
1033       unsigned ReservedOffsetReg
1034         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1035       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1036     }
1037   }
1038 
1039   if (Info->hasWorkItemIDX()) {
1040     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1041     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1042     CCInfo.AllocateReg(Reg);
1043   }
1044 
1045   if (Info->hasWorkItemIDY()) {
1046     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1047     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1048     CCInfo.AllocateReg(Reg);
1049   }
1050 
1051   if (Info->hasWorkItemIDZ()) {
1052     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1053     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1054     CCInfo.AllocateReg(Reg);
1055   }
1056 
1057   if (Chains.empty())
1058     return Chain;
1059 
1060   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1061 }
1062 
1063 SDValue
1064 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1065                               bool isVarArg,
1066                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1067                               const SmallVectorImpl<SDValue> &OutVals,
1068                               const SDLoc &DL, SelectionDAG &DAG) const {
1069   MachineFunction &MF = DAG.getMachineFunction();
1070   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1071 
1072   if (!AMDGPU::isShader(CallConv))
1073     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1074                                              OutVals, DL, DAG);
1075 
1076   Info->setIfReturnsVoid(Outs.size() == 0);
1077 
1078   SmallVector<ISD::OutputArg, 48> Splits;
1079   SmallVector<SDValue, 48> SplitVals;
1080 
1081   // Split vectors into their elements.
1082   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1083     const ISD::OutputArg &Out = Outs[i];
1084 
1085     if (Out.VT.isVector()) {
1086       MVT VT = Out.VT.getVectorElementType();
1087       ISD::OutputArg NewOut = Out;
1088       NewOut.Flags.setSplit();
1089       NewOut.VT = VT;
1090 
1091       // We want the original number of vector elements here, e.g.
1092       // three or five, not four or eight.
1093       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1094 
1095       for (unsigned j = 0; j != NumElements; ++j) {
1096         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1097                                    DAG.getConstant(j, DL, MVT::i32));
1098         SplitVals.push_back(Elem);
1099         Splits.push_back(NewOut);
1100         NewOut.PartOffset += NewOut.VT.getStoreSize();
1101       }
1102     } else {
1103       SplitVals.push_back(OutVals[i]);
1104       Splits.push_back(Out);
1105     }
1106   }
1107 
1108   // CCValAssign - represent the assignment of the return value to a location.
1109   SmallVector<CCValAssign, 48> RVLocs;
1110 
1111   // CCState - Info about the registers and stack slots.
1112   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1113                  *DAG.getContext());
1114 
1115   // Analyze outgoing return values.
1116   AnalyzeReturn(CCInfo, Splits);
1117 
1118   SDValue Flag;
1119   SmallVector<SDValue, 48> RetOps;
1120   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1121 
1122   // Copy the result values into the output registers.
1123   for (unsigned i = 0, realRVLocIdx = 0;
1124        i != RVLocs.size();
1125        ++i, ++realRVLocIdx) {
1126     CCValAssign &VA = RVLocs[i];
1127     assert(VA.isRegLoc() && "Can only return in registers!");
1128 
1129     SDValue Arg = SplitVals[realRVLocIdx];
1130 
1131     // Copied from other backends.
1132     switch (VA.getLocInfo()) {
1133     default: llvm_unreachable("Unknown loc info!");
1134     case CCValAssign::Full:
1135       break;
1136     case CCValAssign::BCvt:
1137       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1138       break;
1139     }
1140 
1141     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1142     Flag = Chain.getValue(1);
1143     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1144   }
1145 
1146   // Update chain and glue.
1147   RetOps[0] = Chain;
1148   if (Flag.getNode())
1149     RetOps.push_back(Flag);
1150 
1151   unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN;
1152   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1153 }
1154 
1155 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1156                                              SelectionDAG &DAG) const {
1157   unsigned Reg = StringSwitch<unsigned>(RegName)
1158     .Case("m0", AMDGPU::M0)
1159     .Case("exec", AMDGPU::EXEC)
1160     .Case("exec_lo", AMDGPU::EXEC_LO)
1161     .Case("exec_hi", AMDGPU::EXEC_HI)
1162     .Case("flat_scratch", AMDGPU::FLAT_SCR)
1163     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1164     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1165     .Default(AMDGPU::NoRegister);
1166 
1167   if (Reg == AMDGPU::NoRegister) {
1168     report_fatal_error(Twine("invalid register name \""
1169                              + StringRef(RegName)  + "\"."));
1170 
1171   }
1172 
1173   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1174       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1175     report_fatal_error(Twine("invalid register \""
1176                              + StringRef(RegName)  + "\" for subtarget."));
1177   }
1178 
1179   switch (Reg) {
1180   case AMDGPU::M0:
1181   case AMDGPU::EXEC_LO:
1182   case AMDGPU::EXEC_HI:
1183   case AMDGPU::FLAT_SCR_LO:
1184   case AMDGPU::FLAT_SCR_HI:
1185     if (VT.getSizeInBits() == 32)
1186       return Reg;
1187     break;
1188   case AMDGPU::EXEC:
1189   case AMDGPU::FLAT_SCR:
1190     if (VT.getSizeInBits() == 64)
1191       return Reg;
1192     break;
1193   default:
1194     llvm_unreachable("missing register type checking");
1195   }
1196 
1197   report_fatal_error(Twine("invalid type for register \""
1198                            + StringRef(RegName) + "\"."));
1199 }
1200 
1201 // If kill is not the last instruction, split the block so kill is always a
1202 // proper terminator.
1203 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1204                                                     MachineBasicBlock *BB) const {
1205   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1206 
1207   MachineBasicBlock::iterator SplitPoint(&MI);
1208   ++SplitPoint;
1209 
1210   if (SplitPoint == BB->end()) {
1211     // Don't bother with a new block.
1212     MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1213     return BB;
1214   }
1215 
1216   MachineFunction *MF = BB->getParent();
1217   MachineBasicBlock *SplitBB
1218     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1219 
1220   MF->insert(++MachineFunction::iterator(BB), SplitBB);
1221   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1222 
1223   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1224   BB->addSuccessor(SplitBB);
1225 
1226   MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1227   return SplitBB;
1228 }
1229 
1230 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1231 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1232 // will only do one iteration. In the worst case, this will loop 64 times.
1233 //
1234 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1235 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1236   const SIInstrInfo *TII,
1237   MachineRegisterInfo &MRI,
1238   MachineBasicBlock &OrigBB,
1239   MachineBasicBlock &LoopBB,
1240   const DebugLoc &DL,
1241   const MachineOperand &IdxReg,
1242   unsigned InitReg,
1243   unsigned ResultReg,
1244   unsigned PhiReg,
1245   unsigned InitSaveExecReg,
1246   int Offset,
1247   bool UseGPRIdxMode) {
1248   MachineBasicBlock::iterator I = LoopBB.begin();
1249 
1250   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1251   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1252   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1253   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1254 
1255   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1256     .addReg(InitReg)
1257     .addMBB(&OrigBB)
1258     .addReg(ResultReg)
1259     .addMBB(&LoopBB);
1260 
1261   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1262     .addReg(InitSaveExecReg)
1263     .addMBB(&OrigBB)
1264     .addReg(NewExec)
1265     .addMBB(&LoopBB);
1266 
1267   // Read the next variant <- also loop target.
1268   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1269     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1270 
1271   // Compare the just read M0 value to all possible Idx values.
1272   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1273     .addReg(CurrentIdxReg)
1274     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1275 
1276   if (UseGPRIdxMode) {
1277     unsigned IdxReg;
1278     if (Offset == 0) {
1279       IdxReg = CurrentIdxReg;
1280     } else {
1281       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1282       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1283         .addReg(CurrentIdxReg, RegState::Kill)
1284         .addImm(Offset);
1285     }
1286 
1287     MachineInstr *SetIdx =
1288       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1289       .addReg(IdxReg, RegState::Kill);
1290     SetIdx->getOperand(2).setIsUndef();
1291   } else {
1292     // Move index from VCC into M0
1293     if (Offset == 0) {
1294       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1295         .addReg(CurrentIdxReg, RegState::Kill);
1296     } else {
1297       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1298         .addReg(CurrentIdxReg, RegState::Kill)
1299         .addImm(Offset);
1300     }
1301   }
1302 
1303   // Update EXEC, save the original EXEC value to VCC.
1304   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1305     .addReg(CondReg, RegState::Kill);
1306 
1307   MRI.setSimpleHint(NewExec, CondReg);
1308 
1309   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1310   MachineInstr *InsertPt =
1311     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1312     .addReg(AMDGPU::EXEC)
1313     .addReg(NewExec);
1314 
1315   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1316   // s_cbranch_scc0?
1317 
1318   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1319   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1320     .addMBB(&LoopBB);
1321 
1322   return InsertPt->getIterator();
1323 }
1324 
1325 // This has slightly sub-optimal regalloc when the source vector is killed by
1326 // the read. The register allocator does not understand that the kill is
1327 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1328 // subregister from it, using 1 more VGPR than necessary. This was saved when
1329 // this was expanded after register allocation.
1330 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1331                                                   MachineBasicBlock &MBB,
1332                                                   MachineInstr &MI,
1333                                                   unsigned InitResultReg,
1334                                                   unsigned PhiReg,
1335                                                   int Offset,
1336                                                   bool UseGPRIdxMode) {
1337   MachineFunction *MF = MBB.getParent();
1338   MachineRegisterInfo &MRI = MF->getRegInfo();
1339   const DebugLoc &DL = MI.getDebugLoc();
1340   MachineBasicBlock::iterator I(&MI);
1341 
1342   unsigned DstReg = MI.getOperand(0).getReg();
1343   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1344   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1345 
1346   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1347 
1348   // Save the EXEC mask
1349   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1350     .addReg(AMDGPU::EXEC);
1351 
1352   // To insert the loop we need to split the block. Move everything after this
1353   // point to a new block, and insert a new empty block between the two.
1354   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1355   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1356   MachineFunction::iterator MBBI(MBB);
1357   ++MBBI;
1358 
1359   MF->insert(MBBI, LoopBB);
1360   MF->insert(MBBI, RemainderBB);
1361 
1362   LoopBB->addSuccessor(LoopBB);
1363   LoopBB->addSuccessor(RemainderBB);
1364 
1365   // Move the rest of the block into a new block.
1366   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1367   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1368 
1369   MBB.addSuccessor(LoopBB);
1370 
1371   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1372 
1373   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1374                                       InitResultReg, DstReg, PhiReg, TmpExec,
1375                                       Offset, UseGPRIdxMode);
1376 
1377   MachineBasicBlock::iterator First = RemainderBB->begin();
1378   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1379     .addReg(SaveExec);
1380 
1381   return InsPt;
1382 }
1383 
1384 // Returns subreg index, offset
1385 static std::pair<unsigned, int>
1386 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1387                             const TargetRegisterClass *SuperRC,
1388                             unsigned VecReg,
1389                             int Offset) {
1390   int NumElts = SuperRC->getSize() / 4;
1391 
1392   // Skip out of bounds offsets, or else we would end up using an undefined
1393   // register.
1394   if (Offset >= NumElts || Offset < 0)
1395     return std::make_pair(AMDGPU::sub0, Offset);
1396 
1397   return std::make_pair(AMDGPU::sub0 + Offset, 0);
1398 }
1399 
1400 // Return true if the index is an SGPR and was set.
1401 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1402                                  MachineRegisterInfo &MRI,
1403                                  MachineInstr &MI,
1404                                  int Offset,
1405                                  bool UseGPRIdxMode,
1406                                  bool IsIndirectSrc) {
1407   MachineBasicBlock *MBB = MI.getParent();
1408   const DebugLoc &DL = MI.getDebugLoc();
1409   MachineBasicBlock::iterator I(&MI);
1410 
1411   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1412   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1413 
1414   assert(Idx->getReg() != AMDGPU::NoRegister);
1415 
1416   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1417     return false;
1418 
1419   if (UseGPRIdxMode) {
1420     unsigned IdxMode = IsIndirectSrc ?
1421       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1422     if (Offset == 0) {
1423       MachineInstr *SetOn =
1424         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1425         .addOperand(*Idx)
1426         .addImm(IdxMode);
1427 
1428       SetOn->getOperand(3).setIsUndef();
1429     } else {
1430       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1431       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1432         .addOperand(*Idx)
1433         .addImm(Offset);
1434       MachineInstr *SetOn =
1435         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1436         .addReg(Tmp, RegState::Kill)
1437         .addImm(IdxMode);
1438 
1439       SetOn->getOperand(3).setIsUndef();
1440     }
1441 
1442     return true;
1443   }
1444 
1445   if (Offset == 0) {
1446     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1447       .addOperand(*Idx);
1448   } else {
1449     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1450       .addOperand(*Idx)
1451       .addImm(Offset);
1452   }
1453 
1454   return true;
1455 }
1456 
1457 // Control flow needs to be inserted if indexing with a VGPR.
1458 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1459                                           MachineBasicBlock &MBB,
1460                                           const SISubtarget &ST) {
1461   const SIInstrInfo *TII = ST.getInstrInfo();
1462   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1463   MachineFunction *MF = MBB.getParent();
1464   MachineRegisterInfo &MRI = MF->getRegInfo();
1465 
1466   unsigned Dst = MI.getOperand(0).getReg();
1467   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1468   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1469 
1470   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1471 
1472   unsigned SubReg;
1473   std::tie(SubReg, Offset)
1474     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1475 
1476   bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1477 
1478   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1479     MachineBasicBlock::iterator I(&MI);
1480     const DebugLoc &DL = MI.getDebugLoc();
1481 
1482     if (UseGPRIdxMode) {
1483       // TODO: Look at the uses to avoid the copy. This may require rescheduling
1484       // to avoid interfering with other uses, so probably requires a new
1485       // optimization pass.
1486       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1487         .addReg(SrcReg, RegState::Undef, SubReg)
1488         .addReg(SrcReg, RegState::Implicit)
1489         .addReg(AMDGPU::M0, RegState::Implicit);
1490       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1491     } else {
1492       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1493         .addReg(SrcReg, RegState::Undef, SubReg)
1494         .addReg(SrcReg, RegState::Implicit);
1495     }
1496 
1497     MI.eraseFromParent();
1498 
1499     return &MBB;
1500   }
1501 
1502 
1503   const DebugLoc &DL = MI.getDebugLoc();
1504   MachineBasicBlock::iterator I(&MI);
1505 
1506   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1507   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1508 
1509   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1510 
1511   if (UseGPRIdxMode) {
1512     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1513       .addImm(0) // Reset inside loop.
1514       .addImm(VGPRIndexMode::SRC0_ENABLE);
1515     SetOn->getOperand(3).setIsUndef();
1516 
1517     // Disable again after the loop.
1518     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1519   }
1520 
1521   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1522   MachineBasicBlock *LoopBB = InsPt->getParent();
1523 
1524   if (UseGPRIdxMode) {
1525     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1526       .addReg(SrcReg, RegState::Undef, SubReg)
1527       .addReg(SrcReg, RegState::Implicit)
1528       .addReg(AMDGPU::M0, RegState::Implicit);
1529   } else {
1530     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1531       .addReg(SrcReg, RegState::Undef, SubReg)
1532       .addReg(SrcReg, RegState::Implicit);
1533   }
1534 
1535   MI.eraseFromParent();
1536 
1537   return LoopBB;
1538 }
1539 
1540 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1541   switch (VecRC->getSize()) {
1542   case 4:
1543     return AMDGPU::V_MOVRELD_B32_V1;
1544   case 8:
1545     return AMDGPU::V_MOVRELD_B32_V2;
1546   case 16:
1547     return AMDGPU::V_MOVRELD_B32_V4;
1548   case 32:
1549     return AMDGPU::V_MOVRELD_B32_V8;
1550   case 64:
1551     return AMDGPU::V_MOVRELD_B32_V16;
1552   default:
1553     llvm_unreachable("unsupported size for MOVRELD pseudos");
1554   }
1555 }
1556 
1557 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1558                                           MachineBasicBlock &MBB,
1559                                           const SISubtarget &ST) {
1560   const SIInstrInfo *TII = ST.getInstrInfo();
1561   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1562   MachineFunction *MF = MBB.getParent();
1563   MachineRegisterInfo &MRI = MF->getRegInfo();
1564 
1565   unsigned Dst = MI.getOperand(0).getReg();
1566   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1567   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1568   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1569   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1570   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1571 
1572   // This can be an immediate, but will be folded later.
1573   assert(Val->getReg());
1574 
1575   unsigned SubReg;
1576   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1577                                                          SrcVec->getReg(),
1578                                                          Offset);
1579   bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1580 
1581   if (Idx->getReg() == AMDGPU::NoRegister) {
1582     MachineBasicBlock::iterator I(&MI);
1583     const DebugLoc &DL = MI.getDebugLoc();
1584 
1585     assert(Offset == 0);
1586 
1587     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1588       .addOperand(*SrcVec)
1589       .addOperand(*Val)
1590       .addImm(SubReg);
1591 
1592     MI.eraseFromParent();
1593     return &MBB;
1594   }
1595 
1596   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1597     MachineBasicBlock::iterator I(&MI);
1598     const DebugLoc &DL = MI.getDebugLoc();
1599 
1600     if (UseGPRIdxMode) {
1601       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1602         .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1603         .addOperand(*Val)
1604         .addReg(Dst, RegState::ImplicitDefine)
1605         .addReg(SrcVec->getReg(), RegState::Implicit)
1606         .addReg(AMDGPU::M0, RegState::Implicit);
1607 
1608       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1609     } else {
1610       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1611 
1612       BuildMI(MBB, I, DL, MovRelDesc)
1613           .addReg(Dst, RegState::Define)
1614           .addReg(SrcVec->getReg())
1615           .addOperand(*Val)
1616           .addImm(SubReg - AMDGPU::sub0);
1617     }
1618 
1619     MI.eraseFromParent();
1620     return &MBB;
1621   }
1622 
1623   if (Val->isReg())
1624     MRI.clearKillFlags(Val->getReg());
1625 
1626   const DebugLoc &DL = MI.getDebugLoc();
1627 
1628   if (UseGPRIdxMode) {
1629     MachineBasicBlock::iterator I(&MI);
1630 
1631     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1632       .addImm(0) // Reset inside loop.
1633       .addImm(VGPRIndexMode::DST_ENABLE);
1634     SetOn->getOperand(3).setIsUndef();
1635 
1636     // Disable again after the loop.
1637     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1638   }
1639 
1640   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1641 
1642   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1643                               Offset, UseGPRIdxMode);
1644   MachineBasicBlock *LoopBB = InsPt->getParent();
1645 
1646   if (UseGPRIdxMode) {
1647     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1648       .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1649       .addOperand(*Val) // src0
1650       .addReg(Dst, RegState::ImplicitDefine)
1651       .addReg(PhiReg, RegState::Implicit)
1652       .addReg(AMDGPU::M0, RegState::Implicit);
1653   } else {
1654     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1655 
1656     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1657         .addReg(Dst, RegState::Define)
1658         .addReg(PhiReg)
1659         .addOperand(*Val)
1660         .addImm(SubReg - AMDGPU::sub0);
1661   }
1662 
1663   MI.eraseFromParent();
1664 
1665   return LoopBB;
1666 }
1667 
1668 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1669   MachineInstr &MI, MachineBasicBlock *BB) const {
1670   switch (MI.getOpcode()) {
1671   case AMDGPU::SI_INIT_M0: {
1672     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1673     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1674             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1675       .addOperand(MI.getOperand(0));
1676     MI.eraseFromParent();
1677     return BB;
1678   }
1679   case AMDGPU::GET_GROUPSTATICSIZE: {
1680     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1681 
1682     MachineFunction *MF = BB->getParent();
1683     SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1684     DebugLoc DL = MI.getDebugLoc();
1685     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1686       .addOperand(MI.getOperand(0))
1687       .addImm(MFI->getLDSSize());
1688     MI.eraseFromParent();
1689     return BB;
1690   }
1691   case AMDGPU::SI_INDIRECT_SRC_V1:
1692   case AMDGPU::SI_INDIRECT_SRC_V2:
1693   case AMDGPU::SI_INDIRECT_SRC_V4:
1694   case AMDGPU::SI_INDIRECT_SRC_V8:
1695   case AMDGPU::SI_INDIRECT_SRC_V16:
1696     return emitIndirectSrc(MI, *BB, *getSubtarget());
1697   case AMDGPU::SI_INDIRECT_DST_V1:
1698   case AMDGPU::SI_INDIRECT_DST_V2:
1699   case AMDGPU::SI_INDIRECT_DST_V4:
1700   case AMDGPU::SI_INDIRECT_DST_V8:
1701   case AMDGPU::SI_INDIRECT_DST_V16:
1702     return emitIndirectDst(MI, *BB, *getSubtarget());
1703   case AMDGPU::SI_KILL:
1704     return splitKillBlock(MI, BB);
1705   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1706     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1707     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1708 
1709     unsigned Dst = MI.getOperand(0).getReg();
1710     unsigned Src0 = MI.getOperand(1).getReg();
1711     unsigned Src1 = MI.getOperand(2).getReg();
1712     const DebugLoc &DL = MI.getDebugLoc();
1713     unsigned SrcCond = MI.getOperand(3).getReg();
1714 
1715     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1716     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1717 
1718     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1719       .addReg(Src0, 0, AMDGPU::sub0)
1720       .addReg(Src1, 0, AMDGPU::sub0)
1721       .addReg(SrcCond);
1722     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1723       .addReg(Src0, 0, AMDGPU::sub1)
1724       .addReg(Src1, 0, AMDGPU::sub1)
1725       .addReg(SrcCond);
1726 
1727     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
1728       .addReg(DstLo)
1729       .addImm(AMDGPU::sub0)
1730       .addReg(DstHi)
1731       .addImm(AMDGPU::sub1);
1732     MI.eraseFromParent();
1733     return BB;
1734   }
1735   default:
1736     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1737   }
1738 }
1739 
1740 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1741   // This currently forces unfolding various combinations of fsub into fma with
1742   // free fneg'd operands. As long as we have fast FMA (controlled by
1743   // isFMAFasterThanFMulAndFAdd), we should perform these.
1744 
1745   // When fma is quarter rate, for f64 where add / sub are at best half rate,
1746   // most of these combines appear to be cycle neutral but save on instruction
1747   // count / code size.
1748   return true;
1749 }
1750 
1751 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
1752                                          EVT VT) const {
1753   if (!VT.isVector()) {
1754     return MVT::i1;
1755   }
1756   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1757 }
1758 
1759 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
1760   return MVT::i32;
1761 }
1762 
1763 // Answering this is somewhat tricky and depends on the specific device which
1764 // have different rates for fma or all f64 operations.
1765 //
1766 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1767 // regardless of which device (although the number of cycles differs between
1768 // devices), so it is always profitable for f64.
1769 //
1770 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1771 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1772 // which we can always do even without fused FP ops since it returns the same
1773 // result as the separate operations and since it is always full
1774 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1775 // however does not support denormals, so we do report fma as faster if we have
1776 // a fast fma device and require denormals.
1777 //
1778 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1779   VT = VT.getScalarType();
1780 
1781   if (!VT.isSimple())
1782     return false;
1783 
1784   switch (VT.getSimpleVT().SimpleTy) {
1785   case MVT::f32:
1786     // This is as fast on some subtargets. However, we always have full rate f32
1787     // mad available which returns the same result as the separate operations
1788     // which we should prefer over fma. We can't use this if we want to support
1789     // denormals, so only report this in these cases.
1790     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1791   case MVT::f64:
1792     return true;
1793   default:
1794     break;
1795   }
1796 
1797   return false;
1798 }
1799 
1800 //===----------------------------------------------------------------------===//
1801 // Custom DAG Lowering Operations
1802 //===----------------------------------------------------------------------===//
1803 
1804 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1805   switch (Op.getOpcode()) {
1806   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1807   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1808   case ISD::LOAD: {
1809     SDValue Result = LowerLOAD(Op, DAG);
1810     assert((!Result.getNode() ||
1811             Result.getNode()->getNumValues() == 2) &&
1812            "Load should return a value and a chain");
1813     return Result;
1814   }
1815 
1816   case ISD::FSIN:
1817   case ISD::FCOS:
1818     return LowerTrig(Op, DAG);
1819   case ISD::SELECT: return LowerSELECT(Op, DAG);
1820   case ISD::FDIV: return LowerFDIV(Op, DAG);
1821   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
1822   case ISD::STORE: return LowerSTORE(Op, DAG);
1823   case ISD::GlobalAddress: {
1824     MachineFunction &MF = DAG.getMachineFunction();
1825     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1826     return LowerGlobalAddress(MFI, Op, DAG);
1827   }
1828   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1829   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1830   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1831   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
1832   case ISD::TRAP: return lowerTRAP(Op, DAG);
1833 
1834   case ISD::ConstantFP:
1835     return lowerConstantFP(Op, DAG);
1836   case ISD::FP_ROUND:
1837     return lowerFP_ROUND(Op, DAG);
1838   }
1839   return SDValue();
1840 }
1841 
1842 /// \brief Helper function for LowerBRCOND
1843 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1844 
1845   SDNode *Parent = Value.getNode();
1846   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1847        I != E; ++I) {
1848 
1849     if (I.getUse().get() != Value)
1850       continue;
1851 
1852     if (I->getOpcode() == Opcode)
1853       return *I;
1854   }
1855   return nullptr;
1856 }
1857 
1858 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
1859   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
1860     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
1861     case AMDGPUIntrinsic::amdgcn_if:
1862     case AMDGPUIntrinsic::amdgcn_else:
1863     case AMDGPUIntrinsic::amdgcn_end_cf:
1864     case AMDGPUIntrinsic::amdgcn_loop:
1865       return true;
1866     default:
1867       return false;
1868     }
1869   }
1870 
1871   if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
1872     switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) {
1873     case AMDGPUIntrinsic::amdgcn_break:
1874     case AMDGPUIntrinsic::amdgcn_if_break:
1875     case AMDGPUIntrinsic::amdgcn_else_break:
1876       return true;
1877     default:
1878       return false;
1879     }
1880   }
1881 
1882   return false;
1883 }
1884 
1885 void SITargetLowering::createDebuggerPrologueStackObjects(
1886     MachineFunction &MF) const {
1887   // Create stack objects that are used for emitting debugger prologue.
1888   //
1889   // Debugger prologue writes work group IDs and work item IDs to scratch memory
1890   // at fixed location in the following format:
1891   //   offset 0:  work group ID x
1892   //   offset 4:  work group ID y
1893   //   offset 8:  work group ID z
1894   //   offset 16: work item ID x
1895   //   offset 20: work item ID y
1896   //   offset 24: work item ID z
1897   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1898   int ObjectIdx = 0;
1899 
1900   // For each dimension:
1901   for (unsigned i = 0; i < 3; ++i) {
1902     // Create fixed stack object for work group ID.
1903     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
1904     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
1905     // Create fixed stack object for work item ID.
1906     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
1907     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
1908   }
1909 }
1910 
1911 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
1912   const Triple &TT = getTargetMachine().getTargetTriple();
1913   return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1914          AMDGPU::shouldEmitConstantsToTextSection(TT);
1915 }
1916 
1917 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
1918   return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
1919               GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
1920          !shouldEmitFixup(GV) &&
1921          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1922 }
1923 
1924 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
1925   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
1926 }
1927 
1928 /// This transforms the control flow intrinsics to get the branch destination as
1929 /// last parameter, also switches branch target with BR if the need arise
1930 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1931                                       SelectionDAG &DAG) const {
1932 
1933   SDLoc DL(BRCOND);
1934 
1935   SDNode *Intr = BRCOND.getOperand(1).getNode();
1936   SDValue Target = BRCOND.getOperand(2);
1937   SDNode *BR = nullptr;
1938   SDNode *SetCC = nullptr;
1939 
1940   if (Intr->getOpcode() == ISD::SETCC) {
1941     // As long as we negate the condition everything is fine
1942     SetCC = Intr;
1943     Intr = SetCC->getOperand(0).getNode();
1944 
1945   } else {
1946     // Get the target from BR if we don't negate the condition
1947     BR = findUser(BRCOND, ISD::BR);
1948     Target = BR->getOperand(1);
1949   }
1950 
1951   // FIXME: This changes the types of the intrinsics instead of introducing new
1952   // nodes with the correct types.
1953   // e.g. llvm.amdgcn.loop
1954 
1955   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
1956   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
1957 
1958   if (!isCFIntrinsic(Intr)) {
1959     // This is a uniform branch so we don't need to legalize.
1960     return BRCOND;
1961   }
1962 
1963   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
1964                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
1965 
1966   assert(!SetCC ||
1967         (SetCC->getConstantOperandVal(1) == 1 &&
1968          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1969                                                              ISD::SETNE));
1970 
1971   // operands of the new intrinsic call
1972   SmallVector<SDValue, 4> Ops;
1973   if (HaveChain)
1974     Ops.push_back(BRCOND.getOperand(0));
1975 
1976   Ops.append(Intr->op_begin() + (HaveChain ?  1 : 0), Intr->op_end());
1977   Ops.push_back(Target);
1978 
1979   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1980 
1981   // build the new intrinsic call
1982   SDNode *Result = DAG.getNode(
1983     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1984     DAG.getVTList(Res), Ops).getNode();
1985 
1986   if (!HaveChain) {
1987     SDValue Ops[] =  {
1988       SDValue(Result, 0),
1989       BRCOND.getOperand(0)
1990     };
1991 
1992     Result = DAG.getMergeValues(Ops, DL).getNode();
1993   }
1994 
1995   if (BR) {
1996     // Give the branch instruction our target
1997     SDValue Ops[] = {
1998       BR->getOperand(0),
1999       BRCOND.getOperand(2)
2000     };
2001     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2002     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2003     BR = NewBR.getNode();
2004   }
2005 
2006   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2007 
2008   // Copy the intrinsic results to registers
2009   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2010     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2011     if (!CopyToReg)
2012       continue;
2013 
2014     Chain = DAG.getCopyToReg(
2015       Chain, DL,
2016       CopyToReg->getOperand(1),
2017       SDValue(Result, i - 1),
2018       SDValue());
2019 
2020     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2021   }
2022 
2023   // Remove the old intrinsic from the chain
2024   DAG.ReplaceAllUsesOfValueWith(
2025     SDValue(Intr, Intr->getNumValues() - 1),
2026     Intr->getOperand(0));
2027 
2028   return Chain;
2029 }
2030 
2031 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2032                                             SDValue Op,
2033                                             const SDLoc &DL,
2034                                             EVT VT) const {
2035   return Op.getValueType().bitsLE(VT) ?
2036       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2037       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2038 }
2039 
2040 SDValue SITargetLowering::lowerConstantFP(SDValue Op, SelectionDAG &DAG) const {
2041   if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(Op)) {
2042     return DAG.getConstant(FP->getValueAPF().bitcastToAPInt().getZExtValue(),
2043                            SDLoc(Op), MVT::i32);
2044   }
2045 
2046   return SDValue();
2047 }
2048 
2049 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2050   assert(Op.getValueType() == MVT::f16 &&
2051          "Do not know how to custom lower FP_ROUND for non-f16 type");
2052 
2053   SDValue Src = Op.getOperand(0);
2054   EVT SrcVT = Src.getValueType();
2055   if (SrcVT != MVT::f64)
2056     return Op;
2057 
2058   SDLoc DL(Op);
2059 
2060   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2061   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2062   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2063 }
2064 
2065 SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2066                                              SelectionDAG &DAG) const {
2067   SDLoc SL;
2068   MachineFunction &MF = DAG.getMachineFunction();
2069   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2070   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2071   assert(UserSGPR != AMDGPU::NoRegister);
2072 
2073   SDValue QueuePtr = CreateLiveInRegister(
2074     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2075 
2076   // Offset into amd_queue_t for group_segment_aperture_base_hi /
2077   // private_segment_aperture_base_hi.
2078   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2079 
2080   SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2081                             DAG.getConstant(StructOffset, SL, MVT::i64));
2082 
2083   // TODO: Use custom target PseudoSourceValue.
2084   // TODO: We should use the value from the IR intrinsic call, but it might not
2085   // be available and how do we get it?
2086   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2087                                               AMDGPUAS::CONSTANT_ADDRESS));
2088 
2089   MachinePointerInfo PtrInfo(V, StructOffset);
2090   return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2091                      MinAlign(64, StructOffset),
2092                      MachineMemOperand::MODereferenceable |
2093                          MachineMemOperand::MOInvariant);
2094 }
2095 
2096 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2097                                              SelectionDAG &DAG) const {
2098   SDLoc SL(Op);
2099   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2100 
2101   SDValue Src = ASC->getOperand(0);
2102 
2103   // FIXME: Really support non-0 null pointers.
2104   SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32);
2105   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2106 
2107   // flat -> local/private
2108   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2109     if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2110         ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2111       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2112       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2113 
2114       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2115                          NonNull, Ptr, SegmentNullPtr);
2116     }
2117   }
2118 
2119   // local/private -> flat
2120   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2121     if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2122         ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2123       SDValue NonNull
2124         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2125 
2126       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2127       SDValue CvtPtr
2128         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2129 
2130       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2131                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2132                          FlatNullPtr);
2133     }
2134   }
2135 
2136   // global <-> flat are no-ops and never emitted.
2137 
2138   const MachineFunction &MF = DAG.getMachineFunction();
2139   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2140     *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2141   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2142 
2143   return DAG.getUNDEF(ASC->getValueType(0));
2144 }
2145 
2146 bool
2147 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2148   // We can fold offsets for anything that doesn't require a GOT relocation.
2149   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2150               GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2151          !shouldEmitGOTReloc(GA->getGlobal());
2152 }
2153 
2154 static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2155                                       SDLoc DL, unsigned Offset, EVT PtrVT,
2156                                       unsigned GAFlags = SIInstrInfo::MO_NONE) {
2157   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2158   // lowered to the following code sequence:
2159   //
2160   // For constant address space:
2161   //   s_getpc_b64 s[0:1]
2162   //   s_add_u32 s0, s0, $symbol
2163   //   s_addc_u32 s1, s1, 0
2164   //
2165   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2166   //   a fixup or relocation is emitted to replace $symbol with a literal
2167   //   constant, which is a pc-relative offset from the encoding of the $symbol
2168   //   operand to the global variable.
2169   //
2170   // For global address space:
2171   //   s_getpc_b64 s[0:1]
2172   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2173   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2174   //
2175   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2176   //   fixups or relocations are emitted to replace $symbol@*@lo and
2177   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2178   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
2179   //   operand to the global variable.
2180   //
2181   // What we want here is an offset from the value returned by s_getpc
2182   // (which is the address of the s_add_u32 instruction) to the global
2183   // variable, but since the encoding of $symbol starts 4 bytes after the start
2184   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2185   // small. This requires us to add 4 to the global variable offset in order to
2186   // compute the correct address.
2187   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2188                                              GAFlags);
2189   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2190                                              GAFlags == SIInstrInfo::MO_NONE ?
2191                                              GAFlags : GAFlags + 1);
2192   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2193 }
2194 
2195 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2196                                              SDValue Op,
2197                                              SelectionDAG &DAG) const {
2198   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2199 
2200   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
2201       GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
2202     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2203 
2204   SDLoc DL(GSD);
2205   const GlobalValue *GV = GSD->getGlobal();
2206   EVT PtrVT = Op.getValueType();
2207 
2208   if (shouldEmitFixup(GV))
2209     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2210   else if (shouldEmitPCReloc(GV))
2211     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2212                                    SIInstrInfo::MO_REL32);
2213 
2214   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2215                                             SIInstrInfo::MO_GOTPCREL32);
2216 
2217   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2218   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
2219   const DataLayout &DataLayout = DAG.getDataLayout();
2220   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2221   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2222   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2223 
2224   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2225                      MachineMemOperand::MODereferenceable |
2226                          MachineMemOperand::MOInvariant);
2227 }
2228 
2229 SDValue SITargetLowering::lowerTRAP(SDValue Op,
2230                                     SelectionDAG &DAG) const {
2231   const MachineFunction &MF = DAG.getMachineFunction();
2232   DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2233                                    "trap handler not supported",
2234                                    Op.getDebugLoc(),
2235                                    DS_Warning);
2236   DAG.getContext()->diagnose(NoTrap);
2237 
2238   // Emit s_endpgm.
2239 
2240   // FIXME: This should really be selected to s_trap, but that requires
2241   // setting up the trap handler for it o do anything.
2242   return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other,
2243                      Op.getOperand(0));
2244 }
2245 
2246 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2247                                    const SDLoc &DL, SDValue V) const {
2248   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2249   // the destination register.
2250   //
2251   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2252   // so we will end up with redundant moves to m0.
2253   //
2254   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2255 
2256   // A Null SDValue creates a glue result.
2257   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2258                                   V, Chain);
2259   return SDValue(M0, 0);
2260 }
2261 
2262 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2263                                                  SDValue Op,
2264                                                  MVT VT,
2265                                                  unsigned Offset) const {
2266   SDLoc SL(Op);
2267   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2268                                  DAG.getEntryNode(), Offset, false);
2269   // The local size values will have the hi 16-bits as zero.
2270   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2271                      DAG.getValueType(VT));
2272 }
2273 
2274 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2275   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2276                                       "non-hsa intrinsic with hsa target",
2277                                       DL.getDebugLoc());
2278   DAG.getContext()->diagnose(BadIntrin);
2279   return DAG.getUNDEF(VT);
2280 }
2281 
2282 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2283   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2284                                       "intrinsic not supported on subtarget",
2285                                       DL.getDebugLoc());
2286   DAG.getContext()->diagnose(BadIntrin);
2287   return DAG.getUNDEF(VT);
2288 }
2289 
2290 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2291                                                   SelectionDAG &DAG) const {
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2294   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2295 
2296   EVT VT = Op.getValueType();
2297   SDLoc DL(Op);
2298   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2299 
2300   // TODO: Should this propagate fast-math-flags?
2301 
2302   switch (IntrinsicID) {
2303   case Intrinsic::amdgcn_dispatch_ptr:
2304   case Intrinsic::amdgcn_queue_ptr: {
2305     if (!Subtarget->isAmdCodeObjectV2()) {
2306       DiagnosticInfoUnsupported BadIntrin(
2307           *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2308           DL.getDebugLoc());
2309       DAG.getContext()->diagnose(BadIntrin);
2310       return DAG.getUNDEF(VT);
2311     }
2312 
2313     auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2314       SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2315     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2316                                 TRI->getPreloadedValue(MF, Reg), VT);
2317   }
2318   case Intrinsic::amdgcn_implicitarg_ptr: {
2319     unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2320     return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2321   }
2322   case Intrinsic::amdgcn_kernarg_segment_ptr: {
2323     unsigned Reg
2324       = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2325     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2326   }
2327   case Intrinsic::amdgcn_dispatch_id: {
2328     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2329     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2330   }
2331   case Intrinsic::amdgcn_rcp:
2332     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2333   case Intrinsic::amdgcn_rsq:
2334   case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name
2335     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2336   case Intrinsic::amdgcn_rsq_legacy: {
2337     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2338       return emitRemovedIntrinsicError(DAG, DL, VT);
2339 
2340     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2341   }
2342   case Intrinsic::amdgcn_rcp_legacy: {
2343     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2344       return emitRemovedIntrinsicError(DAG, DL, VT);
2345     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2346   }
2347   case Intrinsic::amdgcn_rsq_clamp: {
2348     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2349       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2350 
2351     Type *Type = VT.getTypeForEVT(*DAG.getContext());
2352     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2353     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2354 
2355     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2356     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2357                               DAG.getConstantFP(Max, DL, VT));
2358     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2359                        DAG.getConstantFP(Min, DL, VT));
2360   }
2361   case Intrinsic::r600_read_ngroups_x:
2362     if (Subtarget->isAmdHsaOS())
2363       return emitNonHSAIntrinsicError(DAG, DL, VT);
2364 
2365     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2366                           SI::KernelInputOffsets::NGROUPS_X, false);
2367   case Intrinsic::r600_read_ngroups_y:
2368     if (Subtarget->isAmdHsaOS())
2369       return emitNonHSAIntrinsicError(DAG, DL, VT);
2370 
2371     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2372                           SI::KernelInputOffsets::NGROUPS_Y, false);
2373   case Intrinsic::r600_read_ngroups_z:
2374     if (Subtarget->isAmdHsaOS())
2375       return emitNonHSAIntrinsicError(DAG, DL, VT);
2376 
2377     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2378                           SI::KernelInputOffsets::NGROUPS_Z, false);
2379   case Intrinsic::r600_read_global_size_x:
2380     if (Subtarget->isAmdHsaOS())
2381       return emitNonHSAIntrinsicError(DAG, DL, VT);
2382 
2383     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2384                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2385   case Intrinsic::r600_read_global_size_y:
2386     if (Subtarget->isAmdHsaOS())
2387       return emitNonHSAIntrinsicError(DAG, DL, VT);
2388 
2389     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2390                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2391   case Intrinsic::r600_read_global_size_z:
2392     if (Subtarget->isAmdHsaOS())
2393       return emitNonHSAIntrinsicError(DAG, DL, VT);
2394 
2395     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2396                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2397   case Intrinsic::r600_read_local_size_x:
2398     if (Subtarget->isAmdHsaOS())
2399       return emitNonHSAIntrinsicError(DAG, DL, VT);
2400 
2401     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2402                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
2403   case Intrinsic::r600_read_local_size_y:
2404     if (Subtarget->isAmdHsaOS())
2405       return emitNonHSAIntrinsicError(DAG, DL, VT);
2406 
2407     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2408                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
2409   case Intrinsic::r600_read_local_size_z:
2410     if (Subtarget->isAmdHsaOS())
2411       return emitNonHSAIntrinsicError(DAG, DL, VT);
2412 
2413     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2414                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
2415   case Intrinsic::amdgcn_workgroup_id_x:
2416   case Intrinsic::r600_read_tgid_x:
2417     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2418       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2419   case Intrinsic::amdgcn_workgroup_id_y:
2420   case Intrinsic::r600_read_tgid_y:
2421     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2422       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2423   case Intrinsic::amdgcn_workgroup_id_z:
2424   case Intrinsic::r600_read_tgid_z:
2425     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2426       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2427   case Intrinsic::amdgcn_workitem_id_x:
2428   case Intrinsic::r600_read_tidig_x:
2429     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2430       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2431   case Intrinsic::amdgcn_workitem_id_y:
2432   case Intrinsic::r600_read_tidig_y:
2433     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2434       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2435   case Intrinsic::amdgcn_workitem_id_z:
2436   case Intrinsic::r600_read_tidig_z:
2437     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2438       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2439   case AMDGPUIntrinsic::SI_load_const: {
2440     SDValue Ops[] = {
2441       Op.getOperand(1),
2442       Op.getOperand(2)
2443     };
2444 
2445     MachineMemOperand *MMO = MF.getMachineMemOperand(
2446         MachinePointerInfo(),
2447         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2448             MachineMemOperand::MOInvariant,
2449         VT.getStoreSize(), 4);
2450     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2451                                    Op->getVTList(), Ops, VT, MMO);
2452   }
2453   case AMDGPUIntrinsic::amdgcn_fdiv_fast: {
2454     return lowerFDIV_FAST(Op, DAG);
2455   }
2456   case AMDGPUIntrinsic::SI_vs_load_input:
2457     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
2458                        Op.getOperand(1),
2459                        Op.getOperand(2),
2460                        Op.getOperand(3));
2461 
2462   case AMDGPUIntrinsic::SI_fs_constant: {
2463     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2464     SDValue Glue = M0.getValue(1);
2465     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
2466                        DAG.getConstant(2, DL, MVT::i32), // P0
2467                        Op.getOperand(1), Op.getOperand(2), Glue);
2468   }
2469   case AMDGPUIntrinsic::SI_packf16:
2470     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
2471       return DAG.getUNDEF(MVT::i32);
2472     return Op;
2473   case AMDGPUIntrinsic::SI_fs_interp: {
2474     SDValue IJ = Op.getOperand(4);
2475     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2476                             DAG.getConstant(0, DL, MVT::i32));
2477     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2478                             DAG.getConstant(1, DL, MVT::i32));
2479     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2480     SDValue Glue = M0.getValue(1);
2481     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
2482                              DAG.getVTList(MVT::f32, MVT::Glue),
2483                              I, Op.getOperand(1), Op.getOperand(2), Glue);
2484     Glue = SDValue(P1.getNode(), 1);
2485     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
2486                              Op.getOperand(1), Op.getOperand(2), Glue);
2487   }
2488   case Intrinsic::amdgcn_interp_p1: {
2489     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2490     SDValue Glue = M0.getValue(1);
2491     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2492                        Op.getOperand(2), Op.getOperand(3), Glue);
2493   }
2494   case Intrinsic::amdgcn_interp_p2: {
2495     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2496     SDValue Glue = SDValue(M0.getNode(), 1);
2497     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2498                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2499                        Glue);
2500   }
2501   case Intrinsic::amdgcn_sin:
2502     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2503 
2504   case Intrinsic::amdgcn_cos:
2505     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2506 
2507   case Intrinsic::amdgcn_log_clamp: {
2508     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2509       return SDValue();
2510 
2511     DiagnosticInfoUnsupported BadIntrin(
2512       *MF.getFunction(), "intrinsic not supported on subtarget",
2513       DL.getDebugLoc());
2514       DAG.getContext()->diagnose(BadIntrin);
2515       return DAG.getUNDEF(VT);
2516   }
2517   case Intrinsic::amdgcn_ldexp:
2518     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2519                        Op.getOperand(1), Op.getOperand(2));
2520 
2521   case Intrinsic::amdgcn_fract:
2522     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2523 
2524   case Intrinsic::amdgcn_class:
2525     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2526                        Op.getOperand(1), Op.getOperand(2));
2527   case Intrinsic::amdgcn_div_fmas:
2528     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2529                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2530                        Op.getOperand(4));
2531 
2532   case Intrinsic::amdgcn_div_fixup:
2533     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2534                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2535 
2536   case Intrinsic::amdgcn_trig_preop:
2537     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2538                        Op.getOperand(1), Op.getOperand(2));
2539   case Intrinsic::amdgcn_div_scale: {
2540     // 3rd parameter required to be a constant.
2541     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2542     if (!Param)
2543       return DAG.getUNDEF(VT);
2544 
2545     // Translate to the operands expected by the machine instruction. The
2546     // first parameter must be the same as the first instruction.
2547     SDValue Numerator = Op.getOperand(1);
2548     SDValue Denominator = Op.getOperand(2);
2549 
2550     // Note this order is opposite of the machine instruction's operations,
2551     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2552     // intrinsic has the numerator as the first operand to match a normal
2553     // division operation.
2554 
2555     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2556 
2557     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2558                        Denominator, Numerator);
2559   }
2560   case Intrinsic::amdgcn_icmp: {
2561     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2562     int CondCode = CD->getSExtValue();
2563 
2564     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2565         CondCode >= ICmpInst::Predicate::BAD_ICMP_PREDICATE)
2566       return DAG.getUNDEF(VT);
2567 
2568     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2569     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2570     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2571                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2572   }
2573   case Intrinsic::amdgcn_fcmp: {
2574     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2575     int CondCode = CD->getSExtValue();
2576 
2577     if (CondCode <= FCmpInst::Predicate::FCMP_FALSE ||
2578         CondCode >= FCmpInst::Predicate::FCMP_TRUE)
2579       return DAG.getUNDEF(VT);
2580 
2581     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2582     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2583     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2584                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2585   }
2586   case Intrinsic::amdgcn_fmul_legacy:
2587     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2588                        Op.getOperand(1), Op.getOperand(2));
2589   case Intrinsic::amdgcn_sffbh:
2590   case AMDGPUIntrinsic::AMDGPU_flbit_i32: // Legacy name.
2591     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2592   default:
2593     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2594   }
2595 }
2596 
2597 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2598                                                  SelectionDAG &DAG) const {
2599   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2600   switch (IntrID) {
2601   case Intrinsic::amdgcn_atomic_inc:
2602   case Intrinsic::amdgcn_atomic_dec: {
2603     MemSDNode *M = cast<MemSDNode>(Op);
2604     unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2605       AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2606     SDValue Ops[] = {
2607       M->getOperand(0), // Chain
2608       M->getOperand(2), // Ptr
2609       M->getOperand(3)  // Value
2610     };
2611 
2612     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2613                                    M->getMemoryVT(), M->getMemOperand());
2614   }
2615   default:
2616     return SDValue();
2617   }
2618 }
2619 
2620 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
2621                                               SelectionDAG &DAG) const {
2622   MachineFunction &MF = DAG.getMachineFunction();
2623   SDLoc DL(Op);
2624   SDValue Chain = Op.getOperand(0);
2625   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2626 
2627   switch (IntrinsicID) {
2628   case AMDGPUIntrinsic::SI_sendmsg: {
2629     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
2630     SDValue Glue = Chain.getValue(1);
2631     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
2632                        Op.getOperand(2), Glue);
2633   }
2634   case AMDGPUIntrinsic::SI_tbuffer_store: {
2635     SDValue Ops[] = {
2636       Chain,
2637       Op.getOperand(2),
2638       Op.getOperand(3),
2639       Op.getOperand(4),
2640       Op.getOperand(5),
2641       Op.getOperand(6),
2642       Op.getOperand(7),
2643       Op.getOperand(8),
2644       Op.getOperand(9),
2645       Op.getOperand(10),
2646       Op.getOperand(11),
2647       Op.getOperand(12),
2648       Op.getOperand(13),
2649       Op.getOperand(14)
2650     };
2651 
2652     EVT VT = Op.getOperand(3).getValueType();
2653 
2654     MachineMemOperand *MMO = MF.getMachineMemOperand(
2655       MachinePointerInfo(),
2656       MachineMemOperand::MOStore,
2657       VT.getStoreSize(), 4);
2658     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
2659                                    Op->getVTList(), Ops, VT, MMO);
2660   }
2661   case AMDGPUIntrinsic::AMDGPU_kill: {
2662     SDValue Src = Op.getOperand(2);
2663     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
2664       if (!K->isNegative())
2665         return Chain;
2666 
2667       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
2668       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
2669     }
2670 
2671     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
2672     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
2673   }
2674   default:
2675     return SDValue();
2676   }
2677 }
2678 
2679 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2680   SDLoc DL(Op);
2681   LoadSDNode *Load = cast<LoadSDNode>(Op);
2682   ISD::LoadExtType ExtType = Load->getExtensionType();
2683   EVT MemVT = Load->getMemoryVT();
2684 
2685   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
2686     // FIXME: Copied from PPC
2687     // First, load into 32 bits, then truncate to 1 bit.
2688 
2689     SDValue Chain = Load->getChain();
2690     SDValue BasePtr = Load->getBasePtr();
2691     MachineMemOperand *MMO = Load->getMemOperand();
2692 
2693     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
2694 
2695     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
2696                                    BasePtr, RealMemVT, MMO);
2697 
2698     SDValue Ops[] = {
2699       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
2700       NewLD.getValue(1)
2701     };
2702 
2703     return DAG.getMergeValues(Ops, DL);
2704   }
2705 
2706   if (!MemVT.isVector())
2707     return SDValue();
2708 
2709   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
2710          "Custom lowering for non-i32 vectors hasn't been implemented.");
2711 
2712   unsigned AS = Load->getAddressSpace();
2713   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
2714                           AS, Load->getAlignment())) {
2715     SDValue Ops[2];
2716     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
2717     return DAG.getMergeValues(Ops, DL);
2718   }
2719 
2720   MachineFunction &MF = DAG.getMachineFunction();
2721   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2722   // If there is a possibilty that flat instruction access scratch memory
2723   // then we need to use the same legalization rules we use for private.
2724   if (AS == AMDGPUAS::FLAT_ADDRESS)
2725     AS = MFI->hasFlatScratchInit() ?
2726          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
2727 
2728   unsigned NumElements = MemVT.getVectorNumElements();
2729   switch (AS) {
2730   case AMDGPUAS::CONSTANT_ADDRESS:
2731     if (isMemOpUniform(Load))
2732       return SDValue();
2733     // Non-uniform loads will be selected to MUBUF instructions, so they
2734     // have the same legalization requires ments as global and private
2735     // loads.
2736     //
2737     LLVM_FALLTHROUGH;
2738   case AMDGPUAS::GLOBAL_ADDRESS:
2739   case AMDGPUAS::FLAT_ADDRESS:
2740     if (NumElements > 4)
2741       return SplitVectorLoad(Op, DAG);
2742     // v4 loads are supported for private and global memory.
2743     return SDValue();
2744   case AMDGPUAS::PRIVATE_ADDRESS: {
2745     // Depending on the setting of the private_element_size field in the
2746     // resource descriptor, we can only make private accesses up to a certain
2747     // size.
2748     switch (Subtarget->getMaxPrivateElementSize()) {
2749     case 4:
2750       return scalarizeVectorLoad(Load, DAG);
2751     case 8:
2752       if (NumElements > 2)
2753         return SplitVectorLoad(Op, DAG);
2754       return SDValue();
2755     case 16:
2756       // Same as global/flat
2757       if (NumElements > 4)
2758         return SplitVectorLoad(Op, DAG);
2759       return SDValue();
2760     default:
2761       llvm_unreachable("unsupported private_element_size");
2762     }
2763   }
2764   case AMDGPUAS::LOCAL_ADDRESS: {
2765     if (NumElements > 2)
2766       return SplitVectorLoad(Op, DAG);
2767 
2768     if (NumElements == 2)
2769       return SDValue();
2770 
2771     // If properly aligned, if we split we might be able to use ds_read_b64.
2772     return SplitVectorLoad(Op, DAG);
2773   }
2774   default:
2775     return SDValue();
2776   }
2777 }
2778 
2779 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2780   if (Op.getValueType() != MVT::i64)
2781     return SDValue();
2782 
2783   SDLoc DL(Op);
2784   SDValue Cond = Op.getOperand(0);
2785 
2786   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2787   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2788 
2789   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
2790   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
2791 
2792   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
2793   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
2794 
2795   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
2796 
2797   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
2798   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
2799 
2800   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
2801 
2802   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
2803   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
2804 }
2805 
2806 // Catch division cases where we can use shortcuts with rcp and rsq
2807 // instructions.
2808 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
2809                                               SelectionDAG &DAG) const {
2810   SDLoc SL(Op);
2811   SDValue LHS = Op.getOperand(0);
2812   SDValue RHS = Op.getOperand(1);
2813   EVT VT = Op.getValueType();
2814   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
2815 
2816   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
2817     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()))) {
2818 
2819       if (CLHS->isExactlyValue(1.0)) {
2820         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
2821         // the CI documentation has a worst case error of 1 ulp.
2822         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
2823         // use it as long as we aren't trying to use denormals.
2824 
2825         // 1.0 / sqrt(x) -> rsq(x)
2826         //
2827         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
2828         // error seems really high at 2^29 ULP.
2829         if (RHS.getOpcode() == ISD::FSQRT)
2830           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
2831 
2832         // 1.0 / x -> rcp(x)
2833         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2834       }
2835 
2836       // Same as for 1.0, but expand the sign out of the constant.
2837       if (CLHS->isExactlyValue(-1.0)) {
2838         // -1.0 / x -> rcp (fneg x)
2839         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2840         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
2841       }
2842     }
2843   }
2844 
2845   const SDNodeFlags *Flags = Op->getFlags();
2846 
2847   if (Unsafe || Flags->hasAllowReciprocal()) {
2848     // Turn into multiply by the reciprocal.
2849     // x / y -> x * (1.0 / y)
2850     SDNodeFlags Flags;
2851     Flags.setUnsafeAlgebra(true);
2852     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2853     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
2854   }
2855 
2856   return SDValue();
2857 }
2858 
2859 // Faster 2.5 ULP division that does not support denormals.
2860 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
2861   SDLoc SL(Op);
2862   SDValue LHS = Op.getOperand(1);
2863   SDValue RHS = Op.getOperand(2);
2864 
2865   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
2866 
2867   const APFloat K0Val(BitsToFloat(0x6f800000));
2868   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
2869 
2870   const APFloat K1Val(BitsToFloat(0x2f800000));
2871   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
2872 
2873   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
2874 
2875   EVT SetCCVT =
2876     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
2877 
2878   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
2879 
2880   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
2881 
2882   // TODO: Should this propagate fast-math-flags?
2883   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
2884 
2885   // rcp does not support denormals.
2886   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
2887 
2888   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
2889 
2890   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
2891 }
2892 
2893 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
2894   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
2895     return FastLowered;
2896 
2897   SDLoc SL(Op);
2898   SDValue LHS = Op.getOperand(0);
2899   SDValue RHS = Op.getOperand(1);
2900 
2901   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
2902 
2903   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
2904 
2905   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, RHS, RHS, LHS);
2906   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, LHS, RHS, LHS);
2907 
2908   // Denominator is scaled to not be denormal, so using rcp is ok.
2909   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled);
2910 
2911   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled);
2912 
2913   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, ApproxRcp, One);
2914   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, ApproxRcp);
2915 
2916   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1);
2917 
2918   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, NumeratorScaled);
2919   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul);
2920   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, NumeratorScaled);
2921 
2922   SDValue Scale = NumeratorScaled.getValue(1);
2923   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, Fma4, Fma1, Fma3, Scale);
2924 
2925   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
2926 }
2927 
2928 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
2929   if (DAG.getTarget().Options.UnsafeFPMath)
2930     return lowerFastUnsafeFDIV(Op, DAG);
2931 
2932   SDLoc SL(Op);
2933   SDValue X = Op.getOperand(0);
2934   SDValue Y = Op.getOperand(1);
2935 
2936   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2937 
2938   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
2939 
2940   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
2941 
2942   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
2943 
2944   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
2945 
2946   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
2947 
2948   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
2949 
2950   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
2951 
2952   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
2953 
2954   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
2955   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
2956 
2957   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
2958                              NegDivScale0, Mul, DivScale1);
2959 
2960   SDValue Scale;
2961 
2962   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
2963     // Workaround a hardware bug on SI where the condition output from div_scale
2964     // is not usable.
2965 
2966     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
2967 
2968     // Figure out if the scale to use for div_fmas.
2969     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2970     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
2971     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
2972     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
2973 
2974     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
2975     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
2976 
2977     SDValue Scale0Hi
2978       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
2979     SDValue Scale1Hi
2980       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
2981 
2982     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
2983     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
2984     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
2985   } else {
2986     Scale = DivScale1.getValue(1);
2987   }
2988 
2989   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
2990                              Fma4, Fma3, Mul, Scale);
2991 
2992   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
2993 }
2994 
2995 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
2996   EVT VT = Op.getValueType();
2997 
2998   if (VT == MVT::f32)
2999     return LowerFDIV32(Op, DAG);
3000 
3001   if (VT == MVT::f64)
3002     return LowerFDIV64(Op, DAG);
3003 
3004   llvm_unreachable("Unexpected type for fdiv");
3005 }
3006 
3007 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3008   SDLoc DL(Op);
3009   StoreSDNode *Store = cast<StoreSDNode>(Op);
3010   EVT VT = Store->getMemoryVT();
3011 
3012   if (VT == MVT::i1) {
3013     return DAG.getTruncStore(Store->getChain(), DL,
3014        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3015        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3016   }
3017 
3018   assert(VT.isVector() &&
3019          Store->getValue().getValueType().getScalarType() == MVT::i32);
3020 
3021   unsigned AS = Store->getAddressSpace();
3022   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3023                           AS, Store->getAlignment())) {
3024     return expandUnalignedStore(Store, DAG);
3025   }
3026 
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3029   // If there is a possibilty that flat instruction access scratch memory
3030   // then we need to use the same legalization rules we use for private.
3031   if (AS == AMDGPUAS::FLAT_ADDRESS)
3032     AS = MFI->hasFlatScratchInit() ?
3033          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3034 
3035   unsigned NumElements = VT.getVectorNumElements();
3036   switch (AS) {
3037   case AMDGPUAS::GLOBAL_ADDRESS:
3038   case AMDGPUAS::FLAT_ADDRESS:
3039     if (NumElements > 4)
3040       return SplitVectorStore(Op, DAG);
3041     return SDValue();
3042   case AMDGPUAS::PRIVATE_ADDRESS: {
3043     switch (Subtarget->getMaxPrivateElementSize()) {
3044     case 4:
3045       return scalarizeVectorStore(Store, DAG);
3046     case 8:
3047       if (NumElements > 2)
3048         return SplitVectorStore(Op, DAG);
3049       return SDValue();
3050     case 16:
3051       if (NumElements > 4)
3052         return SplitVectorStore(Op, DAG);
3053       return SDValue();
3054     default:
3055       llvm_unreachable("unsupported private_element_size");
3056     }
3057   }
3058   case AMDGPUAS::LOCAL_ADDRESS: {
3059     if (NumElements > 2)
3060       return SplitVectorStore(Op, DAG);
3061 
3062     if (NumElements == 2)
3063       return Op;
3064 
3065     // If properly aligned, if we split we might be able to use ds_write_b64.
3066     return SplitVectorStore(Op, DAG);
3067   }
3068   default:
3069     llvm_unreachable("unhandled address space");
3070   }
3071 }
3072 
3073 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3074   SDLoc DL(Op);
3075   EVT VT = Op.getValueType();
3076   SDValue Arg = Op.getOperand(0);
3077   // TODO: Should this propagate fast-math-flags?
3078   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3079                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
3080                                               DAG.getConstantFP(0.5/M_PI, DL,
3081                                                                 VT)));
3082 
3083   switch (Op.getOpcode()) {
3084   case ISD::FCOS:
3085     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3086   case ISD::FSIN:
3087     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3088   default:
3089     llvm_unreachable("Wrong trig opcode");
3090   }
3091 }
3092 
3093 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3094   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3095   assert(AtomicNode->isCompareAndSwap());
3096   unsigned AS = AtomicNode->getAddressSpace();
3097 
3098   // No custom lowering required for local address space
3099   if (!isFlatGlobalAddrSpace(AS))
3100     return Op;
3101 
3102   // Non-local address space requires custom lowering for atomic compare
3103   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3104   SDLoc DL(Op);
3105   SDValue ChainIn = Op.getOperand(0);
3106   SDValue Addr = Op.getOperand(1);
3107   SDValue Old = Op.getOperand(2);
3108   SDValue New = Op.getOperand(3);
3109   EVT VT = Op.getValueType();
3110   MVT SimpleVT = VT.getSimpleVT();
3111   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3112 
3113   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3114   SDValue Ops[] = { ChainIn, Addr, NewOld };
3115 
3116   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3117                                  Ops, VT, AtomicNode->getMemOperand());
3118 }
3119 
3120 //===----------------------------------------------------------------------===//
3121 // Custom DAG optimizations
3122 //===----------------------------------------------------------------------===//
3123 
3124 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3125                                                      DAGCombinerInfo &DCI) const {
3126   EVT VT = N->getValueType(0);
3127   EVT ScalarVT = VT.getScalarType();
3128   if (ScalarVT != MVT::f32)
3129     return SDValue();
3130 
3131   SelectionDAG &DAG = DCI.DAG;
3132   SDLoc DL(N);
3133 
3134   SDValue Src = N->getOperand(0);
3135   EVT SrcVT = Src.getValueType();
3136 
3137   // TODO: We could try to match extracting the higher bytes, which would be
3138   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3139   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3140   // about in practice.
3141   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3142     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3143       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3144       DCI.AddToWorklist(Cvt.getNode());
3145       return Cvt;
3146     }
3147   }
3148 
3149   return SDValue();
3150 }
3151 
3152 /// \brief Return true if the given offset Size in bytes can be folded into
3153 /// the immediate offsets of a memory instruction for the given address space.
3154 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3155                           const SISubtarget &STI) {
3156   switch (AS) {
3157   case AMDGPUAS::GLOBAL_ADDRESS: {
3158     // MUBUF instructions a 12-bit offset in bytes.
3159     return isUInt<12>(OffsetSize);
3160   }
3161   case AMDGPUAS::CONSTANT_ADDRESS: {
3162     // SMRD instructions have an 8-bit offset in dwords on SI and
3163     // a 20-bit offset in bytes on VI.
3164     if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3165       return isUInt<20>(OffsetSize);
3166     else
3167       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3168   }
3169   case AMDGPUAS::LOCAL_ADDRESS:
3170   case AMDGPUAS::REGION_ADDRESS: {
3171     // The single offset versions have a 16-bit offset in bytes.
3172     return isUInt<16>(OffsetSize);
3173   }
3174   case AMDGPUAS::PRIVATE_ADDRESS:
3175   // Indirect register addressing does not use any offsets.
3176   default:
3177     return 0;
3178   }
3179 }
3180 
3181 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3182 
3183 // This is a variant of
3184 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3185 //
3186 // The normal DAG combiner will do this, but only if the add has one use since
3187 // that would increase the number of instructions.
3188 //
3189 // This prevents us from seeing a constant offset that can be folded into a
3190 // memory instruction's addressing mode. If we know the resulting add offset of
3191 // a pointer can be folded into an addressing offset, we can replace the pointer
3192 // operand with the add of new constant offset. This eliminates one of the uses,
3193 // and may allow the remaining use to also be simplified.
3194 //
3195 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3196                                                unsigned AddrSpace,
3197                                                DAGCombinerInfo &DCI) const {
3198   SDValue N0 = N->getOperand(0);
3199   SDValue N1 = N->getOperand(1);
3200 
3201   if (N0.getOpcode() != ISD::ADD)
3202     return SDValue();
3203 
3204   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3205   if (!CN1)
3206     return SDValue();
3207 
3208   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3209   if (!CAdd)
3210     return SDValue();
3211 
3212   // If the resulting offset is too large, we can't fold it into the addressing
3213   // mode offset.
3214   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3215   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3216     return SDValue();
3217 
3218   SelectionDAG &DAG = DCI.DAG;
3219   SDLoc SL(N);
3220   EVT VT = N->getValueType(0);
3221 
3222   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3223   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3224 
3225   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3226 }
3227 
3228 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3229   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3230          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3231          (Opc == ISD::XOR && Val == 0);
3232 }
3233 
3234 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3235 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3236 // integer combine opportunities since most 64-bit operations are decomposed
3237 // this way.  TODO: We won't want this for SALU especially if it is an inline
3238 // immediate.
3239 SDValue SITargetLowering::splitBinaryBitConstantOp(
3240   DAGCombinerInfo &DCI,
3241   const SDLoc &SL,
3242   unsigned Opc, SDValue LHS,
3243   const ConstantSDNode *CRHS) const {
3244   uint64_t Val = CRHS->getZExtValue();
3245   uint32_t ValLo = Lo_32(Val);
3246   uint32_t ValHi = Hi_32(Val);
3247   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3248 
3249     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3250          bitOpWithConstantIsReducible(Opc, ValHi)) ||
3251         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3252     // If we need to materialize a 64-bit immediate, it will be split up later
3253     // anyway. Avoid creating the harder to understand 64-bit immediate
3254     // materialization.
3255     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3256   }
3257 
3258   return SDValue();
3259 }
3260 
3261 SDValue SITargetLowering::performAndCombine(SDNode *N,
3262                                             DAGCombinerInfo &DCI) const {
3263   if (DCI.isBeforeLegalize())
3264     return SDValue();
3265 
3266   SelectionDAG &DAG = DCI.DAG;
3267   EVT VT = N->getValueType(0);
3268   SDValue LHS = N->getOperand(0);
3269   SDValue RHS = N->getOperand(1);
3270 
3271 
3272   if (VT == MVT::i64) {
3273     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3274     if (CRHS) {
3275       if (SDValue Split
3276           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3277         return Split;
3278     }
3279   }
3280 
3281   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3282   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3283   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3284     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3285     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3286 
3287     SDValue X = LHS.getOperand(0);
3288     SDValue Y = RHS.getOperand(0);
3289     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3290       return SDValue();
3291 
3292     if (LCC == ISD::SETO) {
3293       if (X != LHS.getOperand(1))
3294         return SDValue();
3295 
3296       if (RCC == ISD::SETUNE) {
3297         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3298         if (!C1 || !C1->isInfinity() || C1->isNegative())
3299           return SDValue();
3300 
3301         const uint32_t Mask = SIInstrFlags::N_NORMAL |
3302                               SIInstrFlags::N_SUBNORMAL |
3303                               SIInstrFlags::N_ZERO |
3304                               SIInstrFlags::P_ZERO |
3305                               SIInstrFlags::P_SUBNORMAL |
3306                               SIInstrFlags::P_NORMAL;
3307 
3308         static_assert(((~(SIInstrFlags::S_NAN |
3309                           SIInstrFlags::Q_NAN |
3310                           SIInstrFlags::N_INFINITY |
3311                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3312                       "mask not equal");
3313 
3314         SDLoc DL(N);
3315         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3316                            X, DAG.getConstant(Mask, DL, MVT::i32));
3317       }
3318     }
3319   }
3320 
3321   return SDValue();
3322 }
3323 
3324 SDValue SITargetLowering::performOrCombine(SDNode *N,
3325                                            DAGCombinerInfo &DCI) const {
3326   SelectionDAG &DAG = DCI.DAG;
3327   SDValue LHS = N->getOperand(0);
3328   SDValue RHS = N->getOperand(1);
3329 
3330   EVT VT = N->getValueType(0);
3331   if (VT == MVT::i1) {
3332     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3333     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3334         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3335       SDValue Src = LHS.getOperand(0);
3336       if (Src != RHS.getOperand(0))
3337         return SDValue();
3338 
3339       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3340       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3341       if (!CLHS || !CRHS)
3342         return SDValue();
3343 
3344       // Only 10 bits are used.
3345       static const uint32_t MaxMask = 0x3ff;
3346 
3347       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3348       SDLoc DL(N);
3349       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3350                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
3351     }
3352 
3353     return SDValue();
3354   }
3355 
3356   if (VT != MVT::i64)
3357     return SDValue();
3358 
3359   // TODO: This could be a generic combine with a predicate for extracting the
3360   // high half of an integer being free.
3361 
3362   // (or i64:x, (zero_extend i32:y)) ->
3363   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
3364   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
3365       RHS.getOpcode() != ISD::ZERO_EXTEND)
3366     std::swap(LHS, RHS);
3367 
3368   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
3369     SDValue ExtSrc = RHS.getOperand(0);
3370     EVT SrcVT = ExtSrc.getValueType();
3371     if (SrcVT == MVT::i32) {
3372       SDLoc SL(N);
3373       SDValue LowLHS, HiBits;
3374       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
3375       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
3376 
3377       DCI.AddToWorklist(LowOr.getNode());
3378       DCI.AddToWorklist(HiBits.getNode());
3379 
3380       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3381                                 LowOr, HiBits);
3382       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3383     }
3384   }
3385 
3386   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3387   if (CRHS) {
3388     if (SDValue Split
3389           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
3390       return Split;
3391   }
3392 
3393   return SDValue();
3394 }
3395 
3396 SDValue SITargetLowering::performXorCombine(SDNode *N,
3397                                             DAGCombinerInfo &DCI) const {
3398   EVT VT = N->getValueType(0);
3399   if (VT != MVT::i64)
3400     return SDValue();
3401 
3402   SDValue LHS = N->getOperand(0);
3403   SDValue RHS = N->getOperand(1);
3404 
3405   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3406   if (CRHS) {
3407     if (SDValue Split
3408           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
3409       return Split;
3410   }
3411 
3412   return SDValue();
3413 }
3414 
3415 SDValue SITargetLowering::performClassCombine(SDNode *N,
3416                                               DAGCombinerInfo &DCI) const {
3417   SelectionDAG &DAG = DCI.DAG;
3418   SDValue Mask = N->getOperand(1);
3419 
3420   // fp_class x, 0 -> false
3421   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
3422     if (CMask->isNullValue())
3423       return DAG.getConstant(0, SDLoc(N), MVT::i1);
3424   }
3425 
3426   if (N->getOperand(0).isUndef())
3427     return DAG.getUNDEF(MVT::i1);
3428 
3429   return SDValue();
3430 }
3431 
3432 // Constant fold canonicalize.
3433 SDValue SITargetLowering::performFCanonicalizeCombine(
3434   SDNode *N,
3435   DAGCombinerInfo &DCI) const {
3436   ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3437   if (!CFP)
3438     return SDValue();
3439 
3440   SelectionDAG &DAG = DCI.DAG;
3441   const APFloat &C = CFP->getValueAPF();
3442 
3443   // Flush denormals to 0 if not enabled.
3444   if (C.isDenormal()) {
3445     EVT VT = N->getValueType(0);
3446     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals())
3447       return DAG.getConstantFP(0.0, SDLoc(N), VT);
3448 
3449     if (VT == MVT::f64 && !Subtarget->hasFP64Denormals())
3450       return DAG.getConstantFP(0.0, SDLoc(N), VT);
3451   }
3452 
3453   if (C.isNaN()) {
3454     EVT VT = N->getValueType(0);
3455     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
3456     if (C.isSignaling()) {
3457       // Quiet a signaling NaN.
3458       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3459     }
3460 
3461     // Make sure it is the canonical NaN bitpattern.
3462     //
3463     // TODO: Can we use -1 as the canonical NaN value since it's an inline
3464     // immediate?
3465     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
3466       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3467   }
3468 
3469   return SDValue(CFP, 0);
3470 }
3471 
3472 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
3473   switch (Opc) {
3474   case ISD::FMAXNUM:
3475     return AMDGPUISD::FMAX3;
3476   case ISD::SMAX:
3477     return AMDGPUISD::SMAX3;
3478   case ISD::UMAX:
3479     return AMDGPUISD::UMAX3;
3480   case ISD::FMINNUM:
3481     return AMDGPUISD::FMIN3;
3482   case ISD::SMIN:
3483     return AMDGPUISD::SMIN3;
3484   case ISD::UMIN:
3485     return AMDGPUISD::UMIN3;
3486   default:
3487     llvm_unreachable("Not a min/max opcode");
3488   }
3489 }
3490 
3491 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3492                                         SDValue Op0, SDValue Op1, bool Signed) {
3493   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
3494   if (!K1)
3495     return SDValue();
3496 
3497   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
3498   if (!K0)
3499     return SDValue();
3500 
3501   if (Signed) {
3502     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
3503       return SDValue();
3504   } else {
3505     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
3506       return SDValue();
3507   }
3508 
3509   EVT VT = K0->getValueType(0);
3510 
3511   MVT NVT = MVT::i32;
3512   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3513 
3514   SDValue Tmp1, Tmp2, Tmp3;
3515   Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
3516   Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
3517   Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
3518 
3519   if (VT == MVT::i16) {
3520     Tmp1 = DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, NVT,
3521                        Tmp1, Tmp2, Tmp3);
3522 
3523     return DAG.getNode(ISD::TRUNCATE, SL, VT, Tmp1);
3524   } else
3525     return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT,
3526                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
3527 }
3528 
3529 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
3530   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
3531     return true;
3532 
3533   return DAG.isKnownNeverNaN(Op);
3534 }
3535 
3536 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3537                                        SDValue Op0, SDValue Op1) {
3538   ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
3539   if (!K1)
3540     return SDValue();
3541 
3542   ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
3543   if (!K0)
3544     return SDValue();
3545 
3546   // Ordered >= (although NaN inputs should have folded away by now).
3547   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
3548   if (Cmp == APFloat::cmpGreaterThan)
3549     return SDValue();
3550 
3551   // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
3552   // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
3553   // give the other result, which is different from med3 with a NaN input.
3554   SDValue Var = Op0.getOperand(0);
3555   if (!isKnownNeverSNan(DAG, Var))
3556     return SDValue();
3557 
3558   return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
3559                      Var, SDValue(K0, 0), SDValue(K1, 0));
3560 }
3561 
3562 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
3563                                                DAGCombinerInfo &DCI) const {
3564   SelectionDAG &DAG = DCI.DAG;
3565 
3566   unsigned Opc = N->getOpcode();
3567   SDValue Op0 = N->getOperand(0);
3568   SDValue Op1 = N->getOperand(1);
3569 
3570   // Only do this if the inner op has one use since this will just increases
3571   // register pressure for no benefit.
3572 
3573   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) {
3574     // max(max(a, b), c) -> max3(a, b, c)
3575     // min(min(a, b), c) -> min3(a, b, c)
3576     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
3577       SDLoc DL(N);
3578       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3579                          DL,
3580                          N->getValueType(0),
3581                          Op0.getOperand(0),
3582                          Op0.getOperand(1),
3583                          Op1);
3584     }
3585 
3586     // Try commuted.
3587     // max(a, max(b, c)) -> max3(a, b, c)
3588     // min(a, min(b, c)) -> min3(a, b, c)
3589     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
3590       SDLoc DL(N);
3591       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3592                          DL,
3593                          N->getValueType(0),
3594                          Op0,
3595                          Op1.getOperand(0),
3596                          Op1.getOperand(1));
3597     }
3598   }
3599 
3600   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
3601   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
3602     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
3603       return Med3;
3604   }
3605 
3606   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
3607     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
3608       return Med3;
3609   }
3610 
3611   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
3612   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
3613        (Opc == AMDGPUISD::FMIN_LEGACY &&
3614         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
3615       N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) {
3616     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
3617       return Res;
3618   }
3619 
3620   return SDValue();
3621 }
3622 
3623 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
3624                                               DAGCombinerInfo &DCI) const {
3625   SelectionDAG &DAG = DCI.DAG;
3626   SDLoc SL(N);
3627 
3628   SDValue LHS = N->getOperand(0);
3629   SDValue RHS = N->getOperand(1);
3630   EVT VT = LHS.getValueType();
3631 
3632   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
3633                                            VT != MVT::f16))
3634     return SDValue();
3635 
3636   // Match isinf pattern
3637   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
3638   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
3639   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
3640     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
3641     if (!CRHS)
3642       return SDValue();
3643 
3644     const APFloat &APF = CRHS->getValueAPF();
3645     if (APF.isInfinity() && !APF.isNegative()) {
3646       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
3647       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
3648                          DAG.getConstant(Mask, SL, MVT::i32));
3649     }
3650   }
3651 
3652   return SDValue();
3653 }
3654 
3655 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
3656                                             DAGCombinerInfo &DCI) const {
3657   SelectionDAG &DAG = DCI.DAG;
3658   SDLoc DL(N);
3659 
3660   switch (N->getOpcode()) {
3661   default:
3662     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
3663   case ISD::SETCC:
3664     return performSetCCCombine(N, DCI);
3665   case ISD::FMAXNUM:
3666   case ISD::FMINNUM:
3667   case ISD::SMAX:
3668   case ISD::SMIN:
3669   case ISD::UMAX:
3670   case ISD::UMIN:
3671   case AMDGPUISD::FMIN_LEGACY:
3672   case AMDGPUISD::FMAX_LEGACY: {
3673     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
3674         N->getValueType(0) != MVT::f64 &&
3675         getTargetMachine().getOptLevel() > CodeGenOpt::None)
3676       return performMinMaxCombine(N, DCI);
3677     break;
3678   }
3679 
3680   case AMDGPUISD::CVT_F32_UBYTE0:
3681   case AMDGPUISD::CVT_F32_UBYTE1:
3682   case AMDGPUISD::CVT_F32_UBYTE2:
3683   case AMDGPUISD::CVT_F32_UBYTE3: {
3684     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
3685 
3686     SDValue Src = N->getOperand(0);
3687     SDValue Srl = N->getOperand(0);
3688     if (Srl.getOpcode() == ISD::ZERO_EXTEND)
3689       Srl = Srl.getOperand(0);
3690 
3691     // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
3692     if (Srl.getOpcode() == ISD::SRL) {
3693       // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
3694       // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
3695       // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
3696 
3697       if (const ConstantSDNode *C =
3698               dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
3699         Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
3700                                  EVT(MVT::i32));
3701 
3702         unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
3703         if (SrcOffset < 32 && SrcOffset % 8 == 0) {
3704           return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL,
3705                              MVT::f32, Srl);
3706         }
3707       }
3708     }
3709 
3710     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
3711 
3712     APInt KnownZero, KnownOne;
3713     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3714                                           !DCI.isBeforeLegalizeOps());
3715     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3716     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
3717         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
3718       DCI.CommitTargetLoweringOpt(TLO);
3719     }
3720 
3721     break;
3722   }
3723   case ISD::SINT_TO_FP:
3724   case ISD::UINT_TO_FP: {
3725     return performUCharToFloatCombine(N, DCI);
3726   }
3727   case ISD::FADD: {
3728     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3729       break;
3730 
3731     EVT VT = N->getValueType(0);
3732     if (VT != MVT::f32)
3733       break;
3734 
3735     // Only do this if we are not trying to support denormals. v_mad_f32 does
3736     // not support denormals ever.
3737     if (Subtarget->hasFP32Denormals())
3738       break;
3739 
3740     SDValue LHS = N->getOperand(0);
3741     SDValue RHS = N->getOperand(1);
3742 
3743     // These should really be instruction patterns, but writing patterns with
3744     // source modiifiers is a pain.
3745 
3746     // fadd (fadd (a, a), b) -> mad 2.0, a, b
3747     if (LHS.getOpcode() == ISD::FADD) {
3748       SDValue A = LHS.getOperand(0);
3749       if (A == LHS.getOperand(1)) {
3750         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3751         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
3752       }
3753     }
3754 
3755     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
3756     if (RHS.getOpcode() == ISD::FADD) {
3757       SDValue A = RHS.getOperand(0);
3758       if (A == RHS.getOperand(1)) {
3759         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3760         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
3761       }
3762     }
3763 
3764     return SDValue();
3765   }
3766   case ISD::FSUB: {
3767     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3768       break;
3769 
3770     EVT VT = N->getValueType(0);
3771 
3772     // Try to get the fneg to fold into the source modifier. This undoes generic
3773     // DAG combines and folds them into the mad.
3774     //
3775     // Only do this if we are not trying to support denormals. v_mad_f32 does
3776     // not support denormals ever.
3777     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) {
3778       SDValue LHS = N->getOperand(0);
3779       SDValue RHS = N->getOperand(1);
3780       if (LHS.getOpcode() == ISD::FADD) {
3781         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
3782 
3783         SDValue A = LHS.getOperand(0);
3784         if (A == LHS.getOperand(1)) {
3785           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3786           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
3787 
3788           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
3789         }
3790       }
3791 
3792       if (RHS.getOpcode() == ISD::FADD) {
3793         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
3794 
3795         SDValue A = RHS.getOperand(0);
3796         if (A == RHS.getOperand(1)) {
3797           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
3798           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
3799         }
3800       }
3801 
3802       return SDValue();
3803     }
3804 
3805     break;
3806   }
3807   case ISD::LOAD:
3808   case ISD::STORE:
3809   case ISD::ATOMIC_LOAD:
3810   case ISD::ATOMIC_STORE:
3811   case ISD::ATOMIC_CMP_SWAP:
3812   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3813   case ISD::ATOMIC_SWAP:
3814   case ISD::ATOMIC_LOAD_ADD:
3815   case ISD::ATOMIC_LOAD_SUB:
3816   case ISD::ATOMIC_LOAD_AND:
3817   case ISD::ATOMIC_LOAD_OR:
3818   case ISD::ATOMIC_LOAD_XOR:
3819   case ISD::ATOMIC_LOAD_NAND:
3820   case ISD::ATOMIC_LOAD_MIN:
3821   case ISD::ATOMIC_LOAD_MAX:
3822   case ISD::ATOMIC_LOAD_UMIN:
3823   case ISD::ATOMIC_LOAD_UMAX:
3824   case AMDGPUISD::ATOMIC_INC:
3825   case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics.
3826     if (DCI.isBeforeLegalize())
3827       break;
3828 
3829     MemSDNode *MemNode = cast<MemSDNode>(N);
3830     SDValue Ptr = MemNode->getBasePtr();
3831 
3832     // TODO: We could also do this for multiplies.
3833     unsigned AS = MemNode->getAddressSpace();
3834     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3835       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3836       if (NewPtr) {
3837         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
3838 
3839         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3840         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
3841       }
3842     }
3843     break;
3844   }
3845   case ISD::AND:
3846     return performAndCombine(N, DCI);
3847   case ISD::OR:
3848     return performOrCombine(N, DCI);
3849   case ISD::XOR:
3850     return performXorCombine(N, DCI);
3851   case AMDGPUISD::FP_CLASS:
3852     return performClassCombine(N, DCI);
3853   case ISD::FCANONICALIZE:
3854     return performFCanonicalizeCombine(N, DCI);
3855   case AMDGPUISD::FRACT:
3856   case AMDGPUISD::RCP:
3857   case AMDGPUISD::RSQ:
3858   case AMDGPUISD::RCP_LEGACY:
3859   case AMDGPUISD::RSQ_LEGACY:
3860   case AMDGPUISD::RSQ_CLAMP:
3861   case AMDGPUISD::LDEXP: {
3862     SDValue Src = N->getOperand(0);
3863     if (Src.isUndef())
3864       return Src;
3865     break;
3866   }
3867   }
3868   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
3869 }
3870 
3871 /// \brief Helper function for adjustWritemask
3872 static unsigned SubIdx2Lane(unsigned Idx) {
3873   switch (Idx) {
3874   default: return 0;
3875   case AMDGPU::sub0: return 0;
3876   case AMDGPU::sub1: return 1;
3877   case AMDGPU::sub2: return 2;
3878   case AMDGPU::sub3: return 3;
3879   }
3880 }
3881 
3882 /// \brief Adjust the writemask of MIMG instructions
3883 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
3884                                        SelectionDAG &DAG) const {
3885   SDNode *Users[4] = { };
3886   unsigned Lane = 0;
3887   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
3888   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
3889   unsigned NewDmask = 0;
3890 
3891   // Try to figure out the used register components
3892   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
3893        I != E; ++I) {
3894 
3895     // Abort if we can't understand the usage
3896     if (!I->isMachineOpcode() ||
3897         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
3898       return;
3899 
3900     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
3901     // Note that subregs are packed, i.e. Lane==0 is the first bit set
3902     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
3903     // set, etc.
3904     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
3905 
3906     // Set which texture component corresponds to the lane.
3907     unsigned Comp;
3908     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
3909       assert(Dmask);
3910       Comp = countTrailingZeros(Dmask);
3911       Dmask &= ~(1 << Comp);
3912     }
3913 
3914     // Abort if we have more than one user per component
3915     if (Users[Lane])
3916       return;
3917 
3918     Users[Lane] = *I;
3919     NewDmask |= 1 << Comp;
3920   }
3921 
3922   // Abort if there's no change
3923   if (NewDmask == OldDmask)
3924     return;
3925 
3926   // Adjust the writemask in the node
3927   std::vector<SDValue> Ops;
3928   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
3929   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
3930   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
3931   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
3932 
3933   // If we only got one lane, replace it with a copy
3934   // (if NewDmask has only one bit set...)
3935   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
3936     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
3937                                        MVT::i32);
3938     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
3939                                       SDLoc(), Users[Lane]->getValueType(0),
3940                                       SDValue(Node, 0), RC);
3941     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
3942     return;
3943   }
3944 
3945   // Update the users of the node with the new indices
3946   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
3947 
3948     SDNode *User = Users[i];
3949     if (!User)
3950       continue;
3951 
3952     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
3953     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
3954 
3955     switch (Idx) {
3956     default: break;
3957     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
3958     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
3959     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
3960     }
3961   }
3962 }
3963 
3964 static bool isFrameIndexOp(SDValue Op) {
3965   if (Op.getOpcode() == ISD::AssertZext)
3966     Op = Op.getOperand(0);
3967 
3968   return isa<FrameIndexSDNode>(Op);
3969 }
3970 
3971 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
3972 /// with frame index operands.
3973 /// LLVM assumes that inputs are to these instructions are registers.
3974 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
3975                                                      SelectionDAG &DAG) const {
3976 
3977   SmallVector<SDValue, 8> Ops;
3978   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
3979     if (!isFrameIndexOp(Node->getOperand(i))) {
3980       Ops.push_back(Node->getOperand(i));
3981       continue;
3982     }
3983 
3984     SDLoc DL(Node);
3985     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
3986                                      Node->getOperand(i).getValueType(),
3987                                      Node->getOperand(i)), 0));
3988   }
3989 
3990   DAG.UpdateNodeOperands(Node, Ops);
3991 }
3992 
3993 /// \brief Fold the instructions after selecting them.
3994 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
3995                                           SelectionDAG &DAG) const {
3996   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3997   unsigned Opcode = Node->getMachineOpcode();
3998 
3999   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4000       !TII->isGather4(Opcode))
4001     adjustWritemask(Node, DAG);
4002 
4003   if (Opcode == AMDGPU::INSERT_SUBREG ||
4004       Opcode == AMDGPU::REG_SEQUENCE) {
4005     legalizeTargetIndependentNode(Node, DAG);
4006     return Node;
4007   }
4008   return Node;
4009 }
4010 
4011 /// \brief Assign the register class depending on the number of
4012 /// bits set in the writemask
4013 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4014                                                      SDNode *Node) const {
4015   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4016 
4017   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4018 
4019   if (TII->isVOP3(MI.getOpcode())) {
4020     // Make sure constant bus requirements are respected.
4021     TII->legalizeOperandsVOP3(MRI, MI);
4022     return;
4023   }
4024 
4025   if (TII->isMIMG(MI)) {
4026     unsigned VReg = MI.getOperand(0).getReg();
4027     const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4028     // TODO: Need mapping tables to handle other cases (register classes).
4029     if (RC != &AMDGPU::VReg_128RegClass)
4030       return;
4031 
4032     unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4033     unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4034     unsigned BitsSet = 0;
4035     for (unsigned i = 0; i < 4; ++i)
4036       BitsSet += Writemask & (1 << i) ? 1 : 0;
4037     switch (BitsSet) {
4038     default: return;
4039     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
4040     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
4041     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
4042     }
4043 
4044     unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4045     MI.setDesc(TII->get(NewOpcode));
4046     MRI.setRegClass(VReg, RC);
4047     return;
4048   }
4049 
4050   // Replace unused atomics with the no return version.
4051   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4052   if (NoRetAtomicOp != -1) {
4053     if (!Node->hasAnyUseOfValue(0)) {
4054       MI.setDesc(TII->get(NoRetAtomicOp));
4055       MI.RemoveOperand(0);
4056       return;
4057     }
4058 
4059     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4060     // instruction, because the return type of these instructions is a vec2 of
4061     // the memory type, so it can be tied to the input operand.
4062     // This means these instructions always have a use, so we need to add a
4063     // special case to check if the atomic has only one extract_subreg use,
4064     // which itself has no uses.
4065     if ((Node->hasNUsesOfValue(1, 0) &&
4066          Node->use_begin()->isMachineOpcode() &&
4067          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4068          !Node->use_begin()->hasAnyUseOfValue(0))) {
4069       unsigned Def = MI.getOperand(0).getReg();
4070 
4071       // Change this into a noret atomic.
4072       MI.setDesc(TII->get(NoRetAtomicOp));
4073       MI.RemoveOperand(0);
4074 
4075       // If we only remove the def operand from the atomic instruction, the
4076       // extract_subreg will be left with a use of a vreg without a def.
4077       // So we need to insert an implicit_def to avoid machine verifier
4078       // errors.
4079       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4080               TII->get(AMDGPU::IMPLICIT_DEF), Def);
4081     }
4082     return;
4083   }
4084 }
4085 
4086 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4087                               uint64_t Val) {
4088   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4089   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4090 }
4091 
4092 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4093                                                 const SDLoc &DL,
4094                                                 SDValue Ptr) const {
4095   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4096 
4097   // Build the half of the subregister with the constants before building the
4098   // full 128-bit register. If we are building multiple resource descriptors,
4099   // this will allow CSEing of the 2-component register.
4100   const SDValue Ops0[] = {
4101     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4102     buildSMovImm32(DAG, DL, 0),
4103     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4104     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4105     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4106   };
4107 
4108   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4109                                                 MVT::v2i32, Ops0), 0);
4110 
4111   // Combine the constants and the pointer.
4112   const SDValue Ops1[] = {
4113     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4114     Ptr,
4115     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4116     SubRegHi,
4117     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4118   };
4119 
4120   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4121 }
4122 
4123 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
4124 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4125 ///        of the resource descriptor) to create an offset, which is added to
4126 ///        the resource pointer.
4127 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4128                                            SDValue Ptr, uint32_t RsrcDword1,
4129                                            uint64_t RsrcDword2And3) const {
4130   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4131   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4132   if (RsrcDword1) {
4133     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4134                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4135                     0);
4136   }
4137 
4138   SDValue DataLo = buildSMovImm32(DAG, DL,
4139                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
4140   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4141 
4142   const SDValue Ops[] = {
4143     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4144     PtrLo,
4145     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4146     PtrHi,
4147     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4148     DataLo,
4149     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4150     DataHi,
4151     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4152   };
4153 
4154   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4155 }
4156 
4157 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4158                                                const TargetRegisterClass *RC,
4159                                                unsigned Reg, EVT VT) const {
4160   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4161 
4162   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4163                             cast<RegisterSDNode>(VReg)->getReg(), VT);
4164 }
4165 
4166 //===----------------------------------------------------------------------===//
4167 //                         SI Inline Assembly Support
4168 //===----------------------------------------------------------------------===//
4169 
4170 std::pair<unsigned, const TargetRegisterClass *>
4171 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4172                                                StringRef Constraint,
4173                                                MVT VT) const {
4174   if (!isTypeLegal(VT))
4175     return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4176 
4177   if (Constraint.size() == 1) {
4178     switch (Constraint[0]) {
4179     case 's':
4180     case 'r':
4181       switch (VT.getSizeInBits()) {
4182       default:
4183         return std::make_pair(0U, nullptr);
4184       case 32:
4185         return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
4186       case 64:
4187         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
4188       case 128:
4189         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
4190       case 256:
4191         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
4192       }
4193 
4194     case 'v':
4195       switch (VT.getSizeInBits()) {
4196       default:
4197         return std::make_pair(0U, nullptr);
4198       case 32:
4199         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
4200       case 64:
4201         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
4202       case 96:
4203         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
4204       case 128:
4205         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
4206       case 256:
4207         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
4208       case 512:
4209         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
4210       }
4211     }
4212   }
4213 
4214   if (Constraint.size() > 1) {
4215     const TargetRegisterClass *RC = nullptr;
4216     if (Constraint[1] == 'v') {
4217       RC = &AMDGPU::VGPR_32RegClass;
4218     } else if (Constraint[1] == 's') {
4219       RC = &AMDGPU::SGPR_32RegClass;
4220     }
4221 
4222     if (RC) {
4223       uint32_t Idx;
4224       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
4225       if (!Failed && Idx < RC->getNumRegs())
4226         return std::make_pair(RC->getRegister(Idx), RC);
4227     }
4228   }
4229   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4230 }
4231 
4232 SITargetLowering::ConstraintType
4233 SITargetLowering::getConstraintType(StringRef Constraint) const {
4234   if (Constraint.size() == 1) {
4235     switch (Constraint[0]) {
4236     default: break;
4237     case 's':
4238     case 'v':
4239       return C_RegisterClass;
4240     }
4241   }
4242   return TargetLowering::getConstraintType(Constraint);
4243 }
4244