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