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