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