1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
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 This is the parent TargetLowering class for hardware code gen
12 /// targets.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPUISelLowering.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUCallLowering.h"
19 #include "AMDGPUFrameLowering.h"
20 #include "AMDGPUIntrinsicInfo.h"
21 #include "AMDGPURegisterInfo.h"
22 #include "AMDGPUSubtarget.h"
23 #include "R600MachineFunctionInfo.h"
24 #include "SIMachineFunctionInfo.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "SIInstrInfo.h"
33 using namespace llvm;
34 
35 static bool allocateKernArg(unsigned ValNo, MVT ValVT, MVT LocVT,
36                             CCValAssign::LocInfo LocInfo,
37                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
38   MachineFunction &MF = State.getMachineFunction();
39   AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
40 
41   uint64_t Offset = MFI->allocateKernArg(LocVT.getStoreSize(),
42                                          ArgFlags.getOrigAlign());
43   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
44   return true;
45 }
46 
47 static bool allocateCCRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
48                            CCValAssign::LocInfo LocInfo,
49                            ISD::ArgFlagsTy ArgFlags, CCState &State,
50                            const TargetRegisterClass *RC,
51                            unsigned NumRegs) {
52   ArrayRef<MCPhysReg> RegList = makeArrayRef(RC->begin(), NumRegs);
53   unsigned RegResult = State.AllocateReg(RegList);
54   if (RegResult == AMDGPU::NoRegister)
55     return false;
56 
57   State.addLoc(CCValAssign::getReg(ValNo, ValVT, RegResult, LocVT, LocInfo));
58   return true;
59 }
60 
61 static bool allocateSGPRTuple(unsigned ValNo, MVT ValVT, MVT LocVT,
62                               CCValAssign::LocInfo LocInfo,
63                               ISD::ArgFlagsTy ArgFlags, CCState &State) {
64   switch (LocVT.SimpleTy) {
65   case MVT::i64:
66   case MVT::f64:
67   case MVT::v2i32:
68   case MVT::v2f32: {
69     // Up to SGPR0-SGPR39
70     return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
71                           &AMDGPU::SGPR_64RegClass, 20);
72   }
73   default:
74     return false;
75   }
76 }
77 
78 #include "AMDGPUGenCallingConv.inc"
79 
80 // Find a larger type to do a load / store of a vector with.
81 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
82   unsigned StoreSize = VT.getStoreSizeInBits();
83   if (StoreSize <= 32)
84     return EVT::getIntegerVT(Ctx, StoreSize);
85 
86   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
87   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
88 }
89 
90 AMDGPUTargetLowering::AMDGPUTargetLowering(const TargetMachine &TM,
91                                            const AMDGPUSubtarget &STI)
92     : TargetLowering(TM), Subtarget(&STI) {
93   AMDGPUASI = AMDGPU::getAMDGPUAS(TM);
94   // Lower floating point store/load to integer store/load to reduce the number
95   // of patterns in tablegen.
96   setOperationAction(ISD::LOAD, MVT::f32, Promote);
97   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
98 
99   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
100   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
101 
102   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
103   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
104 
105   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
106   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
107 
108   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
109   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
110 
111   setOperationAction(ISD::LOAD, MVT::i64, Promote);
112   AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
113 
114   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
115   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
116 
117   setOperationAction(ISD::LOAD, MVT::f64, Promote);
118   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::v2i32);
119 
120   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
121   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v4i32);
122 
123   // There are no 64-bit extloads. These should be done as a 32-bit extload and
124   // an extension to 64-bit.
125   for (MVT VT : MVT::integer_valuetypes()) {
126     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
127     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
128     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
129   }
130 
131   for (MVT VT : MVT::integer_valuetypes()) {
132     if (VT == MVT::i64)
133       continue;
134 
135     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
136     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
137     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
138     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
139 
140     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
141     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
142     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
143     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
144 
145     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
146     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
147     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
148     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
149   }
150 
151   for (MVT VT : MVT::integer_vector_valuetypes()) {
152     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
153     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
154     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
155     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
156     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
157     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
158     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
160     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
161     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
162     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
163     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
164   }
165 
166   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
167   setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
168   setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
169   setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
170 
171   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
172   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
173   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
174   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f32, Expand);
175 
176   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
177   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
178   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
179   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
180 
181   setOperationAction(ISD::STORE, MVT::f32, Promote);
182   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
183 
184   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
185   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
186 
187   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
188   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
189 
190   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
191   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
192 
193   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
194   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
195 
196   setOperationAction(ISD::STORE, MVT::i64, Promote);
197   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
198 
199   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
200   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
201 
202   setOperationAction(ISD::STORE, MVT::f64, Promote);
203   AddPromotedToType(ISD::STORE, MVT::f64, MVT::v2i32);
204 
205   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
206   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v4i32);
207 
208   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
209   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
210   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
211   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
212 
213   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
214   setTruncStoreAction(MVT::v2i64, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v2i64, MVT::v2i16, Expand);
216   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
217 
218   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
219   setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
220   setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
221   setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
222 
223   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
224   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
225 
226   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
227   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
228 
229   setTruncStoreAction(MVT::v4f64, MVT::v4f32, Expand);
230   setTruncStoreAction(MVT::v4f64, MVT::v4f16, Expand);
231 
232   setTruncStoreAction(MVT::v8f64, MVT::v8f32, Expand);
233   setTruncStoreAction(MVT::v8f64, MVT::v8f16, Expand);
234 
235 
236   setOperationAction(ISD::Constant, MVT::i32, Legal);
237   setOperationAction(ISD::Constant, MVT::i64, Legal);
238   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
239   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
240 
241   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
242   setOperationAction(ISD::BRIND, MVT::Other, Expand);
243 
244   // This is totally unsupported, just custom lower to produce an error.
245   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
246 
247   // Library functions.  These default to Expand, but we have instructions
248   // for them.
249   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
250   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
251   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
252   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
253   setOperationAction(ISD::FABS,   MVT::f32, Legal);
254   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
255   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
256   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
257   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
258   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
259 
260   setOperationAction(ISD::FROUND, MVT::f32, Custom);
261   setOperationAction(ISD::FROUND, MVT::f64, Custom);
262 
263   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
264   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
265 
266   setOperationAction(ISD::FREM, MVT::f32, Custom);
267   setOperationAction(ISD::FREM, MVT::f64, Custom);
268 
269   // v_mad_f32 does not support denormals according to some sources.
270   if (!Subtarget->hasFP32Denormals())
271     setOperationAction(ISD::FMAD, MVT::f32, Legal);
272 
273   // Expand to fneg + fadd.
274   setOperationAction(ISD::FSUB, MVT::f64, Expand);
275 
276   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
277   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
278   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
279   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
280   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
281   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
282   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
283   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
284   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
285   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
286 
287   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
288     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
289     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
290     setOperationAction(ISD::FRINT, MVT::f64, Custom);
291     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
292   }
293 
294   if (!Subtarget->hasBFI()) {
295     // fcopysign can be done in a single instruction with BFI.
296     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
297     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
298   }
299 
300   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
301   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Custom);
302   setOperationAction(ISD::FP_TO_FP16, MVT::f32, Custom);
303 
304   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
305   for (MVT VT : ScalarIntVTs) {
306     // These should use [SU]DIVREM, so set them to expand
307     setOperationAction(ISD::SDIV, VT, Expand);
308     setOperationAction(ISD::UDIV, VT, Expand);
309     setOperationAction(ISD::SREM, VT, Expand);
310     setOperationAction(ISD::UREM, VT, Expand);
311 
312     // GPU does not have divrem function for signed or unsigned.
313     setOperationAction(ISD::SDIVREM, VT, Custom);
314     setOperationAction(ISD::UDIVREM, VT, Custom);
315 
316     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
317     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
318     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
319 
320     setOperationAction(ISD::BSWAP, VT, Expand);
321     setOperationAction(ISD::CTTZ, VT, Expand);
322     setOperationAction(ISD::CTLZ, VT, Expand);
323   }
324 
325   if (!Subtarget->hasBCNT(32))
326     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
327 
328   if (!Subtarget->hasBCNT(64))
329     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
330 
331   // The hardware supports 32-bit ROTR, but not ROTL.
332   setOperationAction(ISD::ROTL, MVT::i32, Expand);
333   setOperationAction(ISD::ROTL, MVT::i64, Expand);
334   setOperationAction(ISD::ROTR, MVT::i64, Expand);
335 
336   setOperationAction(ISD::MUL, MVT::i64, Expand);
337   setOperationAction(ISD::MULHU, MVT::i64, Expand);
338   setOperationAction(ISD::MULHS, MVT::i64, Expand);
339   setOperationAction(ISD::UDIV, MVT::i32, Expand);
340   setOperationAction(ISD::UREM, MVT::i32, Expand);
341   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
342   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
343   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
344   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
345   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
346 
347   setOperationAction(ISD::SMIN, MVT::i32, Legal);
348   setOperationAction(ISD::UMIN, MVT::i32, Legal);
349   setOperationAction(ISD::SMAX, MVT::i32, Legal);
350   setOperationAction(ISD::UMAX, MVT::i32, Legal);
351 
352   if (Subtarget->hasFFBH())
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
354 
355   if (Subtarget->hasFFBL())
356     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Legal);
357 
358   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
359   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
360 
361   // We only really have 32-bit BFE instructions (and 16-bit on VI).
362   //
363   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
364   // effort to match them now. We want this to be false for i64 cases when the
365   // extraction isn't restricted to the upper or lower half. Ideally we would
366   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
367   // span the midpoint are probably relatively rare, so don't worry about them
368   // for now.
369   if (Subtarget->hasBFE())
370     setHasExtractBitsInsn(true);
371 
372   static const MVT::SimpleValueType VectorIntTypes[] = {
373     MVT::v2i32, MVT::v4i32
374   };
375 
376   for (MVT VT : VectorIntTypes) {
377     // Expand the following operations for the current type by default.
378     setOperationAction(ISD::ADD,  VT, Expand);
379     setOperationAction(ISD::AND,  VT, Expand);
380     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
381     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
382     setOperationAction(ISD::MUL,  VT, Expand);
383     setOperationAction(ISD::MULHU, VT, Expand);
384     setOperationAction(ISD::MULHS, VT, Expand);
385     setOperationAction(ISD::OR,   VT, Expand);
386     setOperationAction(ISD::SHL,  VT, Expand);
387     setOperationAction(ISD::SRA,  VT, Expand);
388     setOperationAction(ISD::SRL,  VT, Expand);
389     setOperationAction(ISD::ROTL, VT, Expand);
390     setOperationAction(ISD::ROTR, VT, Expand);
391     setOperationAction(ISD::SUB,  VT, Expand);
392     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
393     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
394     setOperationAction(ISD::SDIV, VT, Expand);
395     setOperationAction(ISD::UDIV, VT, Expand);
396     setOperationAction(ISD::SREM, VT, Expand);
397     setOperationAction(ISD::UREM, VT, Expand);
398     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
399     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
400     setOperationAction(ISD::SDIVREM, VT, Custom);
401     setOperationAction(ISD::UDIVREM, VT, Expand);
402     setOperationAction(ISD::ADDC, VT, Expand);
403     setOperationAction(ISD::SUBC, VT, Expand);
404     setOperationAction(ISD::ADDE, VT, Expand);
405     setOperationAction(ISD::SUBE, VT, Expand);
406     setOperationAction(ISD::SELECT, VT, Expand);
407     setOperationAction(ISD::VSELECT, VT, Expand);
408     setOperationAction(ISD::SELECT_CC, VT, Expand);
409     setOperationAction(ISD::XOR,  VT, Expand);
410     setOperationAction(ISD::BSWAP, VT, Expand);
411     setOperationAction(ISD::CTPOP, VT, Expand);
412     setOperationAction(ISD::CTTZ, VT, Expand);
413     setOperationAction(ISD::CTLZ, VT, Expand);
414     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
415   }
416 
417   static const MVT::SimpleValueType FloatVectorTypes[] = {
418     MVT::v2f32, MVT::v4f32
419   };
420 
421   for (MVT VT : FloatVectorTypes) {
422     setOperationAction(ISD::FABS, VT, Expand);
423     setOperationAction(ISD::FMINNUM, VT, Expand);
424     setOperationAction(ISD::FMAXNUM, VT, Expand);
425     setOperationAction(ISD::FADD, VT, Expand);
426     setOperationAction(ISD::FCEIL, VT, Expand);
427     setOperationAction(ISD::FCOS, VT, Expand);
428     setOperationAction(ISD::FDIV, VT, Expand);
429     setOperationAction(ISD::FEXP2, VT, Expand);
430     setOperationAction(ISD::FLOG2, VT, Expand);
431     setOperationAction(ISD::FREM, VT, Expand);
432     setOperationAction(ISD::FPOW, VT, Expand);
433     setOperationAction(ISD::FFLOOR, VT, Expand);
434     setOperationAction(ISD::FTRUNC, VT, Expand);
435     setOperationAction(ISD::FMUL, VT, Expand);
436     setOperationAction(ISD::FMA, VT, Expand);
437     setOperationAction(ISD::FRINT, VT, Expand);
438     setOperationAction(ISD::FNEARBYINT, VT, Expand);
439     setOperationAction(ISD::FSQRT, VT, Expand);
440     setOperationAction(ISD::FSIN, VT, Expand);
441     setOperationAction(ISD::FSUB, VT, Expand);
442     setOperationAction(ISD::FNEG, VT, Expand);
443     setOperationAction(ISD::VSELECT, VT, Expand);
444     setOperationAction(ISD::SELECT_CC, VT, Expand);
445     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
446     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
447   }
448 
449   // This causes using an unrolled select operation rather than expansion with
450   // bit operations. This is in general better, but the alternative using BFI
451   // instructions may be better if the select sources are SGPRs.
452   setOperationAction(ISD::SELECT, MVT::v2f32, Promote);
453   AddPromotedToType(ISD::SELECT, MVT::v2f32, MVT::v2i32);
454 
455   setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
456   AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
457 
458   // There are no libcalls of any kind.
459   for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
460     setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
461 
462   setBooleanContents(ZeroOrNegativeOneBooleanContent);
463   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
464 
465   setSchedulingPreference(Sched::RegPressure);
466   setJumpIsExpensive(true);
467 
468   // FIXME: This is only partially true. If we have to do vector compares, any
469   // SGPR pair can be a condition register. If we have a uniform condition, we
470   // are better off doing SALU operations, where there is only one SCC. For now,
471   // we don't have a way of knowing during instruction selection if a condition
472   // will be uniform and we always use vector compares. Assume we are using
473   // vector compares until that is fixed.
474   setHasMultipleConditionRegisters(true);
475 
476   // SI at least has hardware support for floating point exceptions, but no way
477   // of using or handling them is implemented. They are also optional in OpenCL
478   // (Section 7.3)
479   setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
480 
481   PredictableSelectIsExpensive = false;
482 
483   // We want to find all load dependencies for long chains of stores to enable
484   // merging into very wide vectors. The problem is with vectors with > 4
485   // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
486   // vectors are a legal type, even though we have to split the loads
487   // usually. When we can more precisely specify load legality per address
488   // space, we should be able to make FindBetterChain/MergeConsecutiveStores
489   // smarter so that they can figure out what to do in 2 iterations without all
490   // N > 4 stores on the same chain.
491   GatherAllAliasesMaxDepth = 16;
492 
493   // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
494   // about these during lowering.
495   MaxStoresPerMemcpy  = 0xffffffff;
496   MaxStoresPerMemmove = 0xffffffff;
497   MaxStoresPerMemset  = 0xffffffff;
498 
499   setTargetDAGCombine(ISD::BITCAST);
500   setTargetDAGCombine(ISD::SHL);
501   setTargetDAGCombine(ISD::SRA);
502   setTargetDAGCombine(ISD::SRL);
503   setTargetDAGCombine(ISD::MUL);
504   setTargetDAGCombine(ISD::MULHU);
505   setTargetDAGCombine(ISD::MULHS);
506   setTargetDAGCombine(ISD::SELECT);
507   setTargetDAGCombine(ISD::SELECT_CC);
508   setTargetDAGCombine(ISD::STORE);
509   setTargetDAGCombine(ISD::FADD);
510   setTargetDAGCombine(ISD::FSUB);
511   setTargetDAGCombine(ISD::FNEG);
512   setTargetDAGCombine(ISD::FABS);
513 }
514 
515 //===----------------------------------------------------------------------===//
516 // Target Information
517 //===----------------------------------------------------------------------===//
518 
519 LLVM_READNONE
520 static bool fnegFoldsIntoOp(unsigned Opc) {
521   switch (Opc) {
522   case ISD::FADD:
523   case ISD::FSUB:
524   case ISD::FMUL:
525   case ISD::FMA:
526   case ISD::FMAD:
527   case ISD::FMINNUM:
528   case ISD::FMAXNUM:
529   case ISD::FSIN:
530   case ISD::FTRUNC:
531   case ISD::FRINT:
532   case ISD::FNEARBYINT:
533   case AMDGPUISD::RCP:
534   case AMDGPUISD::RCP_LEGACY:
535   case AMDGPUISD::SIN_HW:
536   case AMDGPUISD::FMUL_LEGACY:
537   case AMDGPUISD::FMIN_LEGACY:
538   case AMDGPUISD::FMAX_LEGACY:
539     return true;
540   default:
541     return false;
542   }
543 }
544 
545 /// \p returns true if the operation will definitely need to use a 64-bit
546 /// encoding, and thus will use a VOP3 encoding regardless of the source
547 /// modifiers.
548 LLVM_READONLY
549 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
550   return N->getNumOperands() > 2 || VT == MVT::f64;
551 }
552 
553 // Most FP instructions support source modifiers, but this could be refined
554 // slightly.
555 LLVM_READONLY
556 static bool hasSourceMods(const SDNode *N) {
557   if (isa<MemSDNode>(N))
558     return false;
559 
560   switch (N->getOpcode()) {
561   case ISD::CopyToReg:
562   case ISD::SELECT:
563   case ISD::FDIV:
564   case ISD::FREM:
565   case ISD::INLINEASM:
566   case AMDGPUISD::INTERP_P1:
567   case AMDGPUISD::INTERP_P2:
568   case AMDGPUISD::DIV_SCALE:
569     return false;
570   default:
571     return true;
572   }
573 }
574 
575 static bool allUsesHaveSourceMods(const SDNode *N, unsigned CostThreshold = 4) {
576   // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
577   // it is truly free to use a source modifier in all cases. If there are
578   // multiple users but for each one will necessitate using VOP3, there will be
579   // a code size increase. Try to avoid increasing code size unless we know it
580   // will save on the instruction count.
581   unsigned NumMayIncreaseSize = 0;
582   MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
583 
584   // XXX - Should this limit number of uses to check?
585   for (const SDNode *U : N->uses()) {
586     if (!hasSourceMods(U))
587       return false;
588 
589     if (!opMustUseVOP3Encoding(U, VT)) {
590       if (++NumMayIncreaseSize > CostThreshold)
591         return false;
592     }
593   }
594 
595   return true;
596 }
597 
598 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
599   return MVT::i32;
600 }
601 
602 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
603   return true;
604 }
605 
606 // The backend supports 32 and 64 bit floating point immediates.
607 // FIXME: Why are we reporting vectors of FP immediates as legal?
608 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
609   EVT ScalarVT = VT.getScalarType();
610   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
611          (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
612 }
613 
614 // We don't want to shrink f64 / f32 constants.
615 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
616   EVT ScalarVT = VT.getScalarType();
617   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
618 }
619 
620 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
621                                                  ISD::LoadExtType,
622                                                  EVT NewVT) const {
623 
624   unsigned NewSize = NewVT.getStoreSizeInBits();
625 
626   // If we are reducing to a 32-bit load, this is always better.
627   if (NewSize == 32)
628     return true;
629 
630   EVT OldVT = N->getValueType(0);
631   unsigned OldSize = OldVT.getStoreSizeInBits();
632 
633   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
634   // extloads, so doing one requires using a buffer_load. In cases where we
635   // still couldn't use a scalar load, using the wider load shouldn't really
636   // hurt anything.
637 
638   // If the old size already had to be an extload, there's no harm in continuing
639   // to reduce the width.
640   return (OldSize < 32);
641 }
642 
643 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
644                                                    EVT CastTy) const {
645 
646   assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
647 
648   if (LoadTy.getScalarType() == MVT::i32)
649     return false;
650 
651   unsigned LScalarSize = LoadTy.getScalarSizeInBits();
652   unsigned CastScalarSize = CastTy.getScalarSizeInBits();
653 
654   return (LScalarSize < CastScalarSize) ||
655          (CastScalarSize >= 32);
656 }
657 
658 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
659 // profitable with the expansion for 64-bit since it's generally good to
660 // speculate things.
661 // FIXME: These should really have the size as a parameter.
662 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
663   return true;
664 }
665 
666 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
667   return true;
668 }
669 
670 //===---------------------------------------------------------------------===//
671 // Target Properties
672 //===---------------------------------------------------------------------===//
673 
674 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
675   assert(VT.isFloatingPoint());
676 
677   // Packed operations do not have a fabs modifier.
678   return VT == MVT::f32 || VT == MVT::f64 ||
679          (Subtarget->has16BitInsts() && VT == MVT::f16);
680 }
681 
682 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
683   assert(VT.isFloatingPoint());
684   return VT == MVT::f32 || VT == MVT::f64 ||
685          (Subtarget->has16BitInsts() && VT == MVT::f16) ||
686          (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
687 }
688 
689 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
690                                                          unsigned NumElem,
691                                                          unsigned AS) const {
692   return true;
693 }
694 
695 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
696   // There are few operations which truly have vector input operands. Any vector
697   // operation is going to involve operations on each component, and a
698   // build_vector will be a copy per element, so it always makes sense to use a
699   // build_vector input in place of the extracted element to avoid a copy into a
700   // super register.
701   //
702   // We should probably only do this if all users are extracts only, but this
703   // should be the common case.
704   return true;
705 }
706 
707 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
708   // Truncate is just accessing a subregister.
709 
710   unsigned SrcSize = Source.getSizeInBits();
711   unsigned DestSize = Dest.getSizeInBits();
712 
713   return DestSize < SrcSize && DestSize % 32 == 0 ;
714 }
715 
716 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
717   // Truncate is just accessing a subregister.
718 
719   unsigned SrcSize = Source->getScalarSizeInBits();
720   unsigned DestSize = Dest->getScalarSizeInBits();
721 
722   if (DestSize== 16 && Subtarget->has16BitInsts())
723     return SrcSize >= 32;
724 
725   return DestSize < SrcSize && DestSize % 32 == 0;
726 }
727 
728 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
729   unsigned SrcSize = Src->getScalarSizeInBits();
730   unsigned DestSize = Dest->getScalarSizeInBits();
731 
732   if (SrcSize == 16 && Subtarget->has16BitInsts())
733     return DestSize >= 32;
734 
735   return SrcSize == 32 && DestSize == 64;
736 }
737 
738 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
739   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
740   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
741   // this will enable reducing 64-bit operations the 32-bit, which is always
742   // good.
743 
744   if (Src == MVT::i16)
745     return Dest == MVT::i32 ||Dest == MVT::i64 ;
746 
747   return Src == MVT::i32 && Dest == MVT::i64;
748 }
749 
750 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
751   return isZExtFree(Val.getValueType(), VT2);
752 }
753 
754 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
755   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
756   // limited number of native 64-bit operations. Shrinking an operation to fit
757   // in a single 32-bit register should always be helpful. As currently used,
758   // this is much less general than the name suggests, and is only used in
759   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
760   // not profitable, and may actually be harmful.
761   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
762 }
763 
764 //===---------------------------------------------------------------------===//
765 // TargetLowering Callbacks
766 //===---------------------------------------------------------------------===//
767 
768 CCAssignFn *AMDGPUCallLowering::CCAssignFnForCall(CallingConv::ID CC,
769                                                   bool IsVarArg) const {
770   return CC_AMDGPU;
771 }
772 
773 /// The SelectionDAGBuilder will automatically promote function arguments
774 /// with illegal types.  However, this does not work for the AMDGPU targets
775 /// since the function arguments are stored in memory as these illegal types.
776 /// In order to handle this properly we need to get the original types sizes
777 /// from the LLVM IR Function and fixup the ISD:InputArg values before
778 /// passing them to AnalyzeFormalArguments()
779 
780 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
781 /// input values across multiple registers.  Each item in the Ins array
782 /// represents a single value that will be stored in regsters.  Ins[x].VT is
783 /// the value type of the value that will be stored in the register, so
784 /// whatever SDNode we lower the argument to needs to be this type.
785 ///
786 /// In order to correctly lower the arguments we need to know the size of each
787 /// argument.  Since Ins[x].VT gives us the size of the register that will
788 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
789 /// for the orignal function argument so that we can deduce the correct memory
790 /// type to use for Ins[x].  In most cases the correct memory type will be
791 /// Ins[x].ArgVT.  However, this will not always be the case.  If, for example,
792 /// we have a kernel argument of type v8i8, this argument will be split into
793 /// 8 parts and each part will be represented by its own item in the Ins array.
794 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
795 /// the argument before it was split.  From this, we deduce that the memory type
796 /// for each individual part is i8.  We pass the memory type as LocVT to the
797 /// calling convention analysis function and the register type (Ins[x].VT) as
798 /// the ValVT.
799 void AMDGPUTargetLowering::analyzeFormalArgumentsCompute(CCState &State,
800                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
801   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
802     const ISD::InputArg &In = Ins[i];
803     EVT MemVT;
804 
805     unsigned NumRegs = getNumRegisters(State.getContext(), In.ArgVT);
806 
807     if (!Subtarget->isAmdHsaOS() &&
808         (In.ArgVT == MVT::i16 || In.ArgVT == MVT::i8 || In.ArgVT == MVT::f16)) {
809       // The ABI says the caller will extend these values to 32-bits.
810       MemVT = In.ArgVT.isInteger() ? MVT::i32 : MVT::f32;
811     } else if (NumRegs == 1) {
812       // This argument is not split, so the IR type is the memory type.
813       assert(!In.Flags.isSplit());
814       if (In.ArgVT.isExtended()) {
815         // We have an extended type, like i24, so we should just use the register type
816         MemVT = In.VT;
817       } else {
818         MemVT = In.ArgVT;
819       }
820     } else if (In.ArgVT.isVector() && In.VT.isVector() &&
821                In.ArgVT.getScalarType() == In.VT.getScalarType()) {
822       assert(In.ArgVT.getVectorNumElements() > In.VT.getVectorNumElements());
823       // We have a vector value which has been split into a vector with
824       // the same scalar type, but fewer elements.  This should handle
825       // all the floating-point vector types.
826       MemVT = In.VT;
827     } else if (In.ArgVT.isVector() &&
828                In.ArgVT.getVectorNumElements() == NumRegs) {
829       // This arg has been split so that each element is stored in a separate
830       // register.
831       MemVT = In.ArgVT.getScalarType();
832     } else if (In.ArgVT.isExtended()) {
833       // We have an extended type, like i65.
834       MemVT = In.VT;
835     } else {
836       unsigned MemoryBits = In.ArgVT.getStoreSizeInBits() / NumRegs;
837       assert(In.ArgVT.getStoreSizeInBits() % NumRegs == 0);
838       if (In.VT.isInteger()) {
839         MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
840       } else if (In.VT.isVector()) {
841         assert(!In.VT.getScalarType().isFloatingPoint());
842         unsigned NumElements = In.VT.getVectorNumElements();
843         assert(MemoryBits % NumElements == 0);
844         // This vector type has been split into another vector type with
845         // a different elements size.
846         EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
847                                          MemoryBits / NumElements);
848         MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
849       } else {
850         llvm_unreachable("cannot deduce memory type.");
851       }
852     }
853 
854     // Convert one element vectors to scalar.
855     if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
856       MemVT = MemVT.getScalarType();
857 
858     if (MemVT.isExtended()) {
859       // This should really only happen if we have vec3 arguments
860       assert(MemVT.isVector() && MemVT.getVectorNumElements() == 3);
861       MemVT = MemVT.getPow2VectorType(State.getContext());
862     }
863 
864     assert(MemVT.isSimple());
865     allocateKernArg(i, In.VT, MemVT.getSimpleVT(), CCValAssign::Full, In.Flags,
866                     State);
867   }
868 }
869 
870 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
871                               const SmallVectorImpl<ISD::InputArg> &Ins) const {
872   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
873 }
874 
875 void AMDGPUTargetLowering::AnalyzeReturn(CCState &State,
876                            const SmallVectorImpl<ISD::OutputArg> &Outs) const {
877 
878   State.AnalyzeReturn(Outs, RetCC_SI);
879 }
880 
881 SDValue
882 AMDGPUTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
883                                   bool isVarArg,
884                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
885                                   const SmallVectorImpl<SDValue> &OutVals,
886                                   const SDLoc &DL, SelectionDAG &DAG) const {
887   return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
888 }
889 
890 //===---------------------------------------------------------------------===//
891 // Target specific lowering
892 //===---------------------------------------------------------------------===//
893 
894 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
895                                         SmallVectorImpl<SDValue> &InVals) const {
896   SDValue Callee = CLI.Callee;
897   SelectionDAG &DAG = CLI.DAG;
898 
899   const Function &Fn = *DAG.getMachineFunction().getFunction();
900 
901   StringRef FuncName("<unknown>");
902 
903   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
904     FuncName = G->getSymbol();
905   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
906     FuncName = G->getGlobal()->getName();
907 
908   DiagnosticInfoUnsupported NoCalls(
909       Fn, "unsupported call to function " + FuncName, CLI.DL.getDebugLoc());
910   DAG.getContext()->diagnose(NoCalls);
911 
912   if (!CLI.IsTailCall) {
913     for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
914       InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
915   }
916 
917   return DAG.getEntryNode();
918 }
919 
920 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
921                                                       SelectionDAG &DAG) const {
922   const Function &Fn = *DAG.getMachineFunction().getFunction();
923 
924   DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
925                                             SDLoc(Op).getDebugLoc());
926   DAG.getContext()->diagnose(NoDynamicAlloca);
927   auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
928   return DAG.getMergeValues(Ops, SDLoc());
929 }
930 
931 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
932                                              SelectionDAG &DAG) const {
933   switch (Op.getOpcode()) {
934   default:
935     Op->print(errs(), &DAG);
936     llvm_unreachable("Custom lowering code for this"
937                      "instruction is not implemented yet!");
938     break;
939   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
940   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
941   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
942   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
943   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
944   case ISD::FREM: return LowerFREM(Op, DAG);
945   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
946   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
947   case ISD::FRINT: return LowerFRINT(Op, DAG);
948   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
949   case ISD::FROUND: return LowerFROUND(Op, DAG);
950   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
951   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
952   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
953   case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
954   case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
955   case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
956   case ISD::CTLZ:
957   case ISD::CTLZ_ZERO_UNDEF:
958     return LowerCTLZ(Op, DAG);
959   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
960   }
961   return Op;
962 }
963 
964 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
965                                               SmallVectorImpl<SDValue> &Results,
966                                               SelectionDAG &DAG) const {
967   switch (N->getOpcode()) {
968   case ISD::SIGN_EXTEND_INREG:
969     // Different parts of legalization seem to interpret which type of
970     // sign_extend_inreg is the one to check for custom lowering. The extended
971     // from type is what really matters, but some places check for custom
972     // lowering of the result type. This results in trying to use
973     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
974     // nothing here and let the illegal result integer be handled normally.
975     return;
976   default:
977     return;
978   }
979 }
980 
981 static bool hasDefinedInitializer(const GlobalValue *GV) {
982   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
983   if (!GVar || !GVar->hasInitializer())
984     return false;
985 
986   return !isa<UndefValue>(GVar->getInitializer());
987 }
988 
989 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
990                                                  SDValue Op,
991                                                  SelectionDAG &DAG) const {
992 
993   const DataLayout &DL = DAG.getDataLayout();
994   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
995   const GlobalValue *GV = G->getGlobal();
996 
997   if  (G->getAddressSpace() == AMDGPUASI.LOCAL_ADDRESS) {
998     // XXX: What does the value of G->getOffset() mean?
999     assert(G->getOffset() == 0 &&
1000          "Do not know what to do with an non-zero offset");
1001 
1002     // TODO: We could emit code to handle the initialization somewhere.
1003     if (!hasDefinedInitializer(GV)) {
1004       unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
1005       return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1006     }
1007   }
1008 
1009   const Function &Fn = *DAG.getMachineFunction().getFunction();
1010   DiagnosticInfoUnsupported BadInit(
1011       Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1012   DAG.getContext()->diagnose(BadInit);
1013   return SDValue();
1014 }
1015 
1016 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
1017                                                   SelectionDAG &DAG) const {
1018   SmallVector<SDValue, 8> Args;
1019 
1020   for (const SDUse &U : Op->ops())
1021     DAG.ExtractVectorElements(U.get(), Args);
1022 
1023   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1024 }
1025 
1026 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
1027                                                      SelectionDAG &DAG) const {
1028 
1029   SmallVector<SDValue, 8> Args;
1030   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1031   EVT VT = Op.getValueType();
1032   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1033                             VT.getVectorNumElements());
1034 
1035   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1036 }
1037 
1038 /// \brief Generate Min/Max node
1039 SDValue AMDGPUTargetLowering::combineFMinMaxLegacy(const SDLoc &DL, EVT VT,
1040                                                    SDValue LHS, SDValue RHS,
1041                                                    SDValue True, SDValue False,
1042                                                    SDValue CC,
1043                                                    DAGCombinerInfo &DCI) const {
1044   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1045     return SDValue();
1046 
1047   SelectionDAG &DAG = DCI.DAG;
1048   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1049   switch (CCOpcode) {
1050   case ISD::SETOEQ:
1051   case ISD::SETONE:
1052   case ISD::SETUNE:
1053   case ISD::SETNE:
1054   case ISD::SETUEQ:
1055   case ISD::SETEQ:
1056   case ISD::SETFALSE:
1057   case ISD::SETFALSE2:
1058   case ISD::SETTRUE:
1059   case ISD::SETTRUE2:
1060   case ISD::SETUO:
1061   case ISD::SETO:
1062     break;
1063   case ISD::SETULE:
1064   case ISD::SETULT: {
1065     if (LHS == True)
1066       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1067     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1068   }
1069   case ISD::SETOLE:
1070   case ISD::SETOLT:
1071   case ISD::SETLE:
1072   case ISD::SETLT: {
1073     // Ordered. Assume ordered for undefined.
1074 
1075     // Only do this after legalization to avoid interfering with other combines
1076     // which might occur.
1077     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1078         !DCI.isCalledByLegalizer())
1079       return SDValue();
1080 
1081     // We need to permute the operands to get the correct NaN behavior. The
1082     // selected operand is the second one based on the failing compare with NaN,
1083     // so permute it based on the compare type the hardware uses.
1084     if (LHS == True)
1085       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1086     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1087   }
1088   case ISD::SETUGE:
1089   case ISD::SETUGT: {
1090     if (LHS == True)
1091       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1092     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1093   }
1094   case ISD::SETGT:
1095   case ISD::SETGE:
1096   case ISD::SETOGE:
1097   case ISD::SETOGT: {
1098     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1099         !DCI.isCalledByLegalizer())
1100       return SDValue();
1101 
1102     if (LHS == True)
1103       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1104     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1105   }
1106   case ISD::SETCC_INVALID:
1107     llvm_unreachable("Invalid setcc condcode!");
1108   }
1109   return SDValue();
1110 }
1111 
1112 std::pair<SDValue, SDValue>
1113 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1114   SDLoc SL(Op);
1115 
1116   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1117 
1118   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1119   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1120 
1121   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1122   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1123 
1124   return std::make_pair(Lo, Hi);
1125 }
1126 
1127 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1128   SDLoc SL(Op);
1129 
1130   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1131   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1132   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1133 }
1134 
1135 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1136   SDLoc SL(Op);
1137 
1138   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1139   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1140   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1141 }
1142 
1143 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1144                                               SelectionDAG &DAG) const {
1145   LoadSDNode *Load = cast<LoadSDNode>(Op);
1146   EVT VT = Op.getValueType();
1147 
1148 
1149   // If this is a 2 element vector, we really want to scalarize and not create
1150   // weird 1 element vectors.
1151   if (VT.getVectorNumElements() == 2)
1152     return scalarizeVectorLoad(Load, DAG);
1153 
1154   SDValue BasePtr = Load->getBasePtr();
1155   EVT PtrVT = BasePtr.getValueType();
1156   EVT MemVT = Load->getMemoryVT();
1157   SDLoc SL(Op);
1158 
1159   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1160 
1161   EVT LoVT, HiVT;
1162   EVT LoMemVT, HiMemVT;
1163   SDValue Lo, Hi;
1164 
1165   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1166   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1167   std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1168 
1169   unsigned Size = LoMemVT.getStoreSize();
1170   unsigned BaseAlign = Load->getAlignment();
1171   unsigned HiAlign = MinAlign(BaseAlign, Size);
1172 
1173   SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1174                                   Load->getChain(), BasePtr, SrcValue, LoMemVT,
1175                                   BaseAlign, Load->getMemOperand()->getFlags());
1176   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1177                               DAG.getConstant(Size, SL, PtrVT));
1178   SDValue HiLoad =
1179       DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1180                      HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1181                      HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1182 
1183   SDValue Ops[] = {
1184     DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1185     DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1186                 LoLoad.getValue(1), HiLoad.getValue(1))
1187   };
1188 
1189   return DAG.getMergeValues(Ops, SL);
1190 }
1191 
1192 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1193                                                SelectionDAG &DAG) const {
1194   StoreSDNode *Store = cast<StoreSDNode>(Op);
1195   SDValue Val = Store->getValue();
1196   EVT VT = Val.getValueType();
1197 
1198   // If this is a 2 element vector, we really want to scalarize and not create
1199   // weird 1 element vectors.
1200   if (VT.getVectorNumElements() == 2)
1201     return scalarizeVectorStore(Store, DAG);
1202 
1203   EVT MemVT = Store->getMemoryVT();
1204   SDValue Chain = Store->getChain();
1205   SDValue BasePtr = Store->getBasePtr();
1206   SDLoc SL(Op);
1207 
1208   EVT LoVT, HiVT;
1209   EVT LoMemVT, HiMemVT;
1210   SDValue Lo, Hi;
1211 
1212   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1213   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1214   std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1215 
1216   EVT PtrVT = BasePtr.getValueType();
1217   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1218                               DAG.getConstant(LoMemVT.getStoreSize(), SL,
1219                                               PtrVT));
1220 
1221   const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1222   unsigned BaseAlign = Store->getAlignment();
1223   unsigned Size = LoMemVT.getStoreSize();
1224   unsigned HiAlign = MinAlign(BaseAlign, Size);
1225 
1226   SDValue LoStore =
1227       DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1228                         Store->getMemOperand()->getFlags());
1229   SDValue HiStore =
1230       DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1231                         HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1232 
1233   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1234 }
1235 
1236 // This is a shortcut for integer division because we have fast i32<->f32
1237 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1238 // float is enough to accurately represent up to a 24-bit signed integer.
1239 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG,
1240                                             bool Sign) const {
1241   SDLoc DL(Op);
1242   EVT VT = Op.getValueType();
1243   SDValue LHS = Op.getOperand(0);
1244   SDValue RHS = Op.getOperand(1);
1245   MVT IntVT = MVT::i32;
1246   MVT FltVT = MVT::f32;
1247 
1248   unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1249   if (LHSSignBits < 9)
1250     return SDValue();
1251 
1252   unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1253   if (RHSSignBits < 9)
1254     return SDValue();
1255 
1256   unsigned BitSize = VT.getSizeInBits();
1257   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1258   unsigned DivBits = BitSize - SignBits;
1259   if (Sign)
1260     ++DivBits;
1261 
1262   ISD::NodeType ToFp = Sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1263   ISD::NodeType ToInt = Sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1264 
1265   SDValue jq = DAG.getConstant(1, DL, IntVT);
1266 
1267   if (Sign) {
1268     // char|short jq = ia ^ ib;
1269     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1270 
1271     // jq = jq >> (bitsize - 2)
1272     jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1273                      DAG.getConstant(BitSize - 2, DL, VT));
1274 
1275     // jq = jq | 0x1
1276     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1277   }
1278 
1279   // int ia = (int)LHS;
1280   SDValue ia = LHS;
1281 
1282   // int ib, (int)RHS;
1283   SDValue ib = RHS;
1284 
1285   // float fa = (float)ia;
1286   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1287 
1288   // float fb = (float)ib;
1289   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1290 
1291   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1292                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1293 
1294   // fq = trunc(fq);
1295   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1296 
1297   // float fqneg = -fq;
1298   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1299 
1300   // float fr = mad(fqneg, fb, fa);
1301   unsigned OpCode = Subtarget->hasFP32Denormals() ?
1302                     (unsigned)AMDGPUISD::FMAD_FTZ :
1303                     (unsigned)ISD::FMAD;
1304   SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1305 
1306   // int iq = (int)fq;
1307   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1308 
1309   // fr = fabs(fr);
1310   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1311 
1312   // fb = fabs(fb);
1313   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1314 
1315   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1316 
1317   // int cv = fr >= fb;
1318   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1319 
1320   // jq = (cv ? jq : 0);
1321   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1322 
1323   // dst = iq + jq;
1324   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1325 
1326   // Rem needs compensation, it's easier to recompute it
1327   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1328   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1329 
1330   // Truncate to number of bits this divide really is.
1331   if (Sign) {
1332     SDValue InRegSize
1333       = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1334     Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1335     Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1336   } else {
1337     SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1338     Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1339     Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1340   }
1341 
1342   return DAG.getMergeValues({ Div, Rem }, DL);
1343 }
1344 
1345 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1346                                       SelectionDAG &DAG,
1347                                       SmallVectorImpl<SDValue> &Results) const {
1348   assert(Op.getValueType() == MVT::i64);
1349 
1350   SDLoc DL(Op);
1351   EVT VT = Op.getValueType();
1352   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1353 
1354   SDValue one = DAG.getConstant(1, DL, HalfVT);
1355   SDValue zero = DAG.getConstant(0, DL, HalfVT);
1356 
1357   //HiLo split
1358   SDValue LHS = Op.getOperand(0);
1359   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
1360   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
1361 
1362   SDValue RHS = Op.getOperand(1);
1363   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
1364   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
1365 
1366   if (VT == MVT::i64 &&
1367     DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1368     DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1369 
1370     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1371                               LHS_Lo, RHS_Lo);
1372 
1373     SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), zero});
1374     SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), zero});
1375 
1376     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1377     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1378     return;
1379   }
1380 
1381   // Get Speculative values
1382   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1383   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1384 
1385   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
1386   SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, zero});
1387   REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1388 
1389   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
1390   SDValue DIV_Lo = zero;
1391 
1392   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1393 
1394   for (unsigned i = 0; i < halfBitWidth; ++i) {
1395     const unsigned bitPos = halfBitWidth - i - 1;
1396     SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1397     // Get value of high bit
1398     SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1399     HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
1400     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1401 
1402     // Shift
1403     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1404     // Add LHS high bit
1405     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1406 
1407     SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1408     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETUGE);
1409 
1410     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1411 
1412     // Update REM
1413     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1414     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1415   }
1416 
1417   SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1418   DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1419   Results.push_back(DIV);
1420   Results.push_back(REM);
1421 }
1422 
1423 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1424                                            SelectionDAG &DAG) const {
1425   SDLoc DL(Op);
1426   EVT VT = Op.getValueType();
1427 
1428   if (VT == MVT::i64) {
1429     SmallVector<SDValue, 2> Results;
1430     LowerUDIVREM64(Op, DAG, Results);
1431     return DAG.getMergeValues(Results, DL);
1432   }
1433 
1434   if (VT == MVT::i32) {
1435     if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1436       return Res;
1437   }
1438 
1439   SDValue Num = Op.getOperand(0);
1440   SDValue Den = Op.getOperand(1);
1441 
1442   // RCP =  URECIP(Den) = 2^32 / Den + e
1443   // e is rounding error.
1444   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1445 
1446   // RCP_LO = mul(RCP, Den) */
1447   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1448 
1449   // RCP_HI = mulhu (RCP, Den) */
1450   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1451 
1452   // NEG_RCP_LO = -RCP_LO
1453   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1454                                                      RCP_LO);
1455 
1456   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1457   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1458                                            NEG_RCP_LO, RCP_LO,
1459                                            ISD::SETEQ);
1460   // Calculate the rounding error from the URECIP instruction
1461   // E = mulhu(ABS_RCP_LO, RCP)
1462   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1463 
1464   // RCP_A_E = RCP + E
1465   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1466 
1467   // RCP_S_E = RCP - E
1468   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1469 
1470   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1471   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1472                                      RCP_A_E, RCP_S_E,
1473                                      ISD::SETEQ);
1474   // Quotient = mulhu(Tmp0, Num)
1475   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1476 
1477   // Num_S_Remainder = Quotient * Den
1478   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1479 
1480   // Remainder = Num - Num_S_Remainder
1481   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1482 
1483   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1484   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1485                                                  DAG.getConstant(-1, DL, VT),
1486                                                  DAG.getConstant(0, DL, VT),
1487                                                  ISD::SETUGE);
1488   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1489   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1490                                                   Num_S_Remainder,
1491                                                   DAG.getConstant(-1, DL, VT),
1492                                                   DAG.getConstant(0, DL, VT),
1493                                                   ISD::SETUGE);
1494   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1495   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1496                                                Remainder_GE_Zero);
1497 
1498   // Calculate Division result:
1499 
1500   // Quotient_A_One = Quotient + 1
1501   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1502                                        DAG.getConstant(1, DL, VT));
1503 
1504   // Quotient_S_One = Quotient - 1
1505   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1506                                        DAG.getConstant(1, DL, VT));
1507 
1508   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1509   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1510                                      Quotient, Quotient_A_One, ISD::SETEQ);
1511 
1512   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1513   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1514                             Quotient_S_One, Div, ISD::SETEQ);
1515 
1516   // Calculate Rem result:
1517 
1518   // Remainder_S_Den = Remainder - Den
1519   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1520 
1521   // Remainder_A_Den = Remainder + Den
1522   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1523 
1524   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1525   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1526                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1527 
1528   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1529   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1530                             Remainder_A_Den, Rem, ISD::SETEQ);
1531   SDValue Ops[2] = {
1532     Div,
1533     Rem
1534   };
1535   return DAG.getMergeValues(Ops, DL);
1536 }
1537 
1538 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1539                                            SelectionDAG &DAG) const {
1540   SDLoc DL(Op);
1541   EVT VT = Op.getValueType();
1542 
1543   SDValue LHS = Op.getOperand(0);
1544   SDValue RHS = Op.getOperand(1);
1545 
1546   SDValue Zero = DAG.getConstant(0, DL, VT);
1547   SDValue NegOne = DAG.getConstant(-1, DL, VT);
1548 
1549   if (VT == MVT::i32) {
1550     if (SDValue Res = LowerDIVREM24(Op, DAG, true))
1551       return Res;
1552   }
1553 
1554   if (VT == MVT::i64 &&
1555       DAG.ComputeNumSignBits(LHS) > 32 &&
1556       DAG.ComputeNumSignBits(RHS) > 32) {
1557     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1558 
1559     //HiLo split
1560     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1561     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1562     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1563                                  LHS_Lo, RHS_Lo);
1564     SDValue Res[2] = {
1565       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1566       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1567     };
1568     return DAG.getMergeValues(Res, DL);
1569   }
1570 
1571   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1572   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1573   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1574   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1575 
1576   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1577   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1578 
1579   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1580   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1581 
1582   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1583   SDValue Rem = Div.getValue(1);
1584 
1585   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1586   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1587 
1588   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1589   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1590 
1591   SDValue Res[2] = {
1592     Div,
1593     Rem
1594   };
1595   return DAG.getMergeValues(Res, DL);
1596 }
1597 
1598 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1599 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
1600   SDLoc SL(Op);
1601   EVT VT = Op.getValueType();
1602   SDValue X = Op.getOperand(0);
1603   SDValue Y = Op.getOperand(1);
1604 
1605   // TODO: Should this propagate fast-math-flags?
1606 
1607   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1608   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1609   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1610 
1611   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1612 }
1613 
1614 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1615   SDLoc SL(Op);
1616   SDValue Src = Op.getOperand(0);
1617 
1618   // result = trunc(src)
1619   // if (src > 0.0 && src != result)
1620   //   result += 1.0
1621 
1622   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1623 
1624   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1625   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1626 
1627   EVT SetCCVT =
1628       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1629 
1630   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1631   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1632   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1633 
1634   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1635   // TODO: Should this propagate fast-math-flags?
1636   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1637 }
1638 
1639 static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL,
1640                                   SelectionDAG &DAG) {
1641   const unsigned FractBits = 52;
1642   const unsigned ExpBits = 11;
1643 
1644   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
1645                                 Hi,
1646                                 DAG.getConstant(FractBits - 32, SL, MVT::i32),
1647                                 DAG.getConstant(ExpBits, SL, MVT::i32));
1648   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1649                             DAG.getConstant(1023, SL, MVT::i32));
1650 
1651   return Exp;
1652 }
1653 
1654 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1655   SDLoc SL(Op);
1656   SDValue Src = Op.getOperand(0);
1657 
1658   assert(Op.getValueType() == MVT::f64);
1659 
1660   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1661   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1662 
1663   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1664 
1665   // Extract the upper half, since this is where we will find the sign and
1666   // exponent.
1667   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1668 
1669   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1670 
1671   const unsigned FractBits = 52;
1672 
1673   // Extract the sign bit.
1674   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
1675   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1676 
1677   // Extend back to to 64-bits.
1678   SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
1679   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1680 
1681   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1682   const SDValue FractMask
1683     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
1684 
1685   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1686   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1687   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1688 
1689   EVT SetCCVT =
1690       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1691 
1692   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
1693 
1694   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1695   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1696 
1697   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1698   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1699 
1700   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1701 }
1702 
1703 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1704   SDLoc SL(Op);
1705   SDValue Src = Op.getOperand(0);
1706 
1707   assert(Op.getValueType() == MVT::f64);
1708 
1709   APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
1710   SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
1711   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1712 
1713   // TODO: Should this propagate fast-math-flags?
1714 
1715   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1716   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1717 
1718   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1719 
1720   APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
1721   SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
1722 
1723   EVT SetCCVT =
1724       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1725   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1726 
1727   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1728 }
1729 
1730 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
1731   // FNEARBYINT and FRINT are the same, except in their handling of FP
1732   // exceptions. Those aren't really meaningful for us, and OpenCL only has
1733   // rint, so just treat them as equivalent.
1734   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
1735 }
1736 
1737 // XXX - May require not supporting f32 denormals?
1738 
1739 // Don't handle v2f16. The extra instructions to scalarize and repack around the
1740 // compare and vselect end up producing worse code than scalarizing the whole
1741 // operation.
1742 SDValue AMDGPUTargetLowering::LowerFROUND32_16(SDValue Op, SelectionDAG &DAG) const {
1743   SDLoc SL(Op);
1744   SDValue X = Op.getOperand(0);
1745   EVT VT = Op.getValueType();
1746 
1747   SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
1748 
1749   // TODO: Should this propagate fast-math-flags?
1750 
1751   SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
1752 
1753   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
1754 
1755   const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
1756   const SDValue One = DAG.getConstantFP(1.0, SL, VT);
1757   const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
1758 
1759   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
1760 
1761   EVT SetCCVT =
1762       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1763 
1764   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
1765 
1766   SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
1767 
1768   return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
1769 }
1770 
1771 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
1772   SDLoc SL(Op);
1773   SDValue X = Op.getOperand(0);
1774 
1775   SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
1776 
1777   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1778   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1779   const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
1780   const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
1781   EVT SetCCVT =
1782       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1783 
1784   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1785 
1786   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
1787 
1788   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1789 
1790   const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
1791                                        MVT::i64);
1792 
1793   SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
1794   SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
1795                           DAG.getConstant(INT64_C(0x0008000000000000), SL,
1796                                           MVT::i64),
1797                           Exp);
1798 
1799   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
1800   SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
1801                               DAG.getConstant(0, SL, MVT::i64), Tmp0,
1802                               ISD::SETNE);
1803 
1804   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
1805                              D, DAG.getConstant(0, SL, MVT::i64));
1806   SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
1807 
1808   K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
1809   K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
1810 
1811   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1812   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1813   SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
1814 
1815   SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
1816                             ExpEqNegOne,
1817                             DAG.getConstantFP(1.0, SL, MVT::f64),
1818                             DAG.getConstantFP(0.0, SL, MVT::f64));
1819 
1820   SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
1821 
1822   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
1823   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
1824 
1825   return K;
1826 }
1827 
1828 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
1829   EVT VT = Op.getValueType();
1830 
1831   if (VT == MVT::f32 || VT == MVT::f16)
1832     return LowerFROUND32_16(Op, DAG);
1833 
1834   if (VT == MVT::f64)
1835     return LowerFROUND64(Op, DAG);
1836 
1837   llvm_unreachable("unhandled type");
1838 }
1839 
1840 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1841   SDLoc SL(Op);
1842   SDValue Src = Op.getOperand(0);
1843 
1844   // result = trunc(src);
1845   // if (src < 0.0 && src != result)
1846   //   result += -1.0.
1847 
1848   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1849 
1850   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1851   const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
1852 
1853   EVT SetCCVT =
1854       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1855 
1856   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1857   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1858   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1859 
1860   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1861   // TODO: Should this propagate fast-math-flags?
1862   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1863 }
1864 
1865 SDValue AMDGPUTargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
1866   SDLoc SL(Op);
1867   SDValue Src = Op.getOperand(0);
1868   bool ZeroUndef = Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF;
1869 
1870   if (ZeroUndef && Src.getValueType() == MVT::i32)
1871     return DAG.getNode(AMDGPUISD::FFBH_U32, SL, MVT::i32, Src);
1872 
1873   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1874 
1875   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1876   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1877 
1878   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1879   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1880 
1881   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
1882                                    *DAG.getContext(), MVT::i32);
1883 
1884   SDValue Hi0 = DAG.getSetCC(SL, SetCCVT, Hi, Zero, ISD::SETEQ);
1885 
1886   SDValue CtlzLo = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Lo);
1887   SDValue CtlzHi = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Hi);
1888 
1889   const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
1890   SDValue Add = DAG.getNode(ISD::ADD, SL, MVT::i32, CtlzLo, Bits32);
1891 
1892   // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
1893   SDValue NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0, Add, CtlzHi);
1894 
1895   if (!ZeroUndef) {
1896     // Test if the full 64-bit input is zero.
1897 
1898     // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
1899     // which we probably don't want.
1900     SDValue Lo0 = DAG.getSetCC(SL, SetCCVT, Lo, Zero, ISD::SETEQ);
1901     SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0, Hi0);
1902 
1903     // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
1904     // with the same cycles, otherwise it is slower.
1905     // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
1906     // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
1907 
1908     const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
1909 
1910     // The instruction returns -1 for 0 input, but the defined intrinsic
1911     // behavior is to return the number of bits.
1912     NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32,
1913                           SrcIsZero, Bits32, NewCtlz);
1914   }
1915 
1916   return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewCtlz);
1917 }
1918 
1919 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
1920                                                bool Signed) const {
1921   // Unsigned
1922   // cul2f(ulong u)
1923   //{
1924   //  uint lz = clz(u);
1925   //  uint e = (u != 0) ? 127U + 63U - lz : 0;
1926   //  u = (u << lz) & 0x7fffffffffffffffUL;
1927   //  ulong t = u & 0xffffffffffUL;
1928   //  uint v = (e << 23) | (uint)(u >> 40);
1929   //  uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
1930   //  return as_float(v + r);
1931   //}
1932   // Signed
1933   // cl2f(long l)
1934   //{
1935   //  long s = l >> 63;
1936   //  float r = cul2f((l + s) ^ s);
1937   //  return s ? -r : r;
1938   //}
1939 
1940   SDLoc SL(Op);
1941   SDValue Src = Op.getOperand(0);
1942   SDValue L = Src;
1943 
1944   SDValue S;
1945   if (Signed) {
1946     const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
1947     S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
1948 
1949     SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
1950     L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
1951   }
1952 
1953   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
1954                                    *DAG.getContext(), MVT::f32);
1955 
1956 
1957   SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
1958   SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
1959   SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
1960   LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
1961 
1962   SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
1963   SDValue E = DAG.getSelect(SL, MVT::i32,
1964     DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
1965     DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
1966     ZeroI32);
1967 
1968   SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
1969     DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
1970     DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
1971 
1972   SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
1973                           DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
1974 
1975   SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
1976                              U, DAG.getConstant(40, SL, MVT::i64));
1977 
1978   SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
1979     DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
1980     DAG.getNode(ISD::TRUNCATE, SL, MVT::i32,  UShl));
1981 
1982   SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
1983   SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
1984   SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
1985 
1986   SDValue One = DAG.getConstant(1, SL, MVT::i32);
1987 
1988   SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
1989 
1990   SDValue R = DAG.getSelect(SL, MVT::i32,
1991     RCmp,
1992     One,
1993     DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
1994   R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
1995   R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
1996 
1997   if (!Signed)
1998     return R;
1999 
2000   SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2001   return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2002 }
2003 
2004 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2005                                                bool Signed) const {
2006   SDLoc SL(Op);
2007   SDValue Src = Op.getOperand(0);
2008 
2009   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2010 
2011   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2012                            DAG.getConstant(0, SL, MVT::i32));
2013   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2014                            DAG.getConstant(1, SL, MVT::i32));
2015 
2016   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2017                               SL, MVT::f64, Hi);
2018 
2019   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2020 
2021   SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2022                               DAG.getConstant(32, SL, MVT::i32));
2023   // TODO: Should this propagate fast-math-flags?
2024   return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2025 }
2026 
2027 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2028                                                SelectionDAG &DAG) const {
2029   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2030          "operation should be legal");
2031 
2032   // TODO: Factor out code common with LowerSINT_TO_FP.
2033 
2034   EVT DestVT = Op.getValueType();
2035   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2036     SDLoc DL(Op);
2037     SDValue Src = Op.getOperand(0);
2038 
2039     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2040     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2041     SDValue FPRound =
2042         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2043 
2044     return FPRound;
2045   }
2046 
2047   if (DestVT == MVT::f32)
2048     return LowerINT_TO_FP32(Op, DAG, false);
2049 
2050   assert(DestVT == MVT::f64);
2051   return LowerINT_TO_FP64(Op, DAG, false);
2052 }
2053 
2054 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2055                                               SelectionDAG &DAG) const {
2056   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2057          "operation should be legal");
2058 
2059   // TODO: Factor out code common with LowerUINT_TO_FP.
2060 
2061   EVT DestVT = Op.getValueType();
2062   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2063     SDLoc DL(Op);
2064     SDValue Src = Op.getOperand(0);
2065 
2066     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2067     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2068     SDValue FPRound =
2069         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2070 
2071     return FPRound;
2072   }
2073 
2074   if (DestVT == MVT::f32)
2075     return LowerINT_TO_FP32(Op, DAG, true);
2076 
2077   assert(DestVT == MVT::f64);
2078   return LowerINT_TO_FP64(Op, DAG, true);
2079 }
2080 
2081 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2082                                                bool Signed) const {
2083   SDLoc SL(Op);
2084 
2085   SDValue Src = Op.getOperand(0);
2086 
2087   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2088 
2089   SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2090                                  MVT::f64);
2091   SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2092                                  MVT::f64);
2093   // TODO: Should this propagate fast-math-flags?
2094   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2095 
2096   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2097 
2098 
2099   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2100 
2101   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2102                            MVT::i32, FloorMul);
2103   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2104 
2105   SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2106 
2107   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2108 }
2109 
2110 SDValue AMDGPUTargetLowering::LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) const {
2111   SDLoc DL(Op);
2112   SDValue N0 = Op.getOperand(0);
2113 
2114   // Convert to target node to get known bits
2115   if (N0.getValueType() == MVT::f32)
2116     return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2117 
2118   if (getTargetMachine().Options.UnsafeFPMath) {
2119     // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2120     return SDValue();
2121   }
2122 
2123   assert(N0.getSimpleValueType() == MVT::f64);
2124 
2125   // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2126   const unsigned ExpMask = 0x7ff;
2127   const unsigned ExpBiasf64 = 1023;
2128   const unsigned ExpBiasf16 = 15;
2129   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2130   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2131   SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2132   SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2133                            DAG.getConstant(32, DL, MVT::i64));
2134   UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2135   U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2136   SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2137                           DAG.getConstant(20, DL, MVT::i64));
2138   E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2139                   DAG.getConstant(ExpMask, DL, MVT::i32));
2140   // Subtract the fp64 exponent bias (1023) to get the real exponent and
2141   // add the f16 bias (15) to get the biased exponent for the f16 format.
2142   E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2143                   DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2144 
2145   SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2146                           DAG.getConstant(8, DL, MVT::i32));
2147   M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2148                   DAG.getConstant(0xffe, DL, MVT::i32));
2149 
2150   SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2151                                   DAG.getConstant(0x1ff, DL, MVT::i32));
2152   MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2153 
2154   SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2155   M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2156 
2157   // (M != 0 ? 0x0200 : 0) | 0x7c00;
2158   SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2159       DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2160                       Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2161 
2162   // N = M | (E << 12);
2163   SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2164       DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2165                   DAG.getConstant(12, DL, MVT::i32)));
2166 
2167   // B = clamp(1-E, 0, 13);
2168   SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2169                                   One, E);
2170   SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2171   B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2172                   DAG.getConstant(13, DL, MVT::i32));
2173 
2174   SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2175                                    DAG.getConstant(0x1000, DL, MVT::i32));
2176 
2177   SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2178   SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2179   SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2180   D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2181 
2182   SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2183   SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2184                               DAG.getConstant(0x7, DL, MVT::i32));
2185   V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2186                   DAG.getConstant(2, DL, MVT::i32));
2187   SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2188                                One, Zero, ISD::SETEQ);
2189   SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2190                                One, Zero, ISD::SETGT);
2191   V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2192   V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2193 
2194   V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2195                       DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2196   V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2197                       I, V, ISD::SETEQ);
2198 
2199   // Extract the sign bit.
2200   SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2201                             DAG.getConstant(16, DL, MVT::i32));
2202   Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2203                      DAG.getConstant(0x8000, DL, MVT::i32));
2204 
2205   V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2206   return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2207 }
2208 
2209 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2210                                               SelectionDAG &DAG) const {
2211   SDValue Src = Op.getOperand(0);
2212 
2213   // TODO: Factor out code common with LowerFP_TO_UINT.
2214 
2215   EVT SrcVT = Src.getValueType();
2216   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2217     SDLoc DL(Op);
2218 
2219     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2220     SDValue FpToInt32 =
2221         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2222 
2223     return FpToInt32;
2224   }
2225 
2226   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2227     return LowerFP64_TO_INT(Op, DAG, true);
2228 
2229   return SDValue();
2230 }
2231 
2232 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2233                                               SelectionDAG &DAG) const {
2234   SDValue Src = Op.getOperand(0);
2235 
2236   // TODO: Factor out code common with LowerFP_TO_SINT.
2237 
2238   EVT SrcVT = Src.getValueType();
2239   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2240     SDLoc DL(Op);
2241 
2242     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2243     SDValue FpToInt32 =
2244         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2245 
2246     return FpToInt32;
2247   }
2248 
2249   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2250     return LowerFP64_TO_INT(Op, DAG, false);
2251 
2252   return SDValue();
2253 }
2254 
2255 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2256                                                      SelectionDAG &DAG) const {
2257   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2258   MVT VT = Op.getSimpleValueType();
2259   MVT ScalarVT = VT.getScalarType();
2260 
2261   assert(VT.isVector());
2262 
2263   SDValue Src = Op.getOperand(0);
2264   SDLoc DL(Op);
2265 
2266   // TODO: Don't scalarize on Evergreen?
2267   unsigned NElts = VT.getVectorNumElements();
2268   SmallVector<SDValue, 8> Args;
2269   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2270 
2271   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2272   for (unsigned I = 0; I < NElts; ++I)
2273     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2274 
2275   return DAG.getBuildVector(VT, DL, Args);
2276 }
2277 
2278 //===----------------------------------------------------------------------===//
2279 // Custom DAG optimizations
2280 //===----------------------------------------------------------------------===//
2281 
2282 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2283   APInt KnownZero, KnownOne;
2284   EVT VT = Op.getValueType();
2285   DAG.computeKnownBits(Op, KnownZero, KnownOne);
2286 
2287   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
2288 }
2289 
2290 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2291   EVT VT = Op.getValueType();
2292 
2293   // In order for this to be a signed 24-bit value, bit 23, must
2294   // be a sign bit.
2295   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2296                                      // as unsigned 24-bit values.
2297          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
2298 }
2299 
2300 static bool simplifyI24(SDNode *Node24, unsigned OpIdx,
2301                         TargetLowering::DAGCombinerInfo &DCI) {
2302 
2303   SelectionDAG &DAG = DCI.DAG;
2304   SDValue Op = Node24->getOperand(OpIdx);
2305   EVT VT = Op.getValueType();
2306 
2307   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
2308   APInt KnownZero, KnownOne;
2309   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
2310   if (TLO.SimplifyDemandedBits(Node24, OpIdx, Demanded, DCI))
2311     return true;
2312 
2313   return false;
2314 }
2315 
2316 template <typename IntTy>
2317 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0, uint32_t Offset,
2318                                uint32_t Width, const SDLoc &DL) {
2319   if (Width + Offset < 32) {
2320     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2321     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2322     return DAG.getConstant(Result, DL, MVT::i32);
2323   }
2324 
2325   return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2326 }
2327 
2328 static bool hasVolatileUser(SDNode *Val) {
2329   for (SDNode *U : Val->uses()) {
2330     if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2331       if (M->isVolatile())
2332         return true;
2333     }
2334   }
2335 
2336   return false;
2337 }
2338 
2339 bool AMDGPUTargetLowering::shouldCombineMemoryType(EVT VT) const {
2340   // i32 vectors are the canonical memory type.
2341   if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2342     return false;
2343 
2344   if (!VT.isByteSized())
2345     return false;
2346 
2347   unsigned Size = VT.getStoreSize();
2348 
2349   if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2350     return false;
2351 
2352   if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2353     return false;
2354 
2355   return true;
2356 }
2357 
2358 // Replace load of an illegal type with a store of a bitcast to a friendlier
2359 // type.
2360 SDValue AMDGPUTargetLowering::performLoadCombine(SDNode *N,
2361                                                  DAGCombinerInfo &DCI) const {
2362   if (!DCI.isBeforeLegalize())
2363     return SDValue();
2364 
2365   LoadSDNode *LN = cast<LoadSDNode>(N);
2366   if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2367     return SDValue();
2368 
2369   SDLoc SL(N);
2370   SelectionDAG &DAG = DCI.DAG;
2371   EVT VT = LN->getMemoryVT();
2372 
2373   unsigned Size = VT.getStoreSize();
2374   unsigned Align = LN->getAlignment();
2375   if (Align < Size && isTypeLegal(VT)) {
2376     bool IsFast;
2377     unsigned AS = LN->getAddressSpace();
2378 
2379     // Expand unaligned loads earlier than legalization. Due to visitation order
2380     // problems during legalization, the emitted instructions to pack and unpack
2381     // the bytes again are not eliminated in the case of an unaligned copy.
2382     if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2383       if (VT.isVector())
2384         return scalarizeVectorLoad(LN, DAG);
2385 
2386       SDValue Ops[2];
2387       std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2388       return DAG.getMergeValues(Ops, SDLoc(N));
2389     }
2390 
2391     if (!IsFast)
2392       return SDValue();
2393   }
2394 
2395   if (!shouldCombineMemoryType(VT))
2396     return SDValue();
2397 
2398   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2399 
2400   SDValue NewLoad
2401     = DAG.getLoad(NewVT, SL, LN->getChain(),
2402                   LN->getBasePtr(), LN->getMemOperand());
2403 
2404   SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2405   DCI.CombineTo(N, BC, NewLoad.getValue(1));
2406   return SDValue(N, 0);
2407 }
2408 
2409 // Replace store of an illegal type with a store of a bitcast to a friendlier
2410 // type.
2411 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2412                                                   DAGCombinerInfo &DCI) const {
2413   if (!DCI.isBeforeLegalize())
2414     return SDValue();
2415 
2416   StoreSDNode *SN = cast<StoreSDNode>(N);
2417   if (SN->isVolatile() || !ISD::isNormalStore(SN))
2418     return SDValue();
2419 
2420   EVT VT = SN->getMemoryVT();
2421   unsigned Size = VT.getStoreSize();
2422 
2423   SDLoc SL(N);
2424   SelectionDAG &DAG = DCI.DAG;
2425   unsigned Align = SN->getAlignment();
2426   if (Align < Size && isTypeLegal(VT)) {
2427     bool IsFast;
2428     unsigned AS = SN->getAddressSpace();
2429 
2430     // Expand unaligned stores earlier than legalization. Due to visitation
2431     // order problems during legalization, the emitted instructions to pack and
2432     // unpack the bytes again are not eliminated in the case of an unaligned
2433     // copy.
2434     if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2435       if (VT.isVector())
2436         return scalarizeVectorStore(SN, DAG);
2437 
2438       return expandUnalignedStore(SN, DAG);
2439     }
2440 
2441     if (!IsFast)
2442       return SDValue();
2443   }
2444 
2445   if (!shouldCombineMemoryType(VT))
2446     return SDValue();
2447 
2448   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2449   SDValue Val = SN->getValue();
2450 
2451   //DCI.AddToWorklist(Val.getNode());
2452 
2453   bool OtherUses = !Val.hasOneUse();
2454   SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2455   if (OtherUses) {
2456     SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2457     DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2458   }
2459 
2460   return DAG.getStore(SN->getChain(), SL, CastVal,
2461                       SN->getBasePtr(), SN->getMemOperand());
2462 }
2463 
2464 SDValue AMDGPUTargetLowering::performClampCombine(SDNode *N,
2465                                                   DAGCombinerInfo &DCI) const {
2466   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
2467   if (!CSrc)
2468     return SDValue();
2469 
2470   const APFloat &F = CSrc->getValueAPF();
2471   APFloat Zero = APFloat::getZero(F.getSemantics());
2472   APFloat::cmpResult Cmp0 = F.compare(Zero);
2473   if (Cmp0 == APFloat::cmpLessThan ||
2474       (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
2475     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
2476   }
2477 
2478   APFloat One(F.getSemantics(), "1.0");
2479   APFloat::cmpResult Cmp1 = F.compare(One);
2480   if (Cmp1 == APFloat::cmpGreaterThan)
2481     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
2482 
2483   return SDValue(CSrc, 0);
2484 }
2485 
2486 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
2487 /// binary operation \p Opc to it with the corresponding constant operands.
2488 SDValue AMDGPUTargetLowering::splitBinaryBitConstantOpImpl(
2489   DAGCombinerInfo &DCI, const SDLoc &SL,
2490   unsigned Opc, SDValue LHS,
2491   uint32_t ValLo, uint32_t ValHi) const {
2492   SelectionDAG &DAG = DCI.DAG;
2493   SDValue Lo, Hi;
2494   std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
2495 
2496   SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
2497   SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
2498 
2499   SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
2500   SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
2501 
2502   // Re-visit the ands. It's possible we eliminated one of them and it could
2503   // simplify the vector.
2504   DCI.AddToWorklist(Lo.getNode());
2505   DCI.AddToWorklist(Hi.getNode());
2506 
2507   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
2508   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2509 }
2510 
2511 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
2512                                                 DAGCombinerInfo &DCI) const {
2513   if (N->getValueType(0) != MVT::i64)
2514     return SDValue();
2515 
2516   // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
2517 
2518   // On some subtargets, 64-bit shift is a quarter rate instruction. In the
2519   // common case, splitting this into a move and a 32-bit shift is faster and
2520   // the same code size.
2521   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2522   if (!RHS)
2523     return SDValue();
2524 
2525   unsigned RHSVal = RHS->getZExtValue();
2526   if (RHSVal < 32)
2527     return SDValue();
2528 
2529   SDValue LHS = N->getOperand(0);
2530 
2531   SDLoc SL(N);
2532   SelectionDAG &DAG = DCI.DAG;
2533 
2534   SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
2535 
2536   SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
2537   SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
2538 
2539   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2540 
2541   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
2542   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2543 }
2544 
2545 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
2546                                                 DAGCombinerInfo &DCI) const {
2547   if (N->getValueType(0) != MVT::i64)
2548     return SDValue();
2549 
2550   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2551   if (!RHS)
2552     return SDValue();
2553 
2554   SelectionDAG &DAG = DCI.DAG;
2555   SDLoc SL(N);
2556   unsigned RHSVal = RHS->getZExtValue();
2557 
2558   // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
2559   if (RHSVal == 32) {
2560     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2561     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2562                                    DAG.getConstant(31, SL, MVT::i32));
2563 
2564     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
2565     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2566   }
2567 
2568   // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
2569   if (RHSVal == 63) {
2570     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2571     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2572                                    DAG.getConstant(31, SL, MVT::i32));
2573     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
2574     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2575   }
2576 
2577   return SDValue();
2578 }
2579 
2580 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
2581                                                 DAGCombinerInfo &DCI) const {
2582   if (N->getValueType(0) != MVT::i64)
2583     return SDValue();
2584 
2585   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2586   if (!RHS)
2587     return SDValue();
2588 
2589   unsigned ShiftAmt = RHS->getZExtValue();
2590   if (ShiftAmt < 32)
2591     return SDValue();
2592 
2593   // srl i64:x, C for C >= 32
2594   // =>
2595   //   build_pair (srl hi_32(x), C - 32), 0
2596 
2597   SelectionDAG &DAG = DCI.DAG;
2598   SDLoc SL(N);
2599 
2600   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2601   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2602 
2603   SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, N->getOperand(0));
2604   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
2605                            VecOp, One);
2606 
2607   SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
2608   SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
2609 
2610   SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
2611 
2612   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
2613 }
2614 
2615 // We need to specifically handle i64 mul here to avoid unnecessary conversion
2616 // instructions. If we only match on the legalized i64 mul expansion,
2617 // SimplifyDemandedBits will be unable to remove them because there will be
2618 // multiple uses due to the separate mul + mulh[su].
2619 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
2620                         SDValue N0, SDValue N1, unsigned Size, bool Signed) {
2621   if (Size <= 32) {
2622     unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2623     return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
2624   }
2625 
2626   // Because we want to eliminate extension instructions before the
2627   // operation, we need to create a single user here (i.e. not the separate
2628   // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
2629 
2630   unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
2631 
2632   SDValue Mul = DAG.getNode(MulOpc, SL,
2633                             DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
2634 
2635   return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
2636                      Mul.getValue(0), Mul.getValue(1));
2637 }
2638 
2639 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
2640                                                 DAGCombinerInfo &DCI) const {
2641   EVT VT = N->getValueType(0);
2642 
2643   unsigned Size = VT.getSizeInBits();
2644   if (VT.isVector() || Size > 64)
2645     return SDValue();
2646 
2647   // There are i16 integer mul/mad.
2648   if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
2649     return SDValue();
2650 
2651   SelectionDAG &DAG = DCI.DAG;
2652   SDLoc DL(N);
2653 
2654   SDValue N0 = N->getOperand(0);
2655   SDValue N1 = N->getOperand(1);
2656   SDValue Mul;
2657 
2658   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
2659     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2660     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2661     Mul = getMul24(DAG, DL, N0, N1, Size, false);
2662   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
2663     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2664     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2665     Mul = getMul24(DAG, DL, N0, N1, Size, true);
2666   } else {
2667     return SDValue();
2668   }
2669 
2670   // We need to use sext even for MUL_U24, because MUL_U24 is used
2671   // for signed multiply of 8 and 16-bit types.
2672   return DAG.getSExtOrTrunc(Mul, DL, VT);
2673 }
2674 
2675 SDValue AMDGPUTargetLowering::performMulhsCombine(SDNode *N,
2676                                                   DAGCombinerInfo &DCI) const {
2677   EVT VT = N->getValueType(0);
2678 
2679   if (!Subtarget->hasMulI24() || VT.isVector())
2680     return SDValue();
2681 
2682   SelectionDAG &DAG = DCI.DAG;
2683   SDLoc DL(N);
2684 
2685   SDValue N0 = N->getOperand(0);
2686   SDValue N1 = N->getOperand(1);
2687 
2688   if (!isI24(N0, DAG) || !isI24(N1, DAG))
2689     return SDValue();
2690 
2691   N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2692   N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2693 
2694   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
2695   DCI.AddToWorklist(Mulhi.getNode());
2696   return DAG.getSExtOrTrunc(Mulhi, DL, VT);
2697 }
2698 
2699 SDValue AMDGPUTargetLowering::performMulhuCombine(SDNode *N,
2700                                                   DAGCombinerInfo &DCI) const {
2701   EVT VT = N->getValueType(0);
2702 
2703   if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
2704     return SDValue();
2705 
2706   SelectionDAG &DAG = DCI.DAG;
2707   SDLoc DL(N);
2708 
2709   SDValue N0 = N->getOperand(0);
2710   SDValue N1 = N->getOperand(1);
2711 
2712   if (!isU24(N0, DAG) || !isU24(N1, DAG))
2713     return SDValue();
2714 
2715   N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2716   N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2717 
2718   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
2719   DCI.AddToWorklist(Mulhi.getNode());
2720   return DAG.getZExtOrTrunc(Mulhi, DL, VT);
2721 }
2722 
2723 SDValue AMDGPUTargetLowering::performMulLoHi24Combine(
2724   SDNode *N, DAGCombinerInfo &DCI) const {
2725   SelectionDAG &DAG = DCI.DAG;
2726 
2727   // Simplify demanded bits before splitting into multiple users.
2728   if (simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI))
2729     return SDValue();
2730 
2731   SDValue N0 = N->getOperand(0);
2732   SDValue N1 = N->getOperand(1);
2733 
2734   bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
2735 
2736   unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2737   unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
2738 
2739   SDLoc SL(N);
2740 
2741   SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
2742   SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
2743   return DAG.getMergeValues({ MulLo, MulHi }, SL);
2744 }
2745 
2746 static bool isNegativeOne(SDValue Val) {
2747   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
2748     return C->isAllOnesValue();
2749   return false;
2750 }
2751 
2752 static bool isCtlzOpc(unsigned Opc) {
2753   return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2754 }
2755 
2756 SDValue AMDGPUTargetLowering::getFFBH_U32(SelectionDAG &DAG,
2757                                           SDValue Op,
2758                                           const SDLoc &DL) const {
2759   EVT VT = Op.getValueType();
2760   EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
2761   if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
2762                               LegalVT != MVT::i16))
2763     return SDValue();
2764 
2765   if (VT != MVT::i32)
2766     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
2767 
2768   SDValue FFBH = DAG.getNode(AMDGPUISD::FFBH_U32, DL, MVT::i32, Op);
2769   if (VT != MVT::i32)
2770     FFBH = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBH);
2771 
2772   return FFBH;
2773 }
2774 
2775 // The native instructions return -1 on 0 input. Optimize out a select that
2776 // produces -1 on 0.
2777 //
2778 // TODO: If zero is not undef, we could also do this if the output is compared
2779 // against the bitwidth.
2780 //
2781 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
2782 SDValue AMDGPUTargetLowering::performCtlzCombine(const SDLoc &SL, SDValue Cond,
2783                                                  SDValue LHS, SDValue RHS,
2784                                                  DAGCombinerInfo &DCI) const {
2785   ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2786   if (!CmpRhs || !CmpRhs->isNullValue())
2787     return SDValue();
2788 
2789   SelectionDAG &DAG = DCI.DAG;
2790   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
2791   SDValue CmpLHS = Cond.getOperand(0);
2792 
2793   // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
2794   if (CCOpcode == ISD::SETEQ &&
2795       isCtlzOpc(RHS.getOpcode()) &&
2796       RHS.getOperand(0) == CmpLHS &&
2797       isNegativeOne(LHS)) {
2798     return getFFBH_U32(DAG, CmpLHS, SL);
2799   }
2800 
2801   // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
2802   if (CCOpcode == ISD::SETNE &&
2803       isCtlzOpc(LHS.getOpcode()) &&
2804       LHS.getOperand(0) == CmpLHS &&
2805       isNegativeOne(RHS)) {
2806     return getFFBH_U32(DAG, CmpLHS, SL);
2807   }
2808 
2809   return SDValue();
2810 }
2811 
2812 static SDValue distributeOpThroughSelect(TargetLowering::DAGCombinerInfo &DCI,
2813                                          unsigned Op,
2814                                          const SDLoc &SL,
2815                                          SDValue Cond,
2816                                          SDValue N1,
2817                                          SDValue N2) {
2818   SelectionDAG &DAG = DCI.DAG;
2819   EVT VT = N1.getValueType();
2820 
2821   SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
2822                                   N1.getOperand(0), N2.getOperand(0));
2823   DCI.AddToWorklist(NewSelect.getNode());
2824   return DAG.getNode(Op, SL, VT, NewSelect);
2825 }
2826 
2827 // Pull a free FP operation out of a select so it may fold into uses.
2828 //
2829 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
2830 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
2831 //
2832 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
2833 // select c, (fabs x), +k -> fabs (select c, x, k)
2834 static SDValue foldFreeOpFromSelect(TargetLowering::DAGCombinerInfo &DCI,
2835                                     SDValue N) {
2836   SelectionDAG &DAG = DCI.DAG;
2837   SDValue Cond = N.getOperand(0);
2838   SDValue LHS = N.getOperand(1);
2839   SDValue RHS = N.getOperand(2);
2840 
2841   EVT VT = N.getValueType();
2842   if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
2843       (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
2844     return distributeOpThroughSelect(DCI, LHS.getOpcode(),
2845                                      SDLoc(N), Cond, LHS, RHS);
2846   }
2847 
2848   bool Inv = false;
2849   if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
2850     std::swap(LHS, RHS);
2851     Inv = true;
2852   }
2853 
2854   // TODO: Support vector constants.
2855   ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
2856   if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
2857     SDLoc SL(N);
2858     // If one side is an fneg/fabs and the other is a constant, we can push the
2859     // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
2860     SDValue NewLHS = LHS.getOperand(0);
2861     SDValue NewRHS = RHS;
2862 
2863     // Careful: if the neg can be folded up, don't try to pull it back down.
2864     bool ShouldFoldNeg = true;
2865 
2866     if (NewLHS.hasOneUse()) {
2867       unsigned Opc = NewLHS.getOpcode();
2868       if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
2869         ShouldFoldNeg = false;
2870       if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
2871         ShouldFoldNeg = false;
2872     }
2873 
2874     if (ShouldFoldNeg) {
2875       if (LHS.getOpcode() == ISD::FNEG)
2876         NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2877       else if (CRHS->isNegative())
2878         return SDValue();
2879 
2880       if (Inv)
2881         std::swap(NewLHS, NewRHS);
2882 
2883       SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
2884                                       Cond, NewLHS, NewRHS);
2885       DCI.AddToWorklist(NewSelect.getNode());
2886       return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
2887     }
2888   }
2889 
2890   return SDValue();
2891 }
2892 
2893 
2894 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
2895                                                    DAGCombinerInfo &DCI) const {
2896   if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
2897     return Folded;
2898 
2899   SDValue Cond = N->getOperand(0);
2900   if (Cond.getOpcode() != ISD::SETCC)
2901     return SDValue();
2902 
2903   EVT VT = N->getValueType(0);
2904   SDValue LHS = Cond.getOperand(0);
2905   SDValue RHS = Cond.getOperand(1);
2906   SDValue CC = Cond.getOperand(2);
2907 
2908   SDValue True = N->getOperand(1);
2909   SDValue False = N->getOperand(2);
2910 
2911   if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
2912     SelectionDAG &DAG = DCI.DAG;
2913     if ((DAG.isConstantValueOfAnyType(True) ||
2914          DAG.isConstantValueOfAnyType(True)) &&
2915         (!DAG.isConstantValueOfAnyType(False) &&
2916          !DAG.isConstantValueOfAnyType(False))) {
2917       // Swap cmp + select pair to move constant to false input.
2918       // This will allow using VOPC cndmasks more often.
2919       // select (setcc x, y), k, x -> select (setcc y, x) x, x
2920 
2921       SDLoc SL(N);
2922       ISD::CondCode NewCC = getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2923                                             LHS.getValueType().isInteger());
2924 
2925       SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
2926       return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
2927     }
2928 
2929     if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
2930       SDValue MinMax
2931         = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
2932       // Revisit this node so we can catch min3/max3/med3 patterns.
2933       //DCI.AddToWorklist(MinMax.getNode());
2934       return MinMax;
2935     }
2936   }
2937 
2938   // There's no reason to not do this if the condition has other uses.
2939   return performCtlzCombine(SDLoc(N), Cond, True, False, DCI);
2940 }
2941 
2942 static bool isConstantFPZero(SDValue N) {
2943   if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N))
2944     return C->isZero() && !C->isNegative();
2945   return false;
2946 }
2947 
2948 static unsigned inverseMinMax(unsigned Opc) {
2949   switch (Opc) {
2950   case ISD::FMAXNUM:
2951     return ISD::FMINNUM;
2952   case ISD::FMINNUM:
2953     return ISD::FMAXNUM;
2954   case AMDGPUISD::FMAX_LEGACY:
2955     return AMDGPUISD::FMIN_LEGACY;
2956   case AMDGPUISD::FMIN_LEGACY:
2957     return  AMDGPUISD::FMAX_LEGACY;
2958   default:
2959     llvm_unreachable("invalid min/max opcode");
2960   }
2961 }
2962 
2963 SDValue AMDGPUTargetLowering::performFNegCombine(SDNode *N,
2964                                                  DAGCombinerInfo &DCI) const {
2965   SelectionDAG &DAG = DCI.DAG;
2966   SDValue N0 = N->getOperand(0);
2967   EVT VT = N->getValueType(0);
2968 
2969   unsigned Opc = N0.getOpcode();
2970 
2971   // If the input has multiple uses and we can either fold the negate down, or
2972   // the other uses cannot, give up. This both prevents unprofitable
2973   // transformations and infinite loops: we won't repeatedly try to fold around
2974   // a negate that has no 'good' form.
2975   if (N0.hasOneUse()) {
2976     // This may be able to fold into the source, but at a code size cost. Don't
2977     // fold if the fold into the user is free.
2978     if (allUsesHaveSourceMods(N, 0))
2979       return SDValue();
2980   } else {
2981     if (fnegFoldsIntoOp(Opc) &&
2982         (allUsesHaveSourceMods(N) || !allUsesHaveSourceMods(N0.getNode())))
2983       return SDValue();
2984   }
2985 
2986   SDLoc SL(N);
2987   switch (Opc) {
2988   case ISD::FADD: {
2989     if (!mayIgnoreSignedZero(N0))
2990       return SDValue();
2991 
2992     // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
2993     SDValue LHS = N0.getOperand(0);
2994     SDValue RHS = N0.getOperand(1);
2995 
2996     if (LHS.getOpcode() != ISD::FNEG)
2997       LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
2998     else
2999       LHS = LHS.getOperand(0);
3000 
3001     if (RHS.getOpcode() != ISD::FNEG)
3002       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3003     else
3004       RHS = RHS.getOperand(0);
3005 
3006     SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3007     if (!N0.hasOneUse())
3008       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3009     return Res;
3010   }
3011   case ISD::FMUL:
3012   case AMDGPUISD::FMUL_LEGACY: {
3013     // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3014     // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3015     SDValue LHS = N0.getOperand(0);
3016     SDValue RHS = N0.getOperand(1);
3017 
3018     if (LHS.getOpcode() == ISD::FNEG)
3019       LHS = LHS.getOperand(0);
3020     else if (RHS.getOpcode() == ISD::FNEG)
3021       RHS = RHS.getOperand(0);
3022     else
3023       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3024 
3025     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3026     if (!N0.hasOneUse())
3027       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3028     return Res;
3029   }
3030   case ISD::FMA:
3031   case ISD::FMAD: {
3032     if (!mayIgnoreSignedZero(N0))
3033       return SDValue();
3034 
3035     // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3036     SDValue LHS = N0.getOperand(0);
3037     SDValue MHS = N0.getOperand(1);
3038     SDValue RHS = N0.getOperand(2);
3039 
3040     if (LHS.getOpcode() == ISD::FNEG)
3041       LHS = LHS.getOperand(0);
3042     else if (MHS.getOpcode() == ISD::FNEG)
3043       MHS = MHS.getOperand(0);
3044     else
3045       MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3046 
3047     if (RHS.getOpcode() != ISD::FNEG)
3048       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3049     else
3050       RHS = RHS.getOperand(0);
3051 
3052     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3053     if (!N0.hasOneUse())
3054       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3055     return Res;
3056   }
3057   case ISD::FMAXNUM:
3058   case ISD::FMINNUM:
3059   case AMDGPUISD::FMAX_LEGACY:
3060   case AMDGPUISD::FMIN_LEGACY: {
3061     // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3062     // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3063     // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3064     // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3065 
3066     SDValue LHS = N0.getOperand(0);
3067     SDValue RHS = N0.getOperand(1);
3068 
3069     // 0 doesn't have a negated inline immediate.
3070     // TODO: Shouldn't fold 1/2pi either, and should be generalized to other
3071     // operations.
3072     if (isConstantFPZero(RHS))
3073       return SDValue();
3074 
3075     SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3076     SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3077     unsigned Opposite = inverseMinMax(Opc);
3078 
3079     SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3080     if (!N0.hasOneUse())
3081       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3082     return Res;
3083   }
3084   case ISD::FP_EXTEND:
3085   case ISD::FTRUNC:
3086   case ISD::FRINT:
3087   case ISD::FNEARBYINT: // XXX - Should fround be handled?
3088   case ISD::FSIN:
3089   case AMDGPUISD::RCP:
3090   case AMDGPUISD::RCP_LEGACY:
3091   case AMDGPUISD::SIN_HW: {
3092     SDValue CvtSrc = N0.getOperand(0);
3093     if (CvtSrc.getOpcode() == ISD::FNEG) {
3094       // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3095       // (fneg (rcp (fneg x))) -> (rcp x)
3096       return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3097     }
3098 
3099     if (!N0.hasOneUse())
3100       return SDValue();
3101 
3102     // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3103     // (fneg (rcp x)) -> (rcp (fneg x))
3104     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3105     return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3106   }
3107   case ISD::FP_ROUND: {
3108     SDValue CvtSrc = N0.getOperand(0);
3109 
3110     if (CvtSrc.getOpcode() == ISD::FNEG) {
3111       // (fneg (fp_round (fneg x))) -> (fp_round x)
3112       return DAG.getNode(ISD::FP_ROUND, SL, VT,
3113                          CvtSrc.getOperand(0), N0.getOperand(1));
3114     }
3115 
3116     if (!N0.hasOneUse())
3117       return SDValue();
3118 
3119     // (fneg (fp_round x)) -> (fp_round (fneg x))
3120     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3121     return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3122   }
3123   case ISD::FP16_TO_FP: {
3124     // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3125     // f16, but legalization of f16 fneg ends up pulling it out of the source.
3126     // Put the fneg back as a legal source operation that can be matched later.
3127     SDLoc SL(N);
3128 
3129     SDValue Src = N0.getOperand(0);
3130     EVT SrcVT = Src.getValueType();
3131 
3132     // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3133     SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3134                                   DAG.getConstant(0x8000, SL, SrcVT));
3135     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3136   }
3137   default:
3138     return SDValue();
3139   }
3140 }
3141 
3142 SDValue AMDGPUTargetLowering::performFAbsCombine(SDNode *N,
3143                                                  DAGCombinerInfo &DCI) const {
3144   SelectionDAG &DAG = DCI.DAG;
3145   SDValue N0 = N->getOperand(0);
3146 
3147   if (!N0.hasOneUse())
3148     return SDValue();
3149 
3150   switch (N0.getOpcode()) {
3151   case ISD::FP16_TO_FP: {
3152     assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3153     SDLoc SL(N);
3154     SDValue Src = N0.getOperand(0);
3155     EVT SrcVT = Src.getValueType();
3156 
3157     // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3158     SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3159                                   DAG.getConstant(0x7fff, SL, SrcVT));
3160     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3161   }
3162   default:
3163     return SDValue();
3164   }
3165 }
3166 
3167 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
3168                                                 DAGCombinerInfo &DCI) const {
3169   SelectionDAG &DAG = DCI.DAG;
3170   SDLoc DL(N);
3171 
3172   switch(N->getOpcode()) {
3173   default:
3174     break;
3175   case ISD::BITCAST: {
3176     EVT DestVT = N->getValueType(0);
3177 
3178     // Push casts through vector builds. This helps avoid emitting a large
3179     // number of copies when materializing floating point vector constants.
3180     //
3181     // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3182     //   vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3183     if (DestVT.isVector()) {
3184       SDValue Src = N->getOperand(0);
3185       if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3186         EVT SrcVT = Src.getValueType();
3187         unsigned NElts = DestVT.getVectorNumElements();
3188 
3189         if (SrcVT.getVectorNumElements() == NElts) {
3190           EVT DestEltVT = DestVT.getVectorElementType();
3191 
3192           SmallVector<SDValue, 8> CastedElts;
3193           SDLoc SL(N);
3194           for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3195             SDValue Elt = Src.getOperand(I);
3196             CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3197           }
3198 
3199           return DAG.getBuildVector(DestVT, SL, CastedElts);
3200         }
3201       }
3202     }
3203 
3204     if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3205       break;
3206 
3207     // Fold bitcasts of constants.
3208     //
3209     // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3210     // TODO: Generalize and move to DAGCombiner
3211     SDValue Src = N->getOperand(0);
3212     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3213       assert(Src.getValueType() == MVT::i64);
3214       SDLoc SL(N);
3215       uint64_t CVal = C->getZExtValue();
3216       return DAG.getNode(ISD::BUILD_VECTOR, SL, DestVT,
3217                          DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3218                          DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3219     }
3220 
3221     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3222       const APInt &Val = C->getValueAPF().bitcastToAPInt();
3223       SDLoc SL(N);
3224       uint64_t CVal = Val.getZExtValue();
3225       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3226                                 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3227                                 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3228 
3229       return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3230     }
3231 
3232     break;
3233   }
3234   case ISD::SHL: {
3235     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3236       break;
3237 
3238     return performShlCombine(N, DCI);
3239   }
3240   case ISD::SRL: {
3241     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3242       break;
3243 
3244     return performSrlCombine(N, DCI);
3245   }
3246   case ISD::SRA: {
3247     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3248       break;
3249 
3250     return performSraCombine(N, DCI);
3251   }
3252   case ISD::MUL:
3253     return performMulCombine(N, DCI);
3254   case ISD::MULHS:
3255     return performMulhsCombine(N, DCI);
3256   case ISD::MULHU:
3257     return performMulhuCombine(N, DCI);
3258   case AMDGPUISD::MUL_I24:
3259   case AMDGPUISD::MUL_U24:
3260   case AMDGPUISD::MULHI_I24:
3261   case AMDGPUISD::MULHI_U24: {
3262     // If the first call to simplify is successfull, then N may end up being
3263     // deleted, so we shouldn't call simplifyI24 again.
3264     simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI);
3265     return SDValue();
3266   }
3267   case AMDGPUISD::MUL_LOHI_I24:
3268   case AMDGPUISD::MUL_LOHI_U24:
3269     return performMulLoHi24Combine(N, DCI);
3270   case ISD::SELECT:
3271     return performSelectCombine(N, DCI);
3272   case ISD::FNEG:
3273     return performFNegCombine(N, DCI);
3274   case ISD::FABS:
3275     return performFAbsCombine(N, DCI);
3276   case AMDGPUISD::BFE_I32:
3277   case AMDGPUISD::BFE_U32: {
3278     assert(!N->getValueType(0).isVector() &&
3279            "Vector handling of BFE not implemented");
3280     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
3281     if (!Width)
3282       break;
3283 
3284     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
3285     if (WidthVal == 0)
3286       return DAG.getConstant(0, DL, MVT::i32);
3287 
3288     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
3289     if (!Offset)
3290       break;
3291 
3292     SDValue BitsFrom = N->getOperand(0);
3293     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
3294 
3295     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
3296 
3297     if (OffsetVal == 0) {
3298       // This is already sign / zero extended, so try to fold away extra BFEs.
3299       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
3300 
3301       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
3302       if (OpSignBits >= SignBits)
3303         return BitsFrom;
3304 
3305       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
3306       if (Signed) {
3307         // This is a sign_extend_inreg. Replace it to take advantage of existing
3308         // DAG Combines. If not eliminated, we will match back to BFE during
3309         // selection.
3310 
3311         // TODO: The sext_inreg of extended types ends, although we can could
3312         // handle them in a single BFE.
3313         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
3314                            DAG.getValueType(SmallVT));
3315       }
3316 
3317       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
3318     }
3319 
3320     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
3321       if (Signed) {
3322         return constantFoldBFE<int32_t>(DAG,
3323                                         CVal->getSExtValue(),
3324                                         OffsetVal,
3325                                         WidthVal,
3326                                         DL);
3327       }
3328 
3329       return constantFoldBFE<uint32_t>(DAG,
3330                                        CVal->getZExtValue(),
3331                                        OffsetVal,
3332                                        WidthVal,
3333                                        DL);
3334     }
3335 
3336     if ((OffsetVal + WidthVal) >= 32) {
3337       SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
3338       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
3339                          BitsFrom, ShiftVal);
3340     }
3341 
3342     if (BitsFrom.hasOneUse()) {
3343       APInt Demanded = APInt::getBitsSet(32,
3344                                          OffsetVal,
3345                                          OffsetVal + WidthVal);
3346 
3347       APInt KnownZero, KnownOne;
3348       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3349                                             !DCI.isBeforeLegalizeOps());
3350       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3351       if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
3352           TLI.SimplifyDemandedBits(BitsFrom, Demanded,
3353                                    KnownZero, KnownOne, TLO)) {
3354         DCI.CommitTargetLoweringOpt(TLO);
3355       }
3356     }
3357 
3358     break;
3359   }
3360   case ISD::LOAD:
3361     return performLoadCombine(N, DCI);
3362   case ISD::STORE:
3363     return performStoreCombine(N, DCI);
3364   case AMDGPUISD::CLAMP:
3365     return performClampCombine(N, DCI);
3366   case AMDGPUISD::RCP: {
3367     if (const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
3368       // XXX - Should this flush denormals?
3369       const APFloat &Val = CFP->getValueAPF();
3370       APFloat One(Val.getSemantics(), "1.0");
3371       return DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3372     }
3373 
3374     break;
3375   }
3376   }
3377   return SDValue();
3378 }
3379 
3380 //===----------------------------------------------------------------------===//
3381 // Helper functions
3382 //===----------------------------------------------------------------------===//
3383 
3384 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
3385                                                   const TargetRegisterClass *RC,
3386                                                    unsigned Reg, EVT VT) const {
3387   MachineFunction &MF = DAG.getMachineFunction();
3388   MachineRegisterInfo &MRI = MF.getRegInfo();
3389   unsigned VirtualRegister;
3390   if (!MRI.isLiveIn(Reg)) {
3391     VirtualRegister = MRI.createVirtualRegister(RC);
3392     MRI.addLiveIn(Reg, VirtualRegister);
3393   } else {
3394     VirtualRegister = MRI.getLiveInVirtReg(Reg);
3395   }
3396   return DAG.getRegister(VirtualRegister, VT);
3397 }
3398 
3399 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
3400     const AMDGPUMachineFunction *MFI, const ImplicitParameter Param) const {
3401   unsigned Alignment = Subtarget->getAlignmentForImplicitArgPtr();
3402   uint64_t ArgOffset = alignTo(MFI->getABIArgOffset(), Alignment);
3403   switch (Param) {
3404   case GRID_DIM:
3405     return ArgOffset;
3406   case GRID_OFFSET:
3407     return ArgOffset + 4;
3408   }
3409   llvm_unreachable("unexpected implicit parameter type");
3410 }
3411 
3412 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
3413 
3414 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
3415   switch ((AMDGPUISD::NodeType)Opcode) {
3416   case AMDGPUISD::FIRST_NUMBER: break;
3417   // AMDIL DAG nodes
3418   NODE_NAME_CASE(UMUL);
3419   NODE_NAME_CASE(BRANCH_COND);
3420 
3421   // AMDGPU DAG nodes
3422   NODE_NAME_CASE(IF)
3423   NODE_NAME_CASE(ELSE)
3424   NODE_NAME_CASE(LOOP)
3425   NODE_NAME_CASE(CALL)
3426   NODE_NAME_CASE(RET_FLAG)
3427   NODE_NAME_CASE(RETURN_TO_EPILOG)
3428   NODE_NAME_CASE(ENDPGM)
3429   NODE_NAME_CASE(DWORDADDR)
3430   NODE_NAME_CASE(FRACT)
3431   NODE_NAME_CASE(SETCC)
3432   NODE_NAME_CASE(SETREG)
3433   NODE_NAME_CASE(FMA_W_CHAIN)
3434   NODE_NAME_CASE(FMUL_W_CHAIN)
3435   NODE_NAME_CASE(CLAMP)
3436   NODE_NAME_CASE(COS_HW)
3437   NODE_NAME_CASE(SIN_HW)
3438   NODE_NAME_CASE(FMAX_LEGACY)
3439   NODE_NAME_CASE(FMIN_LEGACY)
3440   NODE_NAME_CASE(FMAX3)
3441   NODE_NAME_CASE(SMAX3)
3442   NODE_NAME_CASE(UMAX3)
3443   NODE_NAME_CASE(FMIN3)
3444   NODE_NAME_CASE(SMIN3)
3445   NODE_NAME_CASE(UMIN3)
3446   NODE_NAME_CASE(FMED3)
3447   NODE_NAME_CASE(SMED3)
3448   NODE_NAME_CASE(UMED3)
3449   NODE_NAME_CASE(URECIP)
3450   NODE_NAME_CASE(DIV_SCALE)
3451   NODE_NAME_CASE(DIV_FMAS)
3452   NODE_NAME_CASE(DIV_FIXUP)
3453   NODE_NAME_CASE(FMAD_FTZ)
3454   NODE_NAME_CASE(TRIG_PREOP)
3455   NODE_NAME_CASE(RCP)
3456   NODE_NAME_CASE(RSQ)
3457   NODE_NAME_CASE(RCP_LEGACY)
3458   NODE_NAME_CASE(RSQ_LEGACY)
3459   NODE_NAME_CASE(FMUL_LEGACY)
3460   NODE_NAME_CASE(RSQ_CLAMP)
3461   NODE_NAME_CASE(LDEXP)
3462   NODE_NAME_CASE(FP_CLASS)
3463   NODE_NAME_CASE(DOT4)
3464   NODE_NAME_CASE(CARRY)
3465   NODE_NAME_CASE(BORROW)
3466   NODE_NAME_CASE(BFE_U32)
3467   NODE_NAME_CASE(BFE_I32)
3468   NODE_NAME_CASE(BFI)
3469   NODE_NAME_CASE(BFM)
3470   NODE_NAME_CASE(FFBH_U32)
3471   NODE_NAME_CASE(FFBH_I32)
3472   NODE_NAME_CASE(MUL_U24)
3473   NODE_NAME_CASE(MUL_I24)
3474   NODE_NAME_CASE(MULHI_U24)
3475   NODE_NAME_CASE(MULHI_I24)
3476   NODE_NAME_CASE(MUL_LOHI_U24)
3477   NODE_NAME_CASE(MUL_LOHI_I24)
3478   NODE_NAME_CASE(MAD_U24)
3479   NODE_NAME_CASE(MAD_I24)
3480   NODE_NAME_CASE(TEXTURE_FETCH)
3481   NODE_NAME_CASE(EXPORT)
3482   NODE_NAME_CASE(EXPORT_DONE)
3483   NODE_NAME_CASE(R600_EXPORT)
3484   NODE_NAME_CASE(CONST_ADDRESS)
3485   NODE_NAME_CASE(REGISTER_LOAD)
3486   NODE_NAME_CASE(REGISTER_STORE)
3487   NODE_NAME_CASE(SAMPLE)
3488   NODE_NAME_CASE(SAMPLEB)
3489   NODE_NAME_CASE(SAMPLED)
3490   NODE_NAME_CASE(SAMPLEL)
3491   NODE_NAME_CASE(CVT_F32_UBYTE0)
3492   NODE_NAME_CASE(CVT_F32_UBYTE1)
3493   NODE_NAME_CASE(CVT_F32_UBYTE2)
3494   NODE_NAME_CASE(CVT_F32_UBYTE3)
3495   NODE_NAME_CASE(CVT_PKRTZ_F16_F32)
3496   NODE_NAME_CASE(FP_TO_FP16)
3497   NODE_NAME_CASE(FP16_ZEXT)
3498   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
3499   NODE_NAME_CASE(CONST_DATA_PTR)
3500   NODE_NAME_CASE(PC_ADD_REL_OFFSET)
3501   NODE_NAME_CASE(KILL)
3502   NODE_NAME_CASE(DUMMY_CHAIN)
3503   case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
3504   NODE_NAME_CASE(SENDMSG)
3505   NODE_NAME_CASE(SENDMSGHALT)
3506   NODE_NAME_CASE(INTERP_MOV)
3507   NODE_NAME_CASE(INTERP_P1)
3508   NODE_NAME_CASE(INTERP_P2)
3509   NODE_NAME_CASE(STORE_MSKOR)
3510   NODE_NAME_CASE(LOAD_CONSTANT)
3511   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
3512   NODE_NAME_CASE(ATOMIC_CMP_SWAP)
3513   NODE_NAME_CASE(ATOMIC_INC)
3514   NODE_NAME_CASE(ATOMIC_DEC)
3515   NODE_NAME_CASE(BUFFER_LOAD)
3516   NODE_NAME_CASE(BUFFER_LOAD_FORMAT)
3517   case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
3518   }
3519   return nullptr;
3520 }
3521 
3522 SDValue AMDGPUTargetLowering::getSqrtEstimate(SDValue Operand,
3523                                               SelectionDAG &DAG, int Enabled,
3524                                               int &RefinementSteps,
3525                                               bool &UseOneConstNR,
3526                                               bool Reciprocal) const {
3527   EVT VT = Operand.getValueType();
3528 
3529   if (VT == MVT::f32) {
3530     RefinementSteps = 0;
3531     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
3532   }
3533 
3534   // TODO: There is also f64 rsq instruction, but the documentation is less
3535   // clear on its precision.
3536 
3537   return SDValue();
3538 }
3539 
3540 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
3541                                                SelectionDAG &DAG, int Enabled,
3542                                                int &RefinementSteps) const {
3543   EVT VT = Operand.getValueType();
3544 
3545   if (VT == MVT::f32) {
3546     // Reciprocal, < 1 ulp error.
3547     //
3548     // This reciprocal approximation converges to < 0.5 ulp error with one
3549     // newton rhapson performed with two fused multiple adds (FMAs).
3550 
3551     RefinementSteps = 0;
3552     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
3553   }
3554 
3555   // TODO: There is also f64 rcp instruction, but the documentation is less
3556   // clear on its precision.
3557 
3558   return SDValue();
3559 }
3560 
3561 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
3562     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
3563     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
3564 
3565   unsigned BitWidth = KnownZero.getBitWidth();
3566   KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
3567 
3568   APInt KnownZero2;
3569   APInt KnownOne2;
3570   unsigned Opc = Op.getOpcode();
3571 
3572   switch (Opc) {
3573   default:
3574     break;
3575   case AMDGPUISD::CARRY:
3576   case AMDGPUISD::BORROW: {
3577     KnownZero = APInt::getHighBitsSet(32, 31);
3578     break;
3579   }
3580 
3581   case AMDGPUISD::BFE_I32:
3582   case AMDGPUISD::BFE_U32: {
3583     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3584     if (!CWidth)
3585       return;
3586 
3587     uint32_t Width = CWidth->getZExtValue() & 0x1f;
3588 
3589     if (Opc == AMDGPUISD::BFE_U32)
3590       KnownZero = APInt::getHighBitsSet(32, 32 - Width);
3591 
3592     break;
3593   }
3594   case AMDGPUISD::FP_TO_FP16:
3595   case AMDGPUISD::FP16_ZEXT: {
3596     unsigned BitWidth = KnownZero.getBitWidth();
3597 
3598     // High bits are zero.
3599     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
3600     break;
3601   }
3602   }
3603 }
3604 
3605 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
3606     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3607     unsigned Depth) const {
3608   switch (Op.getOpcode()) {
3609   case AMDGPUISD::BFE_I32: {
3610     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3611     if (!Width)
3612       return 1;
3613 
3614     unsigned SignBits = 32 - Width->getZExtValue() + 1;
3615     if (!isNullConstant(Op.getOperand(1)))
3616       return SignBits;
3617 
3618     // TODO: Could probably figure something out with non-0 offsets.
3619     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3620     return std::max(SignBits, Op0SignBits);
3621   }
3622 
3623   case AMDGPUISD::BFE_U32: {
3624     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3625     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
3626   }
3627 
3628   case AMDGPUISD::CARRY:
3629   case AMDGPUISD::BORROW:
3630     return 31;
3631   case AMDGPUISD::FP_TO_FP16:
3632   case AMDGPUISD::FP16_ZEXT:
3633     return 16;
3634   default:
3635     return 1;
3636   }
3637 }
3638