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