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