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