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