]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Update clang to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
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 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 #define DEBUG_TYPE "aarch64-lower"
39
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
43 static cl::opt<bool>
44 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
45                            cl::desc("Allow AArch64 SLI/SRI formation"),
46                            cl::init(false));
47
48 // FIXME: The necessary dtprel relocations don't seem to be supported
49 // well in the GNU bfd and gold linkers at the moment. Therefore, by
50 // default, for now, fall back to GeneralDynamic code generation.
51 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52     "aarch64-elf-ldtls-generation", cl::Hidden,
53     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
54     cl::init(false));
55
56 /// Value type used for condition codes.
57 static const MVT MVT_CC = MVT::i32;
58
59 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60                                              const AArch64Subtarget &STI)
61     : TargetLowering(TM), Subtarget(&STI) {
62
63   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64   // we have to make something up. Arbitrarily, choose ZeroOrOne.
65   setBooleanContents(ZeroOrOneBooleanContent);
66   // When comparing vectors the result sets the different elements in the
67   // vector to all-one or all-zero.
68   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
69
70   // Set up the register classes.
71   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
73
74   if (Subtarget->hasFPARMv8()) {
75     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
79   }
80
81   if (Subtarget->hasNEON()) {
82     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84     // Someone set us up the NEON.
85     addDRTypeForNEON(MVT::v2f32);
86     addDRTypeForNEON(MVT::v8i8);
87     addDRTypeForNEON(MVT::v4i16);
88     addDRTypeForNEON(MVT::v2i32);
89     addDRTypeForNEON(MVT::v1i64);
90     addDRTypeForNEON(MVT::v1f64);
91     addDRTypeForNEON(MVT::v4f16);
92
93     addQRTypeForNEON(MVT::v4f32);
94     addQRTypeForNEON(MVT::v2f64);
95     addQRTypeForNEON(MVT::v16i8);
96     addQRTypeForNEON(MVT::v8i16);
97     addQRTypeForNEON(MVT::v4i32);
98     addQRTypeForNEON(MVT::v2i64);
99     addQRTypeForNEON(MVT::v8f16);
100   }
101
102   // Compute derived properties from the register classes
103   computeRegisterProperties(Subtarget->getRegisterInfo());
104
105   // Provide all sorts of operation actions
106   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108   setOperationAction(ISD::SETCC, MVT::i32, Custom);
109   setOperationAction(ISD::SETCC, MVT::i64, Custom);
110   setOperationAction(ISD::SETCC, MVT::f32, Custom);
111   setOperationAction(ISD::SETCC, MVT::f64, Custom);
112   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117   setOperationAction(ISD::SELECT, MVT::i32, Custom);
118   setOperationAction(ISD::SELECT, MVT::i64, Custom);
119   setOperationAction(ISD::SELECT, MVT::f32, Custom);
120   setOperationAction(ISD::SELECT, MVT::f64, Custom);
121   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
127
128   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
131
132   setOperationAction(ISD::FREM, MVT::f32, Expand);
133   setOperationAction(ISD::FREM, MVT::f64, Expand);
134   setOperationAction(ISD::FREM, MVT::f80, Expand);
135
136   // Custom lowering hooks are needed for XOR
137   // to fold it into CSINC/CSINV.
138   setOperationAction(ISD::XOR, MVT::i32, Custom);
139   setOperationAction(ISD::XOR, MVT::i64, Custom);
140
141   // Virtually no operation on f128 is legal, but LLVM can't expand them when
142   // there's a valid register class, so we need custom operations in most cases.
143   setOperationAction(ISD::FABS, MVT::f128, Expand);
144   setOperationAction(ISD::FADD, MVT::f128, Custom);
145   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146   setOperationAction(ISD::FCOS, MVT::f128, Expand);
147   setOperationAction(ISD::FDIV, MVT::f128, Custom);
148   setOperationAction(ISD::FMA, MVT::f128, Expand);
149   setOperationAction(ISD::FMUL, MVT::f128, Custom);
150   setOperationAction(ISD::FNEG, MVT::f128, Expand);
151   setOperationAction(ISD::FPOW, MVT::f128, Expand);
152   setOperationAction(ISD::FREM, MVT::f128, Expand);
153   setOperationAction(ISD::FRINT, MVT::f128, Expand);
154   setOperationAction(ISD::FSIN, MVT::f128, Expand);
155   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157   setOperationAction(ISD::FSUB, MVT::f128, Custom);
158   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159   setOperationAction(ISD::SETCC, MVT::f128, Custom);
160   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161   setOperationAction(ISD::SELECT, MVT::f128, Custom);
162   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
164
165   // Lowering for many of the conversions is actually specified by the non-f128
166   // type. The LowerXXX function will be trivial when f128 isn't involved.
167   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
181
182   // Variable arguments.
183   setOperationAction(ISD::VASTART, MVT::Other, Custom);
184   setOperationAction(ISD::VAARG, MVT::Other, Custom);
185   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186   setOperationAction(ISD::VAEND, MVT::Other, Expand);
187
188   // Variable-sized objects.
189   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
192
193   // Constant pool entries
194   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
195
196   // BlockAddress
197   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
198
199   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200   setOperationAction(ISD::ADDC, MVT::i32, Custom);
201   setOperationAction(ISD::ADDE, MVT::i32, Custom);
202   setOperationAction(ISD::SUBC, MVT::i32, Custom);
203   setOperationAction(ISD::SUBE, MVT::i32, Custom);
204   setOperationAction(ISD::ADDC, MVT::i64, Custom);
205   setOperationAction(ISD::ADDE, MVT::i64, Custom);
206   setOperationAction(ISD::SUBC, MVT::i64, Custom);
207   setOperationAction(ISD::SUBE, MVT::i64, Custom);
208
209   // AArch64 lacks both left-rotate and popcount instructions.
210   setOperationAction(ISD::ROTL, MVT::i32, Expand);
211   setOperationAction(ISD::ROTL, MVT::i64, Expand);
212   for (MVT VT : MVT::vector_valuetypes()) {
213     setOperationAction(ISD::ROTL, VT, Expand);
214     setOperationAction(ISD::ROTR, VT, Expand);
215   }
216
217   // AArch64 doesn't have {U|S}MUL_LOHI.
218   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
220
221
222   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
224
225   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
227   for (MVT VT : MVT::vector_valuetypes()) {
228     setOperationAction(ISD::SDIVREM, VT, Expand);
229     setOperationAction(ISD::UDIVREM, VT, Expand);
230   }
231   setOperationAction(ISD::SREM, MVT::i32, Expand);
232   setOperationAction(ISD::SREM, MVT::i64, Expand);
233   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235   setOperationAction(ISD::UREM, MVT::i32, Expand);
236   setOperationAction(ISD::UREM, MVT::i64, Expand);
237
238   // Custom lower Add/Sub/Mul with overflow.
239   setOperationAction(ISD::SADDO, MVT::i32, Custom);
240   setOperationAction(ISD::SADDO, MVT::i64, Custom);
241   setOperationAction(ISD::UADDO, MVT::i32, Custom);
242   setOperationAction(ISD::UADDO, MVT::i64, Custom);
243   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245   setOperationAction(ISD::USUBO, MVT::i32, Custom);
246   setOperationAction(ISD::USUBO, MVT::i64, Custom);
247   setOperationAction(ISD::SMULO, MVT::i32, Custom);
248   setOperationAction(ISD::SMULO, MVT::i64, Custom);
249   setOperationAction(ISD::UMULO, MVT::i32, Custom);
250   setOperationAction(ISD::UMULO, MVT::i64, Custom);
251
252   setOperationAction(ISD::FSIN, MVT::f32, Expand);
253   setOperationAction(ISD::FSIN, MVT::f64, Expand);
254   setOperationAction(ISD::FCOS, MVT::f32, Expand);
255   setOperationAction(ISD::FCOS, MVT::f64, Expand);
256   setOperationAction(ISD::FPOW, MVT::f32, Expand);
257   setOperationAction(ISD::FPOW, MVT::f64, Expand);
258   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
260
261   // f16 is a storage-only type, always promote it to f32.
262   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
263   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
264   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
265   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
266   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
267   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
268   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
269   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
270   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
271   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
272   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
273   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
274   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
275   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
276   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
277   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
278   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
279   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
280   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
281   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
282   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
283   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
284   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
285   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
286   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
287   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
288   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
289   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
290   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
291   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
292   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
293   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
294   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
295   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
296
297   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
298   // known to be safe.
299   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
311
312   // Expand all other v4f16 operations.
313   // FIXME: We could generate better code by promoting some operations to
314   // a pair of v4f32s
315   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
341
342
343   // v8f16 is also a storage-only type, so expand it.
344   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
375
376   // AArch64 has implementations of a lot of rounding-like FP operations.
377   for (MVT Ty : {MVT::f32, MVT::f64}) {
378     setOperationAction(ISD::FFLOOR, Ty, Legal);
379     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380     setOperationAction(ISD::FCEIL, Ty, Legal);
381     setOperationAction(ISD::FRINT, Ty, Legal);
382     setOperationAction(ISD::FTRUNC, Ty, Legal);
383     setOperationAction(ISD::FROUND, Ty, Legal);
384     setOperationAction(ISD::FMINNUM, Ty, Legal);
385     setOperationAction(ISD::FMAXNUM, Ty, Legal);
386     setOperationAction(ISD::FMINNAN, Ty, Legal);
387     setOperationAction(ISD::FMAXNAN, Ty, Legal);
388   }
389
390   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
391
392   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
393
394   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395   // This requires the Performance Monitors extension.
396   if (Subtarget->hasPerfMon())
397     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
398
399   if (Subtarget->isTargetMachO()) {
400     // For iOS, we don't want to the normal expansion of a libcall to
401     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
402     // traffic.
403     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
405   } else {
406     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
408   }
409
410   // Make floating-point constants legal for the large code model, so they don't
411   // become loads from the constant pool.
412   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
415   }
416
417   // AArch64 does not have floating-point extending loads, i1 sign-extending
418   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
419   for (MVT VT : MVT::fp_valuetypes()) {
420     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
424   }
425   for (MVT VT : MVT::integer_valuetypes())
426     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
427
428   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
435
436   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
438
439   // Indexed loads and stores are supported.
440   for (unsigned im = (unsigned)ISD::PRE_INC;
441        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442     setIndexedLoadAction(im, MVT::i8, Legal);
443     setIndexedLoadAction(im, MVT::i16, Legal);
444     setIndexedLoadAction(im, MVT::i32, Legal);
445     setIndexedLoadAction(im, MVT::i64, Legal);
446     setIndexedLoadAction(im, MVT::f64, Legal);
447     setIndexedLoadAction(im, MVT::f32, Legal);
448     setIndexedLoadAction(im, MVT::f16, Legal);
449     setIndexedStoreAction(im, MVT::i8, Legal);
450     setIndexedStoreAction(im, MVT::i16, Legal);
451     setIndexedStoreAction(im, MVT::i32, Legal);
452     setIndexedStoreAction(im, MVT::i64, Legal);
453     setIndexedStoreAction(im, MVT::f64, Legal);
454     setIndexedStoreAction(im, MVT::f32, Legal);
455     setIndexedStoreAction(im, MVT::f16, Legal);
456   }
457
458   // Trap.
459   setOperationAction(ISD::TRAP, MVT::Other, Legal);
460
461   // We combine OR nodes for bitfield operations.
462   setTargetDAGCombine(ISD::OR);
463
464   // Vector add and sub nodes may conceal a high-half opportunity.
465   // Also, try to fold ADD into CSINC/CSINV..
466   setTargetDAGCombine(ISD::ADD);
467   setTargetDAGCombine(ISD::SUB);
468   setTargetDAGCombine(ISD::SRL);
469   setTargetDAGCombine(ISD::XOR);
470   setTargetDAGCombine(ISD::SINT_TO_FP);
471   setTargetDAGCombine(ISD::UINT_TO_FP);
472
473   setTargetDAGCombine(ISD::FP_TO_SINT);
474   setTargetDAGCombine(ISD::FP_TO_UINT);
475   setTargetDAGCombine(ISD::FDIV);
476
477   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478
479   setTargetDAGCombine(ISD::ANY_EXTEND);
480   setTargetDAGCombine(ISD::ZERO_EXTEND);
481   setTargetDAGCombine(ISD::SIGN_EXTEND);
482   setTargetDAGCombine(ISD::BITCAST);
483   setTargetDAGCombine(ISD::CONCAT_VECTORS);
484   setTargetDAGCombine(ISD::STORE);
485   if (Subtarget->supportsAddressTopByteIgnored())
486     setTargetDAGCombine(ISD::LOAD);
487
488   setTargetDAGCombine(ISD::MUL);
489
490   setTargetDAGCombine(ISD::SELECT);
491   setTargetDAGCombine(ISD::VSELECT);
492
493   setTargetDAGCombine(ISD::INTRINSIC_VOID);
494   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
496   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
497
498   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
501
502   setStackPointerRegisterToSaveRestore(AArch64::SP);
503
504   setSchedulingPreference(Sched::Hybrid);
505
506   // Enable TBZ/TBNZ
507   MaskAndBranchFoldingIsLegal = true;
508   EnableExtLdPromotion = true;
509
510   // Set required alignment.
511   setMinFunctionAlignment(2);
512   // Set preferred alignments.
513   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514   setPrefLoopAlignment(STI.getPrefLoopAlignment());
515
516   // Only change the limit for entries in a jump table if specified by
517   // the subtarget, but not at the command line.
518   unsigned MaxJT = STI.getMaximumJumpTableSize();
519   if (MaxJT && getMaximumJumpTableSize() == 0)
520     setMaximumJumpTableSize(MaxJT);
521
522   setHasExtractBitsInsn(true);
523
524   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
525
526   if (Subtarget->hasNEON()) {
527     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528     // silliness like this:
529     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
554
555     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
560
561     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
562
563     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564     // elements smaller than i32, so promote the input to i32 first.
565     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
569     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570     // -> v8f16 conversions.
571     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
575     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
580     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
581     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
584
585     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
586     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
587
588     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
589     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
590     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
591     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
592     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
593     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
594     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
595     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
596
597     // AArch64 doesn't have MUL.2d:
598     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
599     // Custom handling for some quad-vector types to detect MULL.
600     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
601     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
602     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
603
604     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
605     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
606     // Likewise, narrowing and extending vector loads/stores aren't handled
607     // directly.
608     for (MVT VT : MVT::vector_valuetypes()) {
609       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
610
611       setOperationAction(ISD::MULHS, VT, Expand);
612       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
613       setOperationAction(ISD::MULHU, VT, Expand);
614       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
615
616       setOperationAction(ISD::BSWAP, VT, Expand);
617
618       for (MVT InnerVT : MVT::vector_valuetypes()) {
619         setTruncStoreAction(VT, InnerVT, Expand);
620         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
621         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
622         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
623       }
624     }
625
626     // AArch64 has implementations of a lot of rounding-like FP operations.
627     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
628       setOperationAction(ISD::FFLOOR, Ty, Legal);
629       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
630       setOperationAction(ISD::FCEIL, Ty, Legal);
631       setOperationAction(ISD::FRINT, Ty, Legal);
632       setOperationAction(ISD::FTRUNC, Ty, Legal);
633       setOperationAction(ISD::FROUND, Ty, Legal);
634     }
635   }
636
637   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
638 }
639
640 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
641   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
642     setOperationAction(ISD::LOAD, VT, Promote);
643     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
644
645     setOperationAction(ISD::STORE, VT, Promote);
646     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
647   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
648     setOperationAction(ISD::LOAD, VT, Promote);
649     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
650
651     setOperationAction(ISD::STORE, VT, Promote);
652     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
653   }
654
655   // Mark vector float intrinsics as expand.
656   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
657     setOperationAction(ISD::FSIN, VT, Expand);
658     setOperationAction(ISD::FCOS, VT, Expand);
659     setOperationAction(ISD::FPOWI, VT, Expand);
660     setOperationAction(ISD::FPOW, VT, Expand);
661     setOperationAction(ISD::FLOG, VT, Expand);
662     setOperationAction(ISD::FLOG2, VT, Expand);
663     setOperationAction(ISD::FLOG10, VT, Expand);
664     setOperationAction(ISD::FEXP, VT, Expand);
665     setOperationAction(ISD::FEXP2, VT, Expand);
666
667     // But we do support custom-lowering for FCOPYSIGN.
668     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
669   }
670
671   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
672   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
673   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
674   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
675   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
676   setOperationAction(ISD::SRA, VT, Custom);
677   setOperationAction(ISD::SRL, VT, Custom);
678   setOperationAction(ISD::SHL, VT, Custom);
679   setOperationAction(ISD::AND, VT, Custom);
680   setOperationAction(ISD::OR, VT, Custom);
681   setOperationAction(ISD::SETCC, VT, Custom);
682   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
683
684   setOperationAction(ISD::SELECT, VT, Expand);
685   setOperationAction(ISD::SELECT_CC, VT, Expand);
686   setOperationAction(ISD::VSELECT, VT, Expand);
687   for (MVT InnerVT : MVT::all_valuetypes())
688     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
689
690   // CNT supports only B element sizes.
691   if (VT != MVT::v8i8 && VT != MVT::v16i8)
692     setOperationAction(ISD::CTPOP, VT, Expand);
693
694   setOperationAction(ISD::UDIV, VT, Expand);
695   setOperationAction(ISD::SDIV, VT, Expand);
696   setOperationAction(ISD::UREM, VT, Expand);
697   setOperationAction(ISD::SREM, VT, Expand);
698   setOperationAction(ISD::FREM, VT, Expand);
699
700   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
701   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
702
703   // [SU][MIN|MAX] are available for all NEON types apart from i64.
704   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
705     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
706       setOperationAction(Opcode, VT, Legal);
707
708   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
709   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
710     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
711                             ISD::FMINNUM, ISD::FMAXNUM})
712       setOperationAction(Opcode, VT, Legal);
713
714   if (Subtarget->isLittleEndian()) {
715     for (unsigned im = (unsigned)ISD::PRE_INC;
716          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
717       setIndexedLoadAction(im, VT, Legal);
718       setIndexedStoreAction(im, VT, Legal);
719     }
720   }
721 }
722
723 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
724   addRegisterClass(VT, &AArch64::FPR64RegClass);
725   addTypeForNEON(VT, MVT::v2i32);
726 }
727
728 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
729   addRegisterClass(VT, &AArch64::FPR128RegClass);
730   addTypeForNEON(VT, MVT::v4i32);
731 }
732
733 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
734                                               EVT VT) const {
735   if (!VT.isVector())
736     return MVT::i32;
737   return VT.changeVectorElementTypeToInteger();
738 }
739
740 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
741 /// Mask are known to be either zero or one and return them in the
742 /// KnownZero/KnownOne bitsets.
743 void AArch64TargetLowering::computeKnownBitsForTargetNode(
744     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
745     const SelectionDAG &DAG, unsigned Depth) const {
746   switch (Op.getOpcode()) {
747   default:
748     break;
749   case AArch64ISD::CSEL: {
750     APInt KnownZero2, KnownOne2;
751     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
752     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
753     KnownZero &= KnownZero2;
754     KnownOne &= KnownOne2;
755     break;
756   }
757   case ISD::INTRINSIC_W_CHAIN: {
758     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
759     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
760     switch (IntID) {
761     default: return;
762     case Intrinsic::aarch64_ldaxr:
763     case Intrinsic::aarch64_ldxr: {
764       unsigned BitWidth = KnownOne.getBitWidth();
765       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
766       unsigned MemBits = VT.getScalarSizeInBits();
767       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
768       return;
769     }
770     }
771     break;
772   }
773   case ISD::INTRINSIC_WO_CHAIN:
774   case ISD::INTRINSIC_VOID: {
775     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
776     switch (IntNo) {
777     default:
778       break;
779     case Intrinsic::aarch64_neon_umaxv:
780     case Intrinsic::aarch64_neon_uminv: {
781       // Figure out the datatype of the vector operand. The UMINV instruction
782       // will zero extend the result, so we can mark as known zero all the
783       // bits larger than the element datatype. 32-bit or larget doesn't need
784       // this as those are legal types and will be handled by isel directly.
785       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
786       unsigned BitWidth = KnownZero.getBitWidth();
787       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
788         assert(BitWidth >= 8 && "Unexpected width!");
789         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
790         KnownZero |= Mask;
791       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
792         assert(BitWidth >= 16 && "Unexpected width!");
793         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
794         KnownZero |= Mask;
795       }
796       break;
797     } break;
798     }
799   }
800   }
801 }
802
803 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
804                                                   EVT) const {
805   return MVT::i64;
806 }
807
808 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
809                                                            unsigned AddrSpace,
810                                                            unsigned Align,
811                                                            bool *Fast) const {
812   if (Subtarget->requiresStrictAlign())
813     return false;
814
815   if (Fast) {
816     // Some CPUs are fine with unaligned stores except for 128-bit ones.
817     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
818             // See comments in performSTORECombine() for more details about
819             // these conditions.
820
821             // Code that uses clang vector extensions can mark that it
822             // wants unaligned accesses to be treated as fast by
823             // underspecifying alignment to be 1 or 2.
824             Align <= 2 ||
825
826             // Disregard v2i64. Memcpy lowering produces those and splitting
827             // them regresses performance on micro-benchmarks and olden/bh.
828             VT == MVT::v2i64;
829   }
830   return true;
831 }
832
833 FastISel *
834 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
835                                       const TargetLibraryInfo *libInfo) const {
836   return AArch64::createFastISel(funcInfo, libInfo);
837 }
838
839 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
840   switch ((AArch64ISD::NodeType)Opcode) {
841   case AArch64ISD::FIRST_NUMBER:      break;
842   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
843   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
844   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
845   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
846   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
847   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
848   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
849   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
850   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
851   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
852   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
853   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
854   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
855   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
856   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
857   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
858   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
859   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
860   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
861   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
862   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
863   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
864   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
865   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
866   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
867   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
868   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
869   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
870   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
871   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
872   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
873   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
874   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
875   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
876   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
877   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
878   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
879   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
880   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
881   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
882   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
883   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
884   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
885   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
886   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
887   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
888   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
889   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
890   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
891   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
892   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
893   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
894   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
895   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
896   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
897   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
898   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
899   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
900   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
901   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
902   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
903   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
904   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
905   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
906   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
907   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
908   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
909   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
910   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
911   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
912   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
913   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
914   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
915   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
916   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
917   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
918   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
919   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
920   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
921   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
922   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
923   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
924   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
925   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
926   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
927   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
928   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
929   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
930   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
931   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
932   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
933   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
934   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
935   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
936   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
937   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
938   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
939   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
940   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
941   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
942   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
943   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
944   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
945   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
946   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
947   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
948   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
949   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
950   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
951   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
952   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
953   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
954   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
955   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
956   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
957   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
958   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
959   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
960   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
961   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
962   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
963   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
964   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
965   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
966   }
967   return nullptr;
968 }
969
970 MachineBasicBlock *
971 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
972                                     MachineBasicBlock *MBB) const {
973   // We materialise the F128CSEL pseudo-instruction as some control flow and a
974   // phi node:
975
976   // OrigBB:
977   //     [... previous instrs leading to comparison ...]
978   //     b.ne TrueBB
979   //     b EndBB
980   // TrueBB:
981   //     ; Fallthrough
982   // EndBB:
983   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
984
985   MachineFunction *MF = MBB->getParent();
986   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
987   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
988   DebugLoc DL = MI.getDebugLoc();
989   MachineFunction::iterator It = ++MBB->getIterator();
990
991   unsigned DestReg = MI.getOperand(0).getReg();
992   unsigned IfTrueReg = MI.getOperand(1).getReg();
993   unsigned IfFalseReg = MI.getOperand(2).getReg();
994   unsigned CondCode = MI.getOperand(3).getImm();
995   bool NZCVKilled = MI.getOperand(4).isKill();
996
997   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
998   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
999   MF->insert(It, TrueBB);
1000   MF->insert(It, EndBB);
1001
1002   // Transfer rest of current basic-block to EndBB
1003   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1004                 MBB->end());
1005   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1006
1007   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1008   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1009   MBB->addSuccessor(TrueBB);
1010   MBB->addSuccessor(EndBB);
1011
1012   // TrueBB falls through to the end.
1013   TrueBB->addSuccessor(EndBB);
1014
1015   if (!NZCVKilled) {
1016     TrueBB->addLiveIn(AArch64::NZCV);
1017     EndBB->addLiveIn(AArch64::NZCV);
1018   }
1019
1020   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1021       .addReg(IfTrueReg)
1022       .addMBB(TrueBB)
1023       .addReg(IfFalseReg)
1024       .addMBB(MBB);
1025
1026   MI.eraseFromParent();
1027   return EndBB;
1028 }
1029
1030 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1031     MachineInstr &MI, MachineBasicBlock *BB) const {
1032   switch (MI.getOpcode()) {
1033   default:
1034 #ifndef NDEBUG
1035     MI.dump();
1036 #endif
1037     llvm_unreachable("Unexpected instruction for custom inserter!");
1038
1039   case AArch64::F128CSEL:
1040     return EmitF128CSEL(MI, BB);
1041
1042   case TargetOpcode::STACKMAP:
1043   case TargetOpcode::PATCHPOINT:
1044     return emitPatchPoint(MI, BB);
1045   }
1046 }
1047
1048 //===----------------------------------------------------------------------===//
1049 // AArch64 Lowering private implementation.
1050 //===----------------------------------------------------------------------===//
1051
1052 //===----------------------------------------------------------------------===//
1053 // Lowering Code
1054 //===----------------------------------------------------------------------===//
1055
1056 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1057 /// CC
1058 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1059   switch (CC) {
1060   default:
1061     llvm_unreachable("Unknown condition code!");
1062   case ISD::SETNE:
1063     return AArch64CC::NE;
1064   case ISD::SETEQ:
1065     return AArch64CC::EQ;
1066   case ISD::SETGT:
1067     return AArch64CC::GT;
1068   case ISD::SETGE:
1069     return AArch64CC::GE;
1070   case ISD::SETLT:
1071     return AArch64CC::LT;
1072   case ISD::SETLE:
1073     return AArch64CC::LE;
1074   case ISD::SETUGT:
1075     return AArch64CC::HI;
1076   case ISD::SETUGE:
1077     return AArch64CC::HS;
1078   case ISD::SETULT:
1079     return AArch64CC::LO;
1080   case ISD::SETULE:
1081     return AArch64CC::LS;
1082   }
1083 }
1084
1085 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1086 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1087                                   AArch64CC::CondCode &CondCode,
1088                                   AArch64CC::CondCode &CondCode2) {
1089   CondCode2 = AArch64CC::AL;
1090   switch (CC) {
1091   default:
1092     llvm_unreachable("Unknown FP condition!");
1093   case ISD::SETEQ:
1094   case ISD::SETOEQ:
1095     CondCode = AArch64CC::EQ;
1096     break;
1097   case ISD::SETGT:
1098   case ISD::SETOGT:
1099     CondCode = AArch64CC::GT;
1100     break;
1101   case ISD::SETGE:
1102   case ISD::SETOGE:
1103     CondCode = AArch64CC::GE;
1104     break;
1105   case ISD::SETOLT:
1106     CondCode = AArch64CC::MI;
1107     break;
1108   case ISD::SETOLE:
1109     CondCode = AArch64CC::LS;
1110     break;
1111   case ISD::SETONE:
1112     CondCode = AArch64CC::MI;
1113     CondCode2 = AArch64CC::GT;
1114     break;
1115   case ISD::SETO:
1116     CondCode = AArch64CC::VC;
1117     break;
1118   case ISD::SETUO:
1119     CondCode = AArch64CC::VS;
1120     break;
1121   case ISD::SETUEQ:
1122     CondCode = AArch64CC::EQ;
1123     CondCode2 = AArch64CC::VS;
1124     break;
1125   case ISD::SETUGT:
1126     CondCode = AArch64CC::HI;
1127     break;
1128   case ISD::SETUGE:
1129     CondCode = AArch64CC::PL;
1130     break;
1131   case ISD::SETLT:
1132   case ISD::SETULT:
1133     CondCode = AArch64CC::LT;
1134     break;
1135   case ISD::SETLE:
1136   case ISD::SETULE:
1137     CondCode = AArch64CC::LE;
1138     break;
1139   case ISD::SETNE:
1140   case ISD::SETUNE:
1141     CondCode = AArch64CC::NE;
1142     break;
1143   }
1144 }
1145
1146 /// Convert a DAG fp condition code to an AArch64 CC.
1147 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1148 /// should be AND'ed instead of OR'ed.
1149 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1150                                      AArch64CC::CondCode &CondCode,
1151                                      AArch64CC::CondCode &CondCode2) {
1152   CondCode2 = AArch64CC::AL;
1153   switch (CC) {
1154   default:
1155     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1156     assert(CondCode2 == AArch64CC::AL);
1157     break;
1158   case ISD::SETONE:
1159     // (a one b)
1160     // == ((a olt b) || (a ogt b))
1161     // == ((a ord b) && (a une b))
1162     CondCode = AArch64CC::VC;
1163     CondCode2 = AArch64CC::NE;
1164     break;
1165   case ISD::SETUEQ:
1166     // (a ueq b)
1167     // == ((a uno b) || (a oeq b))
1168     // == ((a ule b) && (a uge b))
1169     CondCode = AArch64CC::PL;
1170     CondCode2 = AArch64CC::LE;
1171     break;
1172   }
1173 }
1174
1175 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1176 /// CC usable with the vector instructions. Fewer operations are available
1177 /// without a real NZCV register, so we have to use less efficient combinations
1178 /// to get the same effect.
1179 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1180                                         AArch64CC::CondCode &CondCode,
1181                                         AArch64CC::CondCode &CondCode2,
1182                                         bool &Invert) {
1183   Invert = false;
1184   switch (CC) {
1185   default:
1186     // Mostly the scalar mappings work fine.
1187     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1188     break;
1189   case ISD::SETUO:
1190     Invert = true;
1191     LLVM_FALLTHROUGH;
1192   case ISD::SETO:
1193     CondCode = AArch64CC::MI;
1194     CondCode2 = AArch64CC::GE;
1195     break;
1196   case ISD::SETUEQ:
1197   case ISD::SETULT:
1198   case ISD::SETULE:
1199   case ISD::SETUGT:
1200   case ISD::SETUGE:
1201     // All of the compare-mask comparisons are ordered, but we can switch
1202     // between the two by a double inversion. E.g. ULE == !OGT.
1203     Invert = true;
1204     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1205     break;
1206   }
1207 }
1208
1209 static bool isLegalArithImmed(uint64_t C) {
1210   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1211   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1212 }
1213
1214 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1215                               const SDLoc &dl, SelectionDAG &DAG) {
1216   EVT VT = LHS.getValueType();
1217
1218   if (VT.isFloatingPoint()) {
1219     assert(VT != MVT::f128);
1220     if (VT == MVT::f16) {
1221       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1222       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1223       VT = MVT::f32;
1224     }
1225     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1226   }
1227
1228   // The CMP instruction is just an alias for SUBS, and representing it as
1229   // SUBS means that it's possible to get CSE with subtract operations.
1230   // A later phase can perform the optimization of setting the destination
1231   // register to WZR/XZR if it ends up being unused.
1232   unsigned Opcode = AArch64ISD::SUBS;
1233
1234   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1235       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1236     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1237     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1238     // can be set differently by this operation. It comes down to whether
1239     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1240     // everything is fine. If not then the optimization is wrong. Thus general
1241     // comparisons are only valid if op2 != 0.
1242
1243     // So, finally, the only LLVM-native comparisons that don't mention C and V
1244     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1245     // the absence of information about op2.
1246     Opcode = AArch64ISD::ADDS;
1247     RHS = RHS.getOperand(1);
1248   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1249              !isUnsignedIntSetCC(CC)) {
1250     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1251     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1252     // of the signed comparisons.
1253     Opcode = AArch64ISD::ANDS;
1254     RHS = LHS.getOperand(1);
1255     LHS = LHS.getOperand(0);
1256   }
1257
1258   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1259       .getValue(1);
1260 }
1261
1262 /// \defgroup AArch64CCMP CMP;CCMP matching
1263 ///
1264 /// These functions deal with the formation of CMP;CCMP;... sequences.
1265 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1266 /// a comparison. They set the NZCV flags to a predefined value if their
1267 /// predicate is false. This allows to express arbitrary conjunctions, for
1268 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1269 /// expressed as:
1270 ///   cmp A
1271 ///   ccmp B, inv(CB), CA
1272 ///   check for CB flags
1273 ///
1274 /// In general we can create code for arbitrary "... (and (and A B) C)"
1275 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1276 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1277 /// negation operations:
1278 /// We can negate the results of a single comparison by inverting the flags
1279 /// used when the predicate fails and inverting the flags tested in the next
1280 /// instruction; We can also negate the results of the whole previous
1281 /// conditional compare sequence by inverting the flags tested in the next
1282 /// instruction. However there is no way to negate the result of a partial
1283 /// sequence.
1284 ///
1285 /// Therefore on encountering an "or" expression we can negate the subtree on
1286 /// one side and have to be able to push the negate to the leafs of the subtree
1287 /// on the other side (see also the comments in code). As complete example:
1288 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1289 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1290 /// is transformed to
1291 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1292 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1293 /// and implemented as:
1294 ///   cmp C
1295 ///   ccmp D, inv(CD), CC
1296 ///   ccmp A, CA, inv(CD)
1297 ///   ccmp B, CB, inv(CA)
1298 ///   check for CB flags
1299 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1300 /// by conditional compare sequences.
1301 /// @{
1302
1303 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1304 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1305                                          ISD::CondCode CC, SDValue CCOp,
1306                                          AArch64CC::CondCode Predicate,
1307                                          AArch64CC::CondCode OutCC,
1308                                          const SDLoc &DL, SelectionDAG &DAG) {
1309   unsigned Opcode = 0;
1310   if (LHS.getValueType().isFloatingPoint()) {
1311     assert(LHS.getValueType() != MVT::f128);
1312     if (LHS.getValueType() == MVT::f16) {
1313       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1314       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1315     }
1316     Opcode = AArch64ISD::FCCMP;
1317   } else if (RHS.getOpcode() == ISD::SUB) {
1318     SDValue SubOp0 = RHS.getOperand(0);
1319     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1320       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1321       Opcode = AArch64ISD::CCMN;
1322       RHS = RHS.getOperand(1);
1323     }
1324   }
1325   if (Opcode == 0)
1326     Opcode = AArch64ISD::CCMP;
1327
1328   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1329   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1330   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1331   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1332   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1333 }
1334
1335 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1336 /// CanPushNegate is set to true if we can push a negate operation through
1337 /// the tree in a was that we are left with AND operations and negate operations
1338 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1339 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1340 /// brought into such a form.
1341 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1342                                          unsigned Depth = 0) {
1343   if (!Val.hasOneUse())
1344     return false;
1345   unsigned Opcode = Val->getOpcode();
1346   if (Opcode == ISD::SETCC) {
1347     if (Val->getOperand(0).getValueType() == MVT::f128)
1348       return false;
1349     CanNegate = true;
1350     return true;
1351   }
1352   // Protect against exponential runtime and stack overflow.
1353   if (Depth > 6)
1354     return false;
1355   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1356     SDValue O0 = Val->getOperand(0);
1357     SDValue O1 = Val->getOperand(1);
1358     bool CanNegateL;
1359     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1360       return false;
1361     bool CanNegateR;
1362     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1363       return false;
1364
1365     if (Opcode == ISD::OR) {
1366       // For an OR expression we need to be able to negate at least one side or
1367       // we cannot do the transformation at all.
1368       if (!CanNegateL && !CanNegateR)
1369         return false;
1370       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1371       // can negate the x and y subtrees.
1372       CanNegate = CanNegateL && CanNegateR;
1373     } else {
1374       // If the operands are OR expressions then we finally need to negate their
1375       // outputs, we can only do that for the operand with emitted last by
1376       // negating OutCC, not for both operands.
1377       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1378       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1379       if (NeedsNegOutL && NeedsNegOutR)
1380         return false;
1381       // We cannot negate an AND operation (it would become an OR),
1382       CanNegate = false;
1383     }
1384     return true;
1385   }
1386   return false;
1387 }
1388
1389 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1390 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1391 /// Tries to transform the given i1 producing node @p Val to a series compare
1392 /// and conditional compare operations. @returns an NZCV flags producing node
1393 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1394 /// transformation was not possible.
1395 /// On recursive invocations @p PushNegate may be set to true to have negation
1396 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1397 /// for the comparisons in the current subtree; @p Depth limits the search
1398 /// depth to avoid stack overflow.
1399 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1400     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1401     AArch64CC::CondCode Predicate) {
1402   // We're at a tree leaf, produce a conditional comparison operation.
1403   unsigned Opcode = Val->getOpcode();
1404   if (Opcode == ISD::SETCC) {
1405     SDValue LHS = Val->getOperand(0);
1406     SDValue RHS = Val->getOperand(1);
1407     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1408     bool isInteger = LHS.getValueType().isInteger();
1409     if (Negate)
1410       CC = getSetCCInverse(CC, isInteger);
1411     SDLoc DL(Val);
1412     // Determine OutCC and handle FP special case.
1413     if (isInteger) {
1414       OutCC = changeIntCCToAArch64CC(CC);
1415     } else {
1416       assert(LHS.getValueType().isFloatingPoint());
1417       AArch64CC::CondCode ExtraCC;
1418       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1419       // Some floating point conditions can't be tested with a single condition
1420       // code. Construct an additional comparison in this case.
1421       if (ExtraCC != AArch64CC::AL) {
1422         SDValue ExtraCmp;
1423         if (!CCOp.getNode())
1424           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1425         else
1426           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1427                                                ExtraCC, DL, DAG);
1428         CCOp = ExtraCmp;
1429         Predicate = ExtraCC;
1430       }
1431     }
1432
1433     // Produce a normal comparison if we are first in the chain
1434     if (!CCOp)
1435       return emitComparison(LHS, RHS, CC, DL, DAG);
1436     // Otherwise produce a ccmp.
1437     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1438                                      DAG);
1439   }
1440   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1441          "Valid conjunction/disjunction tree");
1442
1443   // Check if both sides can be transformed.
1444   SDValue LHS = Val->getOperand(0);
1445   SDValue RHS = Val->getOperand(1);
1446
1447   // In case of an OR we need to negate our operands and the result.
1448   // (A v B) <=> not(not(A) ^ not(B))
1449   bool NegateOpsAndResult = Opcode == ISD::OR;
1450   // We can negate the results of all previous operations by inverting the
1451   // predicate flags giving us a free negation for one side. The other side
1452   // must be negatable by itself.
1453   if (NegateOpsAndResult) {
1454     // See which side we can negate.
1455     bool CanNegateL;
1456     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1457     assert(isValidL && "Valid conjunction/disjunction tree");
1458     (void)isValidL;
1459
1460 #ifndef NDEBUG
1461     bool CanNegateR;
1462     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1463     assert(isValidR && "Valid conjunction/disjunction tree");
1464     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1465 #endif
1466
1467     // Order the side which we cannot negate to RHS so we can emit it first.
1468     if (!CanNegateL)
1469       std::swap(LHS, RHS);
1470   } else {
1471     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1472     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1473            "Valid conjunction/disjunction tree");
1474     // Order the side where we need to negate the output flags to RHS so it
1475     // gets emitted first.
1476     if (NeedsNegOutL)
1477       std::swap(LHS, RHS);
1478   }
1479
1480   // Emit RHS. If we want to negate the tree we only need to push a negate
1481   // through if we are already in a PushNegate case, otherwise we can negate
1482   // the "flags to test" afterwards.
1483   AArch64CC::CondCode RHSCC;
1484   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1485                                                    CCOp, Predicate);
1486   if (NegateOpsAndResult && !Negate)
1487     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1488   // Emit LHS. We may need to negate it.
1489   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1490                                                    NegateOpsAndResult, CmpR,
1491                                                    RHSCC);
1492   // If we transformed an OR to and AND then we have to negate the result
1493   // (or absorb the Negate parameter).
1494   if (NegateOpsAndResult && !Negate)
1495     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1496   return CmpL;
1497 }
1498
1499 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1500 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1501 /// \see emitConjunctionDisjunctionTreeRec().
1502 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1503                                               AArch64CC::CondCode &OutCC) {
1504   bool CanNegate;
1505   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1506     return SDValue();
1507
1508   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1509                                            AArch64CC::AL);
1510 }
1511
1512 /// @}
1513
1514 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1515                              SDValue &AArch64cc, SelectionDAG &DAG,
1516                              const SDLoc &dl) {
1517   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1518     EVT VT = RHS.getValueType();
1519     uint64_t C = RHSC->getZExtValue();
1520     if (!isLegalArithImmed(C)) {
1521       // Constant does not fit, try adjusting it by one?
1522       switch (CC) {
1523       default:
1524         break;
1525       case ISD::SETLT:
1526       case ISD::SETGE:
1527         if ((VT == MVT::i32 && C != 0x80000000 &&
1528              isLegalArithImmed((uint32_t)(C - 1))) ||
1529             (VT == MVT::i64 && C != 0x80000000ULL &&
1530              isLegalArithImmed(C - 1ULL))) {
1531           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1532           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1533           RHS = DAG.getConstant(C, dl, VT);
1534         }
1535         break;
1536       case ISD::SETULT:
1537       case ISD::SETUGE:
1538         if ((VT == MVT::i32 && C != 0 &&
1539              isLegalArithImmed((uint32_t)(C - 1))) ||
1540             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1541           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1542           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1543           RHS = DAG.getConstant(C, dl, VT);
1544         }
1545         break;
1546       case ISD::SETLE:
1547       case ISD::SETGT:
1548         if ((VT == MVT::i32 && C != INT32_MAX &&
1549              isLegalArithImmed((uint32_t)(C + 1))) ||
1550             (VT == MVT::i64 && C != INT64_MAX &&
1551              isLegalArithImmed(C + 1ULL))) {
1552           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1553           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1554           RHS = DAG.getConstant(C, dl, VT);
1555         }
1556         break;
1557       case ISD::SETULE:
1558       case ISD::SETUGT:
1559         if ((VT == MVT::i32 && C != UINT32_MAX &&
1560              isLegalArithImmed((uint32_t)(C + 1))) ||
1561             (VT == MVT::i64 && C != UINT64_MAX &&
1562              isLegalArithImmed(C + 1ULL))) {
1563           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1564           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1565           RHS = DAG.getConstant(C, dl, VT);
1566         }
1567         break;
1568       }
1569     }
1570   }
1571   SDValue Cmp;
1572   AArch64CC::CondCode AArch64CC;
1573   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1574     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1575
1576     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1577     // For the i8 operand, the largest immediate is 255, so this can be easily
1578     // encoded in the compare instruction. For the i16 operand, however, the
1579     // largest immediate cannot be encoded in the compare.
1580     // Therefore, use a sign extending load and cmn to avoid materializing the
1581     // -1 constant. For example,
1582     // movz w1, #65535
1583     // ldrh w0, [x0, #0]
1584     // cmp w0, w1
1585     // >
1586     // ldrsh w0, [x0, #0]
1587     // cmn w0, #1
1588     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1589     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1590     // ensure both the LHS and RHS are truly zero extended and to make sure the
1591     // transformation is profitable.
1592     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1593         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1594         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1595         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1596       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1597       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1598         SDValue SExt =
1599             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1600                         DAG.getValueType(MVT::i16));
1601         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1602                                                    RHS.getValueType()),
1603                              CC, dl, DAG);
1604         AArch64CC = changeIntCCToAArch64CC(CC);
1605       }
1606     }
1607
1608     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1609       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1610         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1611           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1612       }
1613     }
1614   }
1615
1616   if (!Cmp) {
1617     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1618     AArch64CC = changeIntCCToAArch64CC(CC);
1619   }
1620   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1621   return Cmp;
1622 }
1623
1624 static std::pair<SDValue, SDValue>
1625 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1626   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1627          "Unsupported value type");
1628   SDValue Value, Overflow;
1629   SDLoc DL(Op);
1630   SDValue LHS = Op.getOperand(0);
1631   SDValue RHS = Op.getOperand(1);
1632   unsigned Opc = 0;
1633   switch (Op.getOpcode()) {
1634   default:
1635     llvm_unreachable("Unknown overflow instruction!");
1636   case ISD::SADDO:
1637     Opc = AArch64ISD::ADDS;
1638     CC = AArch64CC::VS;
1639     break;
1640   case ISD::UADDO:
1641     Opc = AArch64ISD::ADDS;
1642     CC = AArch64CC::HS;
1643     break;
1644   case ISD::SSUBO:
1645     Opc = AArch64ISD::SUBS;
1646     CC = AArch64CC::VS;
1647     break;
1648   case ISD::USUBO:
1649     Opc = AArch64ISD::SUBS;
1650     CC = AArch64CC::LO;
1651     break;
1652   // Multiply needs a little bit extra work.
1653   case ISD::SMULO:
1654   case ISD::UMULO: {
1655     CC = AArch64CC::NE;
1656     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1657     if (Op.getValueType() == MVT::i32) {
1658       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1659       // For a 32 bit multiply with overflow check we want the instruction
1660       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1661       // need to generate the following pattern:
1662       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1663       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1664       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1665       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1666       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1667                                 DAG.getConstant(0, DL, MVT::i64));
1668       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1669       // operation. We need to clear out the upper 32 bits, because we used a
1670       // widening multiply that wrote all 64 bits. In the end this should be a
1671       // noop.
1672       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1673       if (IsSigned) {
1674         // The signed overflow check requires more than just a simple check for
1675         // any bit set in the upper 32 bits of the result. These bits could be
1676         // just the sign bits of a negative number. To perform the overflow
1677         // check we have to arithmetic shift right the 32nd bit of the result by
1678         // 31 bits. Then we compare the result to the upper 32 bits.
1679         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1680                                         DAG.getConstant(32, DL, MVT::i64));
1681         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1682         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1683                                         DAG.getConstant(31, DL, MVT::i64));
1684         // It is important that LowerBits is last, otherwise the arithmetic
1685         // shift will not be folded into the compare (SUBS).
1686         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1687         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1688                        .getValue(1);
1689       } else {
1690         // The overflow check for unsigned multiply is easy. We only need to
1691         // check if any of the upper 32 bits are set. This can be done with a
1692         // CMP (shifted register). For that we need to generate the following
1693         // pattern:
1694         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1695         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1696                                         DAG.getConstant(32, DL, MVT::i64));
1697         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1698         Overflow =
1699             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1700                         DAG.getConstant(0, DL, MVT::i64),
1701                         UpperBits).getValue(1);
1702       }
1703       break;
1704     }
1705     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1706     // For the 64 bit multiply
1707     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1708     if (IsSigned) {
1709       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1710       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1711                                       DAG.getConstant(63, DL, MVT::i64));
1712       // It is important that LowerBits is last, otherwise the arithmetic
1713       // shift will not be folded into the compare (SUBS).
1714       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1715       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1716                      .getValue(1);
1717     } else {
1718       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1719       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1720       Overflow =
1721           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1722                       DAG.getConstant(0, DL, MVT::i64),
1723                       UpperBits).getValue(1);
1724     }
1725     break;
1726   }
1727   } // switch (...)
1728
1729   if (Opc) {
1730     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1731
1732     // Emit the AArch64 operation with overflow check.
1733     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1734     Overflow = Value.getValue(1);
1735   }
1736   return std::make_pair(Value, Overflow);
1737 }
1738
1739 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1740                                              RTLIB::Libcall Call) const {
1741   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1742   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1743 }
1744
1745 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1746   SDValue Sel = Op.getOperand(0);
1747   SDValue Other = Op.getOperand(1);
1748
1749   // If neither operand is a SELECT_CC, give up.
1750   if (Sel.getOpcode() != ISD::SELECT_CC)
1751     std::swap(Sel, Other);
1752   if (Sel.getOpcode() != ISD::SELECT_CC)
1753     return Op;
1754
1755   // The folding we want to perform is:
1756   // (xor x, (select_cc a, b, cc, 0, -1) )
1757   //   -->
1758   // (csel x, (xor x, -1), cc ...)
1759   //
1760   // The latter will get matched to a CSINV instruction.
1761
1762   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1763   SDValue LHS = Sel.getOperand(0);
1764   SDValue RHS = Sel.getOperand(1);
1765   SDValue TVal = Sel.getOperand(2);
1766   SDValue FVal = Sel.getOperand(3);
1767   SDLoc dl(Sel);
1768
1769   // FIXME: This could be generalized to non-integer comparisons.
1770   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1771     return Op;
1772
1773   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1774   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1775
1776   // The values aren't constants, this isn't the pattern we're looking for.
1777   if (!CFVal || !CTVal)
1778     return Op;
1779
1780   // We can commute the SELECT_CC by inverting the condition.  This
1781   // might be needed to make this fit into a CSINV pattern.
1782   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1783     std::swap(TVal, FVal);
1784     std::swap(CTVal, CFVal);
1785     CC = ISD::getSetCCInverse(CC, true);
1786   }
1787
1788   // If the constants line up, perform the transform!
1789   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1790     SDValue CCVal;
1791     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1792
1793     FVal = Other;
1794     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1795                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1796
1797     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1798                        CCVal, Cmp);
1799   }
1800
1801   return Op;
1802 }
1803
1804 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1805   EVT VT = Op.getValueType();
1806
1807   // Let legalize expand this if it isn't a legal type yet.
1808   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1809     return SDValue();
1810
1811   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1812
1813   unsigned Opc;
1814   bool ExtraOp = false;
1815   switch (Op.getOpcode()) {
1816   default:
1817     llvm_unreachable("Invalid code");
1818   case ISD::ADDC:
1819     Opc = AArch64ISD::ADDS;
1820     break;
1821   case ISD::SUBC:
1822     Opc = AArch64ISD::SUBS;
1823     break;
1824   case ISD::ADDE:
1825     Opc = AArch64ISD::ADCS;
1826     ExtraOp = true;
1827     break;
1828   case ISD::SUBE:
1829     Opc = AArch64ISD::SBCS;
1830     ExtraOp = true;
1831     break;
1832   }
1833
1834   if (!ExtraOp)
1835     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1836   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1837                      Op.getOperand(2));
1838 }
1839
1840 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1841   // Let legalize expand this if it isn't a legal type yet.
1842   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1843     return SDValue();
1844
1845   SDLoc dl(Op);
1846   AArch64CC::CondCode CC;
1847   // The actual operation that sets the overflow or carry flag.
1848   SDValue Value, Overflow;
1849   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1850
1851   // We use 0 and 1 as false and true values.
1852   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1853   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1854
1855   // We use an inverted condition, because the conditional select is inverted
1856   // too. This will allow it to be selected to a single instruction:
1857   // CSINC Wd, WZR, WZR, invert(cond).
1858   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1859   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1860                          CCVal, Overflow);
1861
1862   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1863   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1864 }
1865
1866 // Prefetch operands are:
1867 // 1: Address to prefetch
1868 // 2: bool isWrite
1869 // 3: int locality (0 = no locality ... 3 = extreme locality)
1870 // 4: bool isDataCache
1871 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1872   SDLoc DL(Op);
1873   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1874   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1875   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1876
1877   bool IsStream = !Locality;
1878   // When the locality number is set
1879   if (Locality) {
1880     // The front-end should have filtered out the out-of-range values
1881     assert(Locality <= 3 && "Prefetch locality out-of-range");
1882     // The locality degree is the opposite of the cache speed.
1883     // Put the number the other way around.
1884     // The encoding starts at 0 for level 1
1885     Locality = 3 - Locality;
1886   }
1887
1888   // built the mask value encoding the expected behavior.
1889   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1890                    (!IsData << 3) |     // IsDataCache bit
1891                    (Locality << 1) |    // Cache level bits
1892                    (unsigned)IsStream;  // Stream bit
1893   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1894                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1895 }
1896
1897 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1898                                               SelectionDAG &DAG) const {
1899   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1900
1901   RTLIB::Libcall LC;
1902   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1903
1904   return LowerF128Call(Op, DAG, LC);
1905 }
1906
1907 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1908                                              SelectionDAG &DAG) const {
1909   if (Op.getOperand(0).getValueType() != MVT::f128) {
1910     // It's legal except when f128 is involved
1911     return Op;
1912   }
1913
1914   RTLIB::Libcall LC;
1915   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1916
1917   // FP_ROUND node has a second operand indicating whether it is known to be
1918   // precise. That doesn't take part in the LibCall so we can't directly use
1919   // LowerF128Call.
1920   SDValue SrcVal = Op.getOperand(0);
1921   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1922                      SDLoc(Op)).first;
1923 }
1924
1925 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1926   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1927   // Any additional optimization in this function should be recorded
1928   // in the cost tables.
1929   EVT InVT = Op.getOperand(0).getValueType();
1930   EVT VT = Op.getValueType();
1931   unsigned NumElts = InVT.getVectorNumElements();
1932
1933   // f16 vectors are promoted to f32 before a conversion.
1934   if (InVT.getVectorElementType() == MVT::f16) {
1935     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1936     SDLoc dl(Op);
1937     return DAG.getNode(
1938         Op.getOpcode(), dl, Op.getValueType(),
1939         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1940   }
1941
1942   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1943     SDLoc dl(Op);
1944     SDValue Cv =
1945         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1946                     Op.getOperand(0));
1947     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1948   }
1949
1950   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1951     SDLoc dl(Op);
1952     MVT ExtVT =
1953         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1954                          VT.getVectorNumElements());
1955     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1956     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1957   }
1958
1959   // Type changing conversions are illegal.
1960   return Op;
1961 }
1962
1963 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1964                                               SelectionDAG &DAG) const {
1965   if (Op.getOperand(0).getValueType().isVector())
1966     return LowerVectorFP_TO_INT(Op, DAG);
1967
1968   // f16 conversions are promoted to f32.
1969   if (Op.getOperand(0).getValueType() == MVT::f16) {
1970     SDLoc dl(Op);
1971     return DAG.getNode(
1972         Op.getOpcode(), dl, Op.getValueType(),
1973         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1974   }
1975
1976   if (Op.getOperand(0).getValueType() != MVT::f128) {
1977     // It's legal except when f128 is involved
1978     return Op;
1979   }
1980
1981   RTLIB::Libcall LC;
1982   if (Op.getOpcode() == ISD::FP_TO_SINT)
1983     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1984   else
1985     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1986
1987   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1988   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1989 }
1990
1991 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1992   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1993   // Any additional optimization in this function should be recorded
1994   // in the cost tables.
1995   EVT VT = Op.getValueType();
1996   SDLoc dl(Op);
1997   SDValue In = Op.getOperand(0);
1998   EVT InVT = In.getValueType();
1999
2000   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2001     MVT CastVT =
2002         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2003                          InVT.getVectorNumElements());
2004     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2005     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2006   }
2007
2008   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2009     unsigned CastOpc =
2010         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2011     EVT CastVT = VT.changeVectorElementTypeToInteger();
2012     In = DAG.getNode(CastOpc, dl, CastVT, In);
2013     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2014   }
2015
2016   return Op;
2017 }
2018
2019 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2020                                             SelectionDAG &DAG) const {
2021   if (Op.getValueType().isVector())
2022     return LowerVectorINT_TO_FP(Op, DAG);
2023
2024   // f16 conversions are promoted to f32.
2025   if (Op.getValueType() == MVT::f16) {
2026     SDLoc dl(Op);
2027     return DAG.getNode(
2028         ISD::FP_ROUND, dl, MVT::f16,
2029         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2030         DAG.getIntPtrConstant(0, dl));
2031   }
2032
2033   // i128 conversions are libcalls.
2034   if (Op.getOperand(0).getValueType() == MVT::i128)
2035     return SDValue();
2036
2037   // Other conversions are legal, unless it's to the completely software-based
2038   // fp128.
2039   if (Op.getValueType() != MVT::f128)
2040     return Op;
2041
2042   RTLIB::Libcall LC;
2043   if (Op.getOpcode() == ISD::SINT_TO_FP)
2044     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2045   else
2046     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2047
2048   return LowerF128Call(Op, DAG, LC);
2049 }
2050
2051 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2052                                             SelectionDAG &DAG) const {
2053   // For iOS, we want to call an alternative entry point: __sincos_stret,
2054   // which returns the values in two S / D registers.
2055   SDLoc dl(Op);
2056   SDValue Arg = Op.getOperand(0);
2057   EVT ArgVT = Arg.getValueType();
2058   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2059
2060   ArgListTy Args;
2061   ArgListEntry Entry;
2062
2063   Entry.Node = Arg;
2064   Entry.Ty = ArgTy;
2065   Entry.isSExt = false;
2066   Entry.isZExt = false;
2067   Args.push_back(Entry);
2068
2069   const char *LibcallName =
2070       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2071   SDValue Callee =
2072       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2073
2074   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2075   TargetLowering::CallLoweringInfo CLI(DAG);
2076   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2077     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2078
2079   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2080   return CallResult.first;
2081 }
2082
2083 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2084   if (Op.getValueType() != MVT::f16)
2085     return SDValue();
2086
2087   assert(Op.getOperand(0).getValueType() == MVT::i16);
2088   SDLoc DL(Op);
2089
2090   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2091   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2092   return SDValue(
2093       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2094                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2095       0);
2096 }
2097
2098 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2099   if (OrigVT.getSizeInBits() >= 64)
2100     return OrigVT;
2101
2102   assert(OrigVT.isSimple() && "Expecting a simple value type");
2103
2104   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2105   switch (OrigSimpleTy) {
2106   default: llvm_unreachable("Unexpected Vector Type");
2107   case MVT::v2i8:
2108   case MVT::v2i16:
2109      return MVT::v2i32;
2110   case MVT::v4i8:
2111     return  MVT::v4i16;
2112   }
2113 }
2114
2115 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2116                                                  const EVT &OrigTy,
2117                                                  const EVT &ExtTy,
2118                                                  unsigned ExtOpcode) {
2119   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2120   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2121   // 64-bits we need to insert a new extension so that it will be 64-bits.
2122   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2123   if (OrigTy.getSizeInBits() >= 64)
2124     return N;
2125
2126   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2127   EVT NewVT = getExtensionTo64Bits(OrigTy);
2128
2129   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2130 }
2131
2132 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2133                                    bool isSigned) {
2134   EVT VT = N->getValueType(0);
2135
2136   if (N->getOpcode() != ISD::BUILD_VECTOR)
2137     return false;
2138
2139   for (const SDValue &Elt : N->op_values()) {
2140     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2141       unsigned EltSize = VT.getScalarSizeInBits();
2142       unsigned HalfSize = EltSize / 2;
2143       if (isSigned) {
2144         if (!isIntN(HalfSize, C->getSExtValue()))
2145           return false;
2146       } else {
2147         if (!isUIntN(HalfSize, C->getZExtValue()))
2148           return false;
2149       }
2150       continue;
2151     }
2152     return false;
2153   }
2154
2155   return true;
2156 }
2157
2158 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2159   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2160     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2161                                              N->getOperand(0)->getValueType(0),
2162                                              N->getValueType(0),
2163                                              N->getOpcode());
2164
2165   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2166   EVT VT = N->getValueType(0);
2167   SDLoc dl(N);
2168   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2169   unsigned NumElts = VT.getVectorNumElements();
2170   MVT TruncVT = MVT::getIntegerVT(EltSize);
2171   SmallVector<SDValue, 8> Ops;
2172   for (unsigned i = 0; i != NumElts; ++i) {
2173     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2174     const APInt &CInt = C->getAPIntValue();
2175     // Element types smaller than 32 bits are not legal, so use i32 elements.
2176     // The values are implicitly truncated so sext vs. zext doesn't matter.
2177     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2178   }
2179   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2180 }
2181
2182 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2183   if (N->getOpcode() == ISD::SIGN_EXTEND)
2184     return true;
2185   if (isExtendedBUILD_VECTOR(N, DAG, true))
2186     return true;
2187   return false;
2188 }
2189
2190 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2191   if (N->getOpcode() == ISD::ZERO_EXTEND)
2192     return true;
2193   if (isExtendedBUILD_VECTOR(N, DAG, false))
2194     return true;
2195   return false;
2196 }
2197
2198 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2199   unsigned Opcode = N->getOpcode();
2200   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2201     SDNode *N0 = N->getOperand(0).getNode();
2202     SDNode *N1 = N->getOperand(1).getNode();
2203     return N0->hasOneUse() && N1->hasOneUse() &&
2204       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2205   }
2206   return false;
2207 }
2208
2209 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2210   unsigned Opcode = N->getOpcode();
2211   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2212     SDNode *N0 = N->getOperand(0).getNode();
2213     SDNode *N1 = N->getOperand(1).getNode();
2214     return N0->hasOneUse() && N1->hasOneUse() &&
2215       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2216   }
2217   return false;
2218 }
2219
2220 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2221   // Multiplications are only custom-lowered for 128-bit vectors so that
2222   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2223   EVT VT = Op.getValueType();
2224   assert(VT.is128BitVector() && VT.isInteger() &&
2225          "unexpected type for custom-lowering ISD::MUL");
2226   SDNode *N0 = Op.getOperand(0).getNode();
2227   SDNode *N1 = Op.getOperand(1).getNode();
2228   unsigned NewOpc = 0;
2229   bool isMLA = false;
2230   bool isN0SExt = isSignExtended(N0, DAG);
2231   bool isN1SExt = isSignExtended(N1, DAG);
2232   if (isN0SExt && isN1SExt)
2233     NewOpc = AArch64ISD::SMULL;
2234   else {
2235     bool isN0ZExt = isZeroExtended(N0, DAG);
2236     bool isN1ZExt = isZeroExtended(N1, DAG);
2237     if (isN0ZExt && isN1ZExt)
2238       NewOpc = AArch64ISD::UMULL;
2239     else if (isN1SExt || isN1ZExt) {
2240       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2241       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2242       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2243         NewOpc = AArch64ISD::SMULL;
2244         isMLA = true;
2245       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2246         NewOpc =  AArch64ISD::UMULL;
2247         isMLA = true;
2248       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2249         std::swap(N0, N1);
2250         NewOpc =  AArch64ISD::UMULL;
2251         isMLA = true;
2252       }
2253     }
2254
2255     if (!NewOpc) {
2256       if (VT == MVT::v2i64)
2257         // Fall through to expand this.  It is not legal.
2258         return SDValue();
2259       else
2260         // Other vector multiplications are legal.
2261         return Op;
2262     }
2263   }
2264
2265   // Legalize to a S/UMULL instruction
2266   SDLoc DL(Op);
2267   SDValue Op0;
2268   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2269   if (!isMLA) {
2270     Op0 = skipExtensionForVectorMULL(N0, DAG);
2271     assert(Op0.getValueType().is64BitVector() &&
2272            Op1.getValueType().is64BitVector() &&
2273            "unexpected types for extended operands to VMULL");
2274     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2275   }
2276   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2277   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2278   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2279   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2280   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2281   EVT Op1VT = Op1.getValueType();
2282   return DAG.getNode(N0->getOpcode(), DL, VT,
2283                      DAG.getNode(NewOpc, DL, VT,
2284                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2285                      DAG.getNode(NewOpc, DL, VT,
2286                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2287 }
2288
2289 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2290                                                      SelectionDAG &DAG) const {
2291   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2292   SDLoc dl(Op);
2293   switch (IntNo) {
2294   default: return SDValue();    // Don't custom lower most intrinsics.
2295   case Intrinsic::thread_pointer: {
2296     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2297     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2298   }
2299   case Intrinsic::aarch64_neon_smax:
2300     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2301                        Op.getOperand(1), Op.getOperand(2));
2302   case Intrinsic::aarch64_neon_umax:
2303     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2304                        Op.getOperand(1), Op.getOperand(2));
2305   case Intrinsic::aarch64_neon_smin:
2306     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2307                        Op.getOperand(1), Op.getOperand(2));
2308   case Intrinsic::aarch64_neon_umin:
2309     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2310                        Op.getOperand(1), Op.getOperand(2));
2311   }
2312 }
2313
2314 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2315                                               SelectionDAG &DAG) const {
2316   switch (Op.getOpcode()) {
2317   default:
2318     llvm_unreachable("unimplemented operand");
2319     return SDValue();
2320   case ISD::BITCAST:
2321     return LowerBITCAST(Op, DAG);
2322   case ISD::GlobalAddress:
2323     return LowerGlobalAddress(Op, DAG);
2324   case ISD::GlobalTLSAddress:
2325     return LowerGlobalTLSAddress(Op, DAG);
2326   case ISD::SETCC:
2327     return LowerSETCC(Op, DAG);
2328   case ISD::BR_CC:
2329     return LowerBR_CC(Op, DAG);
2330   case ISD::SELECT:
2331     return LowerSELECT(Op, DAG);
2332   case ISD::SELECT_CC:
2333     return LowerSELECT_CC(Op, DAG);
2334   case ISD::JumpTable:
2335     return LowerJumpTable(Op, DAG);
2336   case ISD::ConstantPool:
2337     return LowerConstantPool(Op, DAG);
2338   case ISD::BlockAddress:
2339     return LowerBlockAddress(Op, DAG);
2340   case ISD::VASTART:
2341     return LowerVASTART(Op, DAG);
2342   case ISD::VACOPY:
2343     return LowerVACOPY(Op, DAG);
2344   case ISD::VAARG:
2345     return LowerVAARG(Op, DAG);
2346   case ISD::ADDC:
2347   case ISD::ADDE:
2348   case ISD::SUBC:
2349   case ISD::SUBE:
2350     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2351   case ISD::SADDO:
2352   case ISD::UADDO:
2353   case ISD::SSUBO:
2354   case ISD::USUBO:
2355   case ISD::SMULO:
2356   case ISD::UMULO:
2357     return LowerXALUO(Op, DAG);
2358   case ISD::FADD:
2359     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2360   case ISD::FSUB:
2361     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2362   case ISD::FMUL:
2363     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2364   case ISD::FDIV:
2365     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2366   case ISD::FP_ROUND:
2367     return LowerFP_ROUND(Op, DAG);
2368   case ISD::FP_EXTEND:
2369     return LowerFP_EXTEND(Op, DAG);
2370   case ISD::FRAMEADDR:
2371     return LowerFRAMEADDR(Op, DAG);
2372   case ISD::RETURNADDR:
2373     return LowerRETURNADDR(Op, DAG);
2374   case ISD::INSERT_VECTOR_ELT:
2375     return LowerINSERT_VECTOR_ELT(Op, DAG);
2376   case ISD::EXTRACT_VECTOR_ELT:
2377     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2378   case ISD::BUILD_VECTOR:
2379     return LowerBUILD_VECTOR(Op, DAG);
2380   case ISD::VECTOR_SHUFFLE:
2381     return LowerVECTOR_SHUFFLE(Op, DAG);
2382   case ISD::EXTRACT_SUBVECTOR:
2383     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2384   case ISD::SRA:
2385   case ISD::SRL:
2386   case ISD::SHL:
2387     return LowerVectorSRA_SRL_SHL(Op, DAG);
2388   case ISD::SHL_PARTS:
2389     return LowerShiftLeftParts(Op, DAG);
2390   case ISD::SRL_PARTS:
2391   case ISD::SRA_PARTS:
2392     return LowerShiftRightParts(Op, DAG);
2393   case ISD::CTPOP:
2394     return LowerCTPOP(Op, DAG);
2395   case ISD::FCOPYSIGN:
2396     return LowerFCOPYSIGN(Op, DAG);
2397   case ISD::AND:
2398     return LowerVectorAND(Op, DAG);
2399   case ISD::OR:
2400     return LowerVectorOR(Op, DAG);
2401   case ISD::XOR:
2402     return LowerXOR(Op, DAG);
2403   case ISD::PREFETCH:
2404     return LowerPREFETCH(Op, DAG);
2405   case ISD::SINT_TO_FP:
2406   case ISD::UINT_TO_FP:
2407     return LowerINT_TO_FP(Op, DAG);
2408   case ISD::FP_TO_SINT:
2409   case ISD::FP_TO_UINT:
2410     return LowerFP_TO_INT(Op, DAG);
2411   case ISD::FSINCOS:
2412     return LowerFSINCOS(Op, DAG);
2413   case ISD::MUL:
2414     return LowerMUL(Op, DAG);
2415   case ISD::INTRINSIC_WO_CHAIN:
2416     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2417   }
2418 }
2419
2420 //===----------------------------------------------------------------------===//
2421 //                      Calling Convention Implementation
2422 //===----------------------------------------------------------------------===//
2423
2424 #include "AArch64GenCallingConv.inc"
2425
2426 /// Selects the correct CCAssignFn for a given CallingConvention value.
2427 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2428                                                      bool IsVarArg) const {
2429   switch (CC) {
2430   default:
2431     llvm_unreachable("Unsupported calling convention.");
2432   case CallingConv::WebKit_JS:
2433     return CC_AArch64_WebKit_JS;
2434   case CallingConv::GHC:
2435     return CC_AArch64_GHC;
2436   case CallingConv::C:
2437   case CallingConv::Fast:
2438   case CallingConv::PreserveMost:
2439   case CallingConv::CXX_FAST_TLS:
2440   case CallingConv::Swift:
2441     if (!Subtarget->isTargetDarwin())
2442       return CC_AArch64_AAPCS;
2443     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2444   }
2445 }
2446
2447 CCAssignFn *
2448 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2449   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2450                                       : RetCC_AArch64_AAPCS;
2451 }
2452
2453 SDValue AArch64TargetLowering::LowerFormalArguments(
2454     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2455     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2456     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2457   MachineFunction &MF = DAG.getMachineFunction();
2458   MachineFrameInfo &MFI = MF.getFrameInfo();
2459
2460   // Assign locations to all of the incoming arguments.
2461   SmallVector<CCValAssign, 16> ArgLocs;
2462   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2463                  *DAG.getContext());
2464
2465   // At this point, Ins[].VT may already be promoted to i32. To correctly
2466   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2467   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2468   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2469   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2470   // LocVT.
2471   unsigned NumArgs = Ins.size();
2472   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2473   unsigned CurArgIdx = 0;
2474   for (unsigned i = 0; i != NumArgs; ++i) {
2475     MVT ValVT = Ins[i].VT;
2476     if (Ins[i].isOrigArg()) {
2477       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2478       CurArgIdx = Ins[i].getOrigArgIndex();
2479
2480       // Get type of the original argument.
2481       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2482                                   /*AllowUnknown*/ true);
2483       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2484       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2485       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2486         ValVT = MVT::i8;
2487       else if (ActualMVT == MVT::i16)
2488         ValVT = MVT::i16;
2489     }
2490     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2491     bool Res =
2492         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2493     assert(!Res && "Call operand has unhandled type");
2494     (void)Res;
2495   }
2496   assert(ArgLocs.size() == Ins.size());
2497   SmallVector<SDValue, 16> ArgValues;
2498   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2499     CCValAssign &VA = ArgLocs[i];
2500
2501     if (Ins[i].Flags.isByVal()) {
2502       // Byval is used for HFAs in the PCS, but the system should work in a
2503       // non-compliant manner for larger structs.
2504       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2505       int Size = Ins[i].Flags.getByValSize();
2506       unsigned NumRegs = (Size + 7) / 8;
2507
2508       // FIXME: This works on big-endian for composite byvals, which are the common
2509       // case. It should also work for fundamental types too.
2510       unsigned FrameIdx =
2511         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2512       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2513       InVals.push_back(FrameIdxN);
2514
2515       continue;
2516     }
2517
2518     if (VA.isRegLoc()) {
2519       // Arguments stored in registers.
2520       EVT RegVT = VA.getLocVT();
2521
2522       SDValue ArgValue;
2523       const TargetRegisterClass *RC;
2524
2525       if (RegVT == MVT::i32)
2526         RC = &AArch64::GPR32RegClass;
2527       else if (RegVT == MVT::i64)
2528         RC = &AArch64::GPR64RegClass;
2529       else if (RegVT == MVT::f16)
2530         RC = &AArch64::FPR16RegClass;
2531       else if (RegVT == MVT::f32)
2532         RC = &AArch64::FPR32RegClass;
2533       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2534         RC = &AArch64::FPR64RegClass;
2535       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2536         RC = &AArch64::FPR128RegClass;
2537       else
2538         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2539
2540       // Transform the arguments in physical registers into virtual ones.
2541       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2542       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2543
2544       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2545       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2546       // truncate to the right size.
2547       switch (VA.getLocInfo()) {
2548       default:
2549         llvm_unreachable("Unknown loc info!");
2550       case CCValAssign::Full:
2551         break;
2552       case CCValAssign::BCvt:
2553         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2554         break;
2555       case CCValAssign::AExt:
2556       case CCValAssign::SExt:
2557       case CCValAssign::ZExt:
2558         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2559         // nodes after our lowering.
2560         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2561         break;
2562       }
2563
2564       InVals.push_back(ArgValue);
2565
2566     } else { // VA.isRegLoc()
2567       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2568       unsigned ArgOffset = VA.getLocMemOffset();
2569       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2570
2571       uint32_t BEAlign = 0;
2572       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2573           !Ins[i].Flags.isInConsecutiveRegs())
2574         BEAlign = 8 - ArgSize;
2575
2576       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2577
2578       // Create load nodes to retrieve arguments from the stack.
2579       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2580       SDValue ArgValue;
2581
2582       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2583       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2584       MVT MemVT = VA.getValVT();
2585
2586       switch (VA.getLocInfo()) {
2587       default:
2588         break;
2589       case CCValAssign::BCvt:
2590         MemVT = VA.getLocVT();
2591         break;
2592       case CCValAssign::SExt:
2593         ExtType = ISD::SEXTLOAD;
2594         break;
2595       case CCValAssign::ZExt:
2596         ExtType = ISD::ZEXTLOAD;
2597         break;
2598       case CCValAssign::AExt:
2599         ExtType = ISD::EXTLOAD;
2600         break;
2601       }
2602
2603       ArgValue = DAG.getExtLoad(
2604           ExtType, DL, VA.getLocVT(), Chain, FIN,
2605           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2606           MemVT);
2607
2608       InVals.push_back(ArgValue);
2609     }
2610   }
2611
2612   // varargs
2613   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2614   if (isVarArg) {
2615     if (!Subtarget->isTargetDarwin()) {
2616       // The AAPCS variadic function ABI is identical to the non-variadic
2617       // one. As a result there may be more arguments in registers and we should
2618       // save them for future reference.
2619       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2620     }
2621
2622     // This will point to the next argument passed via stack.
2623     unsigned StackOffset = CCInfo.getNextStackOffset();
2624     // We currently pass all varargs at 8-byte alignment.
2625     StackOffset = ((StackOffset + 7) & ~7);
2626     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2627   }
2628
2629   unsigned StackArgSize = CCInfo.getNextStackOffset();
2630   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2631   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2632     // This is a non-standard ABI so by fiat I say we're allowed to make full
2633     // use of the stack area to be popped, which must be aligned to 16 bytes in
2634     // any case:
2635     StackArgSize = alignTo(StackArgSize, 16);
2636
2637     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2638     // a multiple of 16.
2639     FuncInfo->setArgumentStackToRestore(StackArgSize);
2640
2641     // This realignment carries over to the available bytes below. Our own
2642     // callers will guarantee the space is free by giving an aligned value to
2643     // CALLSEQ_START.
2644   }
2645   // Even if we're not expected to free up the space, it's useful to know how
2646   // much is there while considering tail calls (because we can reuse it).
2647   FuncInfo->setBytesInStackArgArea(StackArgSize);
2648
2649   return Chain;
2650 }
2651
2652 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2653                                                 SelectionDAG &DAG,
2654                                                 const SDLoc &DL,
2655                                                 SDValue &Chain) const {
2656   MachineFunction &MF = DAG.getMachineFunction();
2657   MachineFrameInfo &MFI = MF.getFrameInfo();
2658   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2659   auto PtrVT = getPointerTy(DAG.getDataLayout());
2660
2661   SmallVector<SDValue, 8> MemOps;
2662
2663   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2664                                           AArch64::X3, AArch64::X4, AArch64::X5,
2665                                           AArch64::X6, AArch64::X7 };
2666   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2667   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2668
2669   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2670   int GPRIdx = 0;
2671   if (GPRSaveSize != 0) {
2672     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2673
2674     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2675
2676     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2677       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2678       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2679       SDValue Store = DAG.getStore(
2680           Val.getValue(1), DL, Val, FIN,
2681           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2682       MemOps.push_back(Store);
2683       FIN =
2684           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2685     }
2686   }
2687   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2688   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2689
2690   if (Subtarget->hasFPARMv8()) {
2691     static const MCPhysReg FPRArgRegs[] = {
2692         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2693         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2694     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2695     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2696
2697     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2698     int FPRIdx = 0;
2699     if (FPRSaveSize != 0) {
2700       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2701
2702       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2703
2704       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2705         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2706         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2707
2708         SDValue Store = DAG.getStore(
2709             Val.getValue(1), DL, Val, FIN,
2710             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2711         MemOps.push_back(Store);
2712         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2713                           DAG.getConstant(16, DL, PtrVT));
2714       }
2715     }
2716     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2717     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2718   }
2719
2720   if (!MemOps.empty()) {
2721     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2722   }
2723 }
2724
2725 /// LowerCallResult - Lower the result values of a call into the
2726 /// appropriate copies out of appropriate physical registers.
2727 SDValue AArch64TargetLowering::LowerCallResult(
2728     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2729     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2730     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2731     SDValue ThisVal) const {
2732   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2733                           ? RetCC_AArch64_WebKit_JS
2734                           : RetCC_AArch64_AAPCS;
2735   // Assign locations to each value returned by this call.
2736   SmallVector<CCValAssign, 16> RVLocs;
2737   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2738                  *DAG.getContext());
2739   CCInfo.AnalyzeCallResult(Ins, RetCC);
2740
2741   // Copy all of the result registers out of their specified physreg.
2742   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2743     CCValAssign VA = RVLocs[i];
2744
2745     // Pass 'this' value directly from the argument to return value, to avoid
2746     // reg unit interference
2747     if (i == 0 && isThisReturn) {
2748       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2749              "unexpected return calling convention register assignment");
2750       InVals.push_back(ThisVal);
2751       continue;
2752     }
2753
2754     SDValue Val =
2755         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2756     Chain = Val.getValue(1);
2757     InFlag = Val.getValue(2);
2758
2759     switch (VA.getLocInfo()) {
2760     default:
2761       llvm_unreachable("Unknown loc info!");
2762     case CCValAssign::Full:
2763       break;
2764     case CCValAssign::BCvt:
2765       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2766       break;
2767     }
2768
2769     InVals.push_back(Val);
2770   }
2771
2772   return Chain;
2773 }
2774
2775 /// Return true if the calling convention is one that we can guarantee TCO for.
2776 static bool canGuaranteeTCO(CallingConv::ID CC) {
2777   return CC == CallingConv::Fast;
2778 }
2779
2780 /// Return true if we might ever do TCO for calls with this calling convention.
2781 static bool mayTailCallThisCC(CallingConv::ID CC) {
2782   switch (CC) {
2783   case CallingConv::C:
2784   case CallingConv::PreserveMost:
2785   case CallingConv::Swift:
2786     return true;
2787   default:
2788     return canGuaranteeTCO(CC);
2789   }
2790 }
2791
2792 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2793     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2794     const SmallVectorImpl<ISD::OutputArg> &Outs,
2795     const SmallVectorImpl<SDValue> &OutVals,
2796     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2797   if (!mayTailCallThisCC(CalleeCC))
2798     return false;
2799
2800   MachineFunction &MF = DAG.getMachineFunction();
2801   const Function *CallerF = MF.getFunction();
2802   CallingConv::ID CallerCC = CallerF->getCallingConv();
2803   bool CCMatch = CallerCC == CalleeCC;
2804
2805   // Byval parameters hand the function a pointer directly into the stack area
2806   // we want to reuse during a tail call. Working around this *is* possible (see
2807   // X86) but less efficient and uglier in LowerCall.
2808   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809                                     e = CallerF->arg_end();
2810        i != e; ++i)
2811     if (i->hasByValAttr())
2812       return false;
2813
2814   if (getTargetMachine().Options.GuaranteedTailCallOpt)
2815     return canGuaranteeTCO(CalleeCC) && CCMatch;
2816
2817   // Externally-defined functions with weak linkage should not be
2818   // tail-called on AArch64 when the OS does not support dynamic
2819   // pre-emption of symbols, as the AAELF spec requires normal calls
2820   // to undefined weak functions to be replaced with a NOP or jump to the
2821   // next instruction. The behaviour of branch instructions in this
2822   // situation (as used for tail calls) is implementation-defined, so we
2823   // cannot rely on the linker replacing the tail call with a return.
2824   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2825     const GlobalValue *GV = G->getGlobal();
2826     const Triple &TT = getTargetMachine().getTargetTriple();
2827     if (GV->hasExternalWeakLinkage() &&
2828         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2829       return false;
2830   }
2831
2832   // Now we search for cases where we can use a tail call without changing the
2833   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2834   // concept.
2835
2836   // I want anyone implementing a new calling convention to think long and hard
2837   // about this assert.
2838   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2839          "Unexpected variadic calling convention");
2840
2841   LLVMContext &C = *DAG.getContext();
2842   if (isVarArg && !Outs.empty()) {
2843     // At least two cases here: if caller is fastcc then we can't have any
2844     // memory arguments (we'd be expected to clean up the stack afterwards). If
2845     // caller is C then we could potentially use its argument area.
2846
2847     // FIXME: for now we take the most conservative of these in both cases:
2848     // disallow all variadic memory operands.
2849     SmallVector<CCValAssign, 16> ArgLocs;
2850     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2851
2852     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2853     for (const CCValAssign &ArgLoc : ArgLocs)
2854       if (!ArgLoc.isRegLoc())
2855         return false;
2856   }
2857
2858   // Check that the call results are passed in the same way.
2859   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2860                                   CCAssignFnForCall(CalleeCC, isVarArg),
2861                                   CCAssignFnForCall(CallerCC, isVarArg)))
2862     return false;
2863   // The callee has to preserve all registers the caller needs to preserve.
2864   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2865   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2866   if (!CCMatch) {
2867     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2868     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2869       return false;
2870   }
2871
2872   // Nothing more to check if the callee is taking no arguments
2873   if (Outs.empty())
2874     return true;
2875
2876   SmallVector<CCValAssign, 16> ArgLocs;
2877   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2878
2879   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2880
2881   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2882
2883   // If the stack arguments for this call do not fit into our own save area then
2884   // the call cannot be made tail.
2885   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2886     return false;
2887
2888   const MachineRegisterInfo &MRI = MF.getRegInfo();
2889   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2890     return false;
2891
2892   return true;
2893 }
2894
2895 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2896                                                    SelectionDAG &DAG,
2897                                                    MachineFrameInfo &MFI,
2898                                                    int ClobberedFI) const {
2899   SmallVector<SDValue, 8> ArgChains;
2900   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2901   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2902
2903   // Include the original chain at the beginning of the list. When this is
2904   // used by target LowerCall hooks, this helps legalize find the
2905   // CALLSEQ_BEGIN node.
2906   ArgChains.push_back(Chain);
2907
2908   // Add a chain value for each stack argument corresponding
2909   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2910                             UE = DAG.getEntryNode().getNode()->use_end();
2911        U != UE; ++U)
2912     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2913       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2914         if (FI->getIndex() < 0) {
2915           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2916           int64_t InLastByte = InFirstByte;
2917           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2918
2919           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2920               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2921             ArgChains.push_back(SDValue(L, 1));
2922         }
2923
2924   // Build a tokenfactor for all the chains.
2925   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2926 }
2927
2928 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2929                                                    bool TailCallOpt) const {
2930   return CallCC == CallingConv::Fast && TailCallOpt;
2931 }
2932
2933 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2934 /// and add input and output parameter nodes.
2935 SDValue
2936 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2937                                  SmallVectorImpl<SDValue> &InVals) const {
2938   SelectionDAG &DAG = CLI.DAG;
2939   SDLoc &DL = CLI.DL;
2940   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2941   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2942   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2943   SDValue Chain = CLI.Chain;
2944   SDValue Callee = CLI.Callee;
2945   bool &IsTailCall = CLI.IsTailCall;
2946   CallingConv::ID CallConv = CLI.CallConv;
2947   bool IsVarArg = CLI.IsVarArg;
2948
2949   MachineFunction &MF = DAG.getMachineFunction();
2950   bool IsThisReturn = false;
2951
2952   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2953   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2954   bool IsSibCall = false;
2955
2956   if (IsTailCall) {
2957     // Check if it's really possible to do a tail call.
2958     IsTailCall = isEligibleForTailCallOptimization(
2959         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2960     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2961       report_fatal_error("failed to perform tail call elimination on a call "
2962                          "site marked musttail");
2963
2964     // A sibling call is one where we're under the usual C ABI and not planning
2965     // to change that but can still do a tail call:
2966     if (!TailCallOpt && IsTailCall)
2967       IsSibCall = true;
2968
2969     if (IsTailCall)
2970       ++NumTailCalls;
2971   }
2972
2973   // Analyze operands of the call, assigning locations to each operand.
2974   SmallVector<CCValAssign, 16> ArgLocs;
2975   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2976                  *DAG.getContext());
2977
2978   if (IsVarArg) {
2979     // Handle fixed and variable vector arguments differently.
2980     // Variable vector arguments always go into memory.
2981     unsigned NumArgs = Outs.size();
2982
2983     for (unsigned i = 0; i != NumArgs; ++i) {
2984       MVT ArgVT = Outs[i].VT;
2985       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2986       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2987                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2988       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2989       assert(!Res && "Call operand has unhandled type");
2990       (void)Res;
2991     }
2992   } else {
2993     // At this point, Outs[].VT may already be promoted to i32. To correctly
2994     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2995     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2996     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2997     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2998     // LocVT.
2999     unsigned NumArgs = Outs.size();
3000     for (unsigned i = 0; i != NumArgs; ++i) {
3001       MVT ValVT = Outs[i].VT;
3002       // Get type of the original argument.
3003       EVT ActualVT = getValueType(DAG.getDataLayout(),
3004                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3005                                   /*AllowUnknown*/ true);
3006       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3007       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3008       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3009       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3010         ValVT = MVT::i8;
3011       else if (ActualMVT == MVT::i16)
3012         ValVT = MVT::i16;
3013
3014       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3015       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3016       assert(!Res && "Call operand has unhandled type");
3017       (void)Res;
3018     }
3019   }
3020
3021   // Get a count of how many bytes are to be pushed on the stack.
3022   unsigned NumBytes = CCInfo.getNextStackOffset();
3023
3024   if (IsSibCall) {
3025     // Since we're not changing the ABI to make this a tail call, the memory
3026     // operands are already available in the caller's incoming argument space.
3027     NumBytes = 0;
3028   }
3029
3030   // FPDiff is the byte offset of the call's argument area from the callee's.
3031   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3032   // by this amount for a tail call. In a sibling call it must be 0 because the
3033   // caller will deallocate the entire stack and the callee still expects its
3034   // arguments to begin at SP+0. Completely unused for non-tail calls.
3035   int FPDiff = 0;
3036
3037   if (IsTailCall && !IsSibCall) {
3038     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3039
3040     // Since callee will pop argument stack as a tail call, we must keep the
3041     // popped size 16-byte aligned.
3042     NumBytes = alignTo(NumBytes, 16);
3043
3044     // FPDiff will be negative if this tail call requires more space than we
3045     // would automatically have in our incoming argument space. Positive if we
3046     // can actually shrink the stack.
3047     FPDiff = NumReusableBytes - NumBytes;
3048
3049     // The stack pointer must be 16-byte aligned at all times it's used for a
3050     // memory operation, which in practice means at *all* times and in
3051     // particular across call boundaries. Therefore our own arguments started at
3052     // a 16-byte aligned SP and the delta applied for the tail call should
3053     // satisfy the same constraint.
3054     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3055   }
3056
3057   // Adjust the stack pointer for the new arguments...
3058   // These operations are automatically eliminated by the prolog/epilog pass
3059   if (!IsSibCall)
3060     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3061                                                               true),
3062                                  DL);
3063
3064   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3065                                         getPointerTy(DAG.getDataLayout()));
3066
3067   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3068   SmallVector<SDValue, 8> MemOpChains;
3069   auto PtrVT = getPointerTy(DAG.getDataLayout());
3070
3071   // Walk the register/memloc assignments, inserting copies/loads.
3072   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3073        ++i, ++realArgIdx) {
3074     CCValAssign &VA = ArgLocs[i];
3075     SDValue Arg = OutVals[realArgIdx];
3076     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3077
3078     // Promote the value if needed.
3079     switch (VA.getLocInfo()) {
3080     default:
3081       llvm_unreachable("Unknown loc info!");
3082     case CCValAssign::Full:
3083       break;
3084     case CCValAssign::SExt:
3085       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3086       break;
3087     case CCValAssign::ZExt:
3088       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3089       break;
3090     case CCValAssign::AExt:
3091       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3092         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3093         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3094         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3095       }
3096       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3097       break;
3098     case CCValAssign::BCvt:
3099       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3100       break;
3101     case CCValAssign::FPExt:
3102       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3103       break;
3104     }
3105
3106     if (VA.isRegLoc()) {
3107       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3108         assert(VA.getLocVT() == MVT::i64 &&
3109                "unexpected calling convention register assignment");
3110         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3111                "unexpected use of 'returned'");
3112         IsThisReturn = true;
3113       }
3114       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3115     } else {
3116       assert(VA.isMemLoc());
3117
3118       SDValue DstAddr;
3119       MachinePointerInfo DstInfo;
3120
3121       // FIXME: This works on big-endian for composite byvals, which are the
3122       // common case. It should also work for fundamental types too.
3123       uint32_t BEAlign = 0;
3124       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3125                                         : VA.getValVT().getSizeInBits();
3126       OpSize = (OpSize + 7) / 8;
3127       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3128           !Flags.isInConsecutiveRegs()) {
3129         if (OpSize < 8)
3130           BEAlign = 8 - OpSize;
3131       }
3132       unsigned LocMemOffset = VA.getLocMemOffset();
3133       int32_t Offset = LocMemOffset + BEAlign;
3134       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3135       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3136
3137       if (IsTailCall) {
3138         Offset = Offset + FPDiff;
3139         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3140
3141         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3142         DstInfo =
3143             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3144
3145         // Make sure any stack arguments overlapping with where we're storing
3146         // are loaded before this eventual operation. Otherwise they'll be
3147         // clobbered.
3148         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3149       } else {
3150         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3151
3152         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3153         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3154                                                LocMemOffset);
3155       }
3156
3157       if (Outs[i].Flags.isByVal()) {
3158         SDValue SizeNode =
3159             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3160         SDValue Cpy = DAG.getMemcpy(
3161             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3162             /*isVol = */ false, /*AlwaysInline = */ false,
3163             /*isTailCall = */ false,
3164             DstInfo, MachinePointerInfo());
3165
3166         MemOpChains.push_back(Cpy);
3167       } else {
3168         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3169         // promoted to a legal register type i32, we should truncate Arg back to
3170         // i1/i8/i16.
3171         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3172             VA.getValVT() == MVT::i16)
3173           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3174
3175         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3176         MemOpChains.push_back(Store);
3177       }
3178     }
3179   }
3180
3181   if (!MemOpChains.empty())
3182     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3183
3184   // Build a sequence of copy-to-reg nodes chained together with token chain
3185   // and flag operands which copy the outgoing args into the appropriate regs.
3186   SDValue InFlag;
3187   for (auto &RegToPass : RegsToPass) {
3188     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3189                              RegToPass.second, InFlag);
3190     InFlag = Chain.getValue(1);
3191   }
3192
3193   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3194   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3195   // node so that legalize doesn't hack it.
3196   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3197       Subtarget->isTargetMachO()) {
3198     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3199       const GlobalValue *GV = G->getGlobal();
3200       bool InternalLinkage = GV->hasInternalLinkage();
3201       if (InternalLinkage)
3202         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3203       else {
3204         Callee =
3205             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3206         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3207       }
3208     } else if (ExternalSymbolSDNode *S =
3209                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3210       const char *Sym = S->getSymbol();
3211       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3212       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3213     }
3214   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215     const GlobalValue *GV = G->getGlobal();
3216     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3217   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3218     const char *Sym = S->getSymbol();
3219     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3220   }
3221
3222   // We don't usually want to end the call-sequence here because we would tidy
3223   // the frame up *after* the call, however in the ABI-changing tail-call case
3224   // we've carefully laid out the parameters so that when sp is reset they'll be
3225   // in the correct location.
3226   if (IsTailCall && !IsSibCall) {
3227     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3228                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3229     InFlag = Chain.getValue(1);
3230   }
3231
3232   std::vector<SDValue> Ops;
3233   Ops.push_back(Chain);
3234   Ops.push_back(Callee);
3235
3236   if (IsTailCall) {
3237     // Each tail call may have to adjust the stack by a different amount, so
3238     // this information must travel along with the operation for eventual
3239     // consumption by emitEpilogue.
3240     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3241   }
3242
3243   // Add argument registers to the end of the list so that they are known live
3244   // into the call.
3245   for (auto &RegToPass : RegsToPass)
3246     Ops.push_back(DAG.getRegister(RegToPass.first,
3247                                   RegToPass.second.getValueType()));
3248
3249   // Add a register mask operand representing the call-preserved registers.
3250   const uint32_t *Mask;
3251   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3252   if (IsThisReturn) {
3253     // For 'this' returns, use the X0-preserving mask if applicable
3254     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3255     if (!Mask) {
3256       IsThisReturn = false;
3257       Mask = TRI->getCallPreservedMask(MF, CallConv);
3258     }
3259   } else
3260     Mask = TRI->getCallPreservedMask(MF, CallConv);
3261
3262   assert(Mask && "Missing call preserved mask for calling convention");
3263   Ops.push_back(DAG.getRegisterMask(Mask));
3264
3265   if (InFlag.getNode())
3266     Ops.push_back(InFlag);
3267
3268   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3269
3270   // If we're doing a tall call, use a TC_RETURN here rather than an
3271   // actual call instruction.
3272   if (IsTailCall) {
3273     MF.getFrameInfo().setHasTailCall();
3274     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3275   }
3276
3277   // Returns a chain and a flag for retval copy to use.
3278   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3279   InFlag = Chain.getValue(1);
3280
3281   uint64_t CalleePopBytes =
3282       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3283
3284   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3285                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3286                              InFlag, DL);
3287   if (!Ins.empty())
3288     InFlag = Chain.getValue(1);
3289
3290   // Handle result values, copying them out of physregs into vregs that we
3291   // return.
3292   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3293                          InVals, IsThisReturn,
3294                          IsThisReturn ? OutVals[0] : SDValue());
3295 }
3296
3297 bool AArch64TargetLowering::CanLowerReturn(
3298     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3299     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3300   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3301                           ? RetCC_AArch64_WebKit_JS
3302                           : RetCC_AArch64_AAPCS;
3303   SmallVector<CCValAssign, 16> RVLocs;
3304   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3305   return CCInfo.CheckReturn(Outs, RetCC);
3306 }
3307
3308 SDValue
3309 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3310                                    bool isVarArg,
3311                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3312                                    const SmallVectorImpl<SDValue> &OutVals,
3313                                    const SDLoc &DL, SelectionDAG &DAG) const {
3314   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3315                           ? RetCC_AArch64_WebKit_JS
3316                           : RetCC_AArch64_AAPCS;
3317   SmallVector<CCValAssign, 16> RVLocs;
3318   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3319                  *DAG.getContext());
3320   CCInfo.AnalyzeReturn(Outs, RetCC);
3321
3322   // Copy the result values into the output registers.
3323   SDValue Flag;
3324   SmallVector<SDValue, 4> RetOps(1, Chain);
3325   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3326        ++i, ++realRVLocIdx) {
3327     CCValAssign &VA = RVLocs[i];
3328     assert(VA.isRegLoc() && "Can only return in registers!");
3329     SDValue Arg = OutVals[realRVLocIdx];
3330
3331     switch (VA.getLocInfo()) {
3332     default:
3333       llvm_unreachable("Unknown loc info!");
3334     case CCValAssign::Full:
3335       if (Outs[i].ArgVT == MVT::i1) {
3336         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3337         // value. This is strictly redundant on Darwin (which uses "zeroext
3338         // i1"), but will be optimised out before ISel.
3339         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3340         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3341       }
3342       break;
3343     case CCValAssign::BCvt:
3344       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3345       break;
3346     }
3347
3348     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3349     Flag = Chain.getValue(1);
3350     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3351   }
3352   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3353   const MCPhysReg *I =
3354       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3355   if (I) {
3356     for (; *I; ++I) {
3357       if (AArch64::GPR64RegClass.contains(*I))
3358         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3359       else if (AArch64::FPR64RegClass.contains(*I))
3360         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3361       else
3362         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3363     }
3364   }
3365
3366   RetOps[0] = Chain; // Update chain.
3367
3368   // Add the flag if we have it.
3369   if (Flag.getNode())
3370     RetOps.push_back(Flag);
3371
3372   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3373 }
3374
3375 //===----------------------------------------------------------------------===//
3376 //  Other Lowering Code
3377 //===----------------------------------------------------------------------===//
3378
3379 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3380                                                   SelectionDAG &DAG) const {
3381   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3382   SDLoc DL(Op);
3383   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3384   const GlobalValue *GV = GN->getGlobal();
3385   unsigned char OpFlags =
3386       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3387
3388   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3389          "unexpected offset in global node");
3390
3391   // This also catched the large code model case for Darwin.
3392   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3393     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3394     // FIXME: Once remat is capable of dealing with instructions with register
3395     // operands, expand this into two nodes instead of using a wrapper node.
3396     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3397   }
3398
3399   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3400     const unsigned char MO_NC = AArch64II::MO_NC;
3401     return DAG.getNode(
3402         AArch64ISD::WrapperLarge, DL, PtrVT,
3403         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3404         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3405         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3406         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3407   } else {
3408     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3409     // the only correct model on Darwin.
3410     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3411                                             OpFlags | AArch64II::MO_PAGE);
3412     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3413     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3414
3415     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3416     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3417   }
3418 }
3419
3420 /// \brief Convert a TLS address reference into the correct sequence of loads
3421 /// and calls to compute the variable's address (for Darwin, currently) and
3422 /// return an SDValue containing the final node.
3423
3424 /// Darwin only has one TLS scheme which must be capable of dealing with the
3425 /// fully general situation, in the worst case. This means:
3426 ///     + "extern __thread" declaration.
3427 ///     + Defined in a possibly unknown dynamic library.
3428 ///
3429 /// The general system is that each __thread variable has a [3 x i64] descriptor
3430 /// which contains information used by the runtime to calculate the address. The
3431 /// only part of this the compiler needs to know about is the first xword, which
3432 /// contains a function pointer that must be called with the address of the
3433 /// entire descriptor in "x0".
3434 ///
3435 /// Since this descriptor may be in a different unit, in general even the
3436 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3437 /// is:
3438 ///     adrp x0, _var@TLVPPAGE
3439 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3440 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3441 ///                                      ; the function pointer
3442 ///     blr x1                           ; Uses descriptor address in x0
3443 ///     ; Address of _var is now in x0.
3444 ///
3445 /// If the address of _var's descriptor *is* known to the linker, then it can
3446 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3447 /// a slight efficiency gain.
3448 SDValue
3449 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3450                                                    SelectionDAG &DAG) const {
3451   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3452
3453   SDLoc DL(Op);
3454   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3455   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3456
3457   SDValue TLVPAddr =
3458       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3459   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3460
3461   // The first entry in the descriptor is a function pointer that we must call
3462   // to obtain the address of the variable.
3463   SDValue Chain = DAG.getEntryNode();
3464   SDValue FuncTLVGet = DAG.getLoad(
3465       MVT::i64, DL, Chain, DescAddr,
3466       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3467       /* Alignment = */ 8,
3468       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3469           MachineMemOperand::MODereferenceable);
3470   Chain = FuncTLVGet.getValue(1);
3471
3472   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3473   MFI.setAdjustsStack(true);
3474
3475   // TLS calls preserve all registers except those that absolutely must be
3476   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3477   // silly).
3478   const uint32_t *Mask =
3479       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3480
3481   // Finally, we can make the call. This is just a degenerate version of a
3482   // normal AArch64 call node: x0 takes the address of the descriptor, and
3483   // returns the address of the variable in this thread.
3484   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3485   Chain =
3486       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3487                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3488                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3489   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3490 }
3491
3492 /// When accessing thread-local variables under either the general-dynamic or
3493 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3494 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3495 /// is a function pointer to carry out the resolution.
3496 ///
3497 /// The sequence is:
3498 ///    adrp  x0, :tlsdesc:var
3499 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3500 ///    add   x0, x0, #:tlsdesc_lo12:var
3501 ///    .tlsdesccall var
3502 ///    blr   x1
3503 ///    (TPIDR_EL0 offset now in x0)
3504 ///
3505 ///  The above sequence must be produced unscheduled, to enable the linker to
3506 ///  optimize/relax this sequence.
3507 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3508 ///  above sequence, and expanded really late in the compilation flow, to ensure
3509 ///  the sequence is produced as per above.
3510 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3511                                                       const SDLoc &DL,
3512                                                       SelectionDAG &DAG) const {
3513   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3514
3515   SDValue Chain = DAG.getEntryNode();
3516   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3517
3518   Chain =
3519       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3520   SDValue Glue = Chain.getValue(1);
3521
3522   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3523 }
3524
3525 SDValue
3526 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3527                                                 SelectionDAG &DAG) const {
3528   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3529   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3530          "ELF TLS only supported in small memory model");
3531   // Different choices can be made for the maximum size of the TLS area for a
3532   // module. For the small address model, the default TLS size is 16MiB and the
3533   // maximum TLS size is 4GiB.
3534   // FIXME: add -mtls-size command line option and make it control the 16MiB
3535   // vs. 4GiB code sequence generation.
3536   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3537
3538   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3539
3540   if (DAG.getTarget().Options.EmulatedTLS)
3541     return LowerToTLSEmulatedModel(GA, DAG);
3542
3543   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3544     if (Model == TLSModel::LocalDynamic)
3545       Model = TLSModel::GeneralDynamic;
3546   }
3547
3548   SDValue TPOff;
3549   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3550   SDLoc DL(Op);
3551   const GlobalValue *GV = GA->getGlobal();
3552
3553   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3554
3555   if (Model == TLSModel::LocalExec) {
3556     SDValue HiVar = DAG.getTargetGlobalAddress(
3557         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3558     SDValue LoVar = DAG.getTargetGlobalAddress(
3559         GV, DL, PtrVT, 0,
3560         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3561
3562     SDValue TPWithOff_lo =
3563         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3564                                    HiVar,
3565                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3566                 0);
3567     SDValue TPWithOff =
3568         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3569                                    LoVar,
3570                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3571                 0);
3572     return TPWithOff;
3573   } else if (Model == TLSModel::InitialExec) {
3574     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3575     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3576   } else if (Model == TLSModel::LocalDynamic) {
3577     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3578     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3579     // the beginning of the module's TLS region, followed by a DTPREL offset
3580     // calculation.
3581
3582     // These accesses will need deduplicating if there's more than one.
3583     AArch64FunctionInfo *MFI =
3584         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3585     MFI->incNumLocalDynamicTLSAccesses();
3586
3587     // The call needs a relocation too for linker relaxation. It doesn't make
3588     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3589     // the address.
3590     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3591                                                   AArch64II::MO_TLS);
3592
3593     // Now we can calculate the offset from TPIDR_EL0 to this module's
3594     // thread-local area.
3595     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3596
3597     // Now use :dtprel_whatever: operations to calculate this variable's offset
3598     // in its thread-storage area.
3599     SDValue HiVar = DAG.getTargetGlobalAddress(
3600         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3601     SDValue LoVar = DAG.getTargetGlobalAddress(
3602         GV, DL, MVT::i64, 0,
3603         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3604
3605     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3606                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3607                     0);
3608     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3609                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3610                     0);
3611   } else if (Model == TLSModel::GeneralDynamic) {
3612     // The call needs a relocation too for linker relaxation. It doesn't make
3613     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3614     // the address.
3615     SDValue SymAddr =
3616         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3617
3618     // Finally we can make a call to calculate the offset from tpidr_el0.
3619     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3620   } else
3621     llvm_unreachable("Unsupported ELF TLS access model");
3622
3623   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3624 }
3625
3626 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3627                                                      SelectionDAG &DAG) const {
3628   if (Subtarget->isTargetDarwin())
3629     return LowerDarwinGlobalTLSAddress(Op, DAG);
3630   else if (Subtarget->isTargetELF())
3631     return LowerELFGlobalTLSAddress(Op, DAG);
3632
3633   llvm_unreachable("Unexpected platform trying to use TLS");
3634 }
3635 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3636   SDValue Chain = Op.getOperand(0);
3637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3638   SDValue LHS = Op.getOperand(2);
3639   SDValue RHS = Op.getOperand(3);
3640   SDValue Dest = Op.getOperand(4);
3641   SDLoc dl(Op);
3642
3643   // Handle f128 first, since lowering it will result in comparing the return
3644   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3645   // is expecting to deal with.
3646   if (LHS.getValueType() == MVT::f128) {
3647     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3648
3649     // If softenSetCCOperands returned a scalar, we need to compare the result
3650     // against zero to select between true and false values.
3651     if (!RHS.getNode()) {
3652       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3653       CC = ISD::SETNE;
3654     }
3655   }
3656
3657   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3658   // instruction.
3659   unsigned Opc = LHS.getOpcode();
3660   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3661       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3662        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3663     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3664            "Unexpected condition code.");
3665     // Only lower legal XALUO ops.
3666     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3667       return SDValue();
3668
3669     // The actual operation with overflow check.
3670     AArch64CC::CondCode OFCC;
3671     SDValue Value, Overflow;
3672     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3673
3674     if (CC == ISD::SETNE)
3675       OFCC = getInvertedCondCode(OFCC);
3676     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3677
3678     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3679                        Overflow);
3680   }
3681
3682   if (LHS.getValueType().isInteger()) {
3683     assert((LHS.getValueType() == RHS.getValueType()) &&
3684            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3685
3686     // If the RHS of the comparison is zero, we can potentially fold this
3687     // to a specialized branch.
3688     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3689     if (RHSC && RHSC->getZExtValue() == 0) {
3690       if (CC == ISD::SETEQ) {
3691         // See if we can use a TBZ to fold in an AND as well.
3692         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3693         // out of bounds, a late MI-layer pass rewrites branches.
3694         // 403.gcc is an example that hits this case.
3695         if (LHS.getOpcode() == ISD::AND &&
3696             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3697             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3698           SDValue Test = LHS.getOperand(0);
3699           uint64_t Mask = LHS.getConstantOperandVal(1);
3700           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3701                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3702                              Dest);
3703         }
3704
3705         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3706       } else if (CC == ISD::SETNE) {
3707         // See if we can use a TBZ to fold in an AND as well.
3708         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3709         // out of bounds, a late MI-layer pass rewrites branches.
3710         // 403.gcc is an example that hits this case.
3711         if (LHS.getOpcode() == ISD::AND &&
3712             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3713             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3714           SDValue Test = LHS.getOperand(0);
3715           uint64_t Mask = LHS.getConstantOperandVal(1);
3716           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3717                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3718                              Dest);
3719         }
3720
3721         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3722       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3723         // Don't combine AND since emitComparison converts the AND to an ANDS
3724         // (a.k.a. TST) and the test in the test bit and branch instruction
3725         // becomes redundant.  This would also increase register pressure.
3726         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3727         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3728                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3729       }
3730     }
3731     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3732         LHS.getOpcode() != ISD::AND) {
3733       // Don't combine AND since emitComparison converts the AND to an ANDS
3734       // (a.k.a. TST) and the test in the test bit and branch instruction
3735       // becomes redundant.  This would also increase register pressure.
3736       uint64_t Mask = LHS.getValueSizeInBits() - 1;
3737       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3738                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3739     }
3740
3741     SDValue CCVal;
3742     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3743     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3744                        Cmp);
3745   }
3746
3747   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3748
3749   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3750   // clean.  Some of them require two branches to implement.
3751   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3752   AArch64CC::CondCode CC1, CC2;
3753   changeFPCCToAArch64CC(CC, CC1, CC2);
3754   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3755   SDValue BR1 =
3756       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3757   if (CC2 != AArch64CC::AL) {
3758     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3759     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3760                        Cmp);
3761   }
3762
3763   return BR1;
3764 }
3765
3766 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3767                                               SelectionDAG &DAG) const {
3768   EVT VT = Op.getValueType();
3769   SDLoc DL(Op);
3770
3771   SDValue In1 = Op.getOperand(0);
3772   SDValue In2 = Op.getOperand(1);
3773   EVT SrcVT = In2.getValueType();
3774
3775   if (SrcVT.bitsLT(VT))
3776     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3777   else if (SrcVT.bitsGT(VT))
3778     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3779
3780   EVT VecVT;
3781   EVT EltVT;
3782   uint64_t EltMask;
3783   SDValue VecVal1, VecVal2;
3784   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3785     EltVT = MVT::i32;
3786     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3787     EltMask = 0x80000000ULL;
3788
3789     if (!VT.isVector()) {
3790       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3791                                           DAG.getUNDEF(VecVT), In1);
3792       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3793                                           DAG.getUNDEF(VecVT), In2);
3794     } else {
3795       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3796       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3797     }
3798   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3799     EltVT = MVT::i64;
3800     VecVT = MVT::v2i64;
3801
3802     // We want to materialize a mask with the high bit set, but the AdvSIMD
3803     // immediate moves cannot materialize that in a single instruction for
3804     // 64-bit elements. Instead, materialize zero and then negate it.
3805     EltMask = 0;
3806
3807     if (!VT.isVector()) {
3808       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3809                                           DAG.getUNDEF(VecVT), In1);
3810       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3811                                           DAG.getUNDEF(VecVT), In2);
3812     } else {
3813       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3814       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3815     }
3816   } else {
3817     llvm_unreachable("Invalid type for copysign!");
3818   }
3819
3820   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3821
3822   // If we couldn't materialize the mask above, then the mask vector will be
3823   // the zero vector, and we need to negate it here.
3824   if (VT == MVT::f64 || VT == MVT::v2f64) {
3825     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3826     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3827     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3828   }
3829
3830   SDValue Sel =
3831       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3832
3833   if (VT == MVT::f32)
3834     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3835   else if (VT == MVT::f64)
3836     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3837   else
3838     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3839 }
3840
3841 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3842   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3843           Attribute::NoImplicitFloat))
3844     return SDValue();
3845
3846   if (!Subtarget->hasNEON())
3847     return SDValue();
3848
3849   // While there is no integer popcount instruction, it can
3850   // be more efficiently lowered to the following sequence that uses
3851   // AdvSIMD registers/instructions as long as the copies to/from
3852   // the AdvSIMD registers are cheap.
3853   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3854   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3855   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3856   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3857   SDValue Val = Op.getOperand(0);
3858   SDLoc DL(Op);
3859   EVT VT = Op.getValueType();
3860
3861   if (VT == MVT::i32)
3862     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3863   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3864
3865   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3866   SDValue UaddLV = DAG.getNode(
3867       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3868       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3869
3870   if (VT == MVT::i64)
3871     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3872   return UaddLV;
3873 }
3874
3875 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3876
3877   if (Op.getValueType().isVector())
3878     return LowerVSETCC(Op, DAG);
3879
3880   SDValue LHS = Op.getOperand(0);
3881   SDValue RHS = Op.getOperand(1);
3882   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3883   SDLoc dl(Op);
3884
3885   // We chose ZeroOrOneBooleanContents, so use zero and one.
3886   EVT VT = Op.getValueType();
3887   SDValue TVal = DAG.getConstant(1, dl, VT);
3888   SDValue FVal = DAG.getConstant(0, dl, VT);
3889
3890   // Handle f128 first, since one possible outcome is a normal integer
3891   // comparison which gets picked up by the next if statement.
3892   if (LHS.getValueType() == MVT::f128) {
3893     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3894
3895     // If softenSetCCOperands returned a scalar, use it.
3896     if (!RHS.getNode()) {
3897       assert(LHS.getValueType() == Op.getValueType() &&
3898              "Unexpected setcc expansion!");
3899       return LHS;
3900     }
3901   }
3902
3903   if (LHS.getValueType().isInteger()) {
3904     SDValue CCVal;
3905     SDValue Cmp =
3906         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3907
3908     // Note that we inverted the condition above, so we reverse the order of
3909     // the true and false operands here.  This will allow the setcc to be
3910     // matched to a single CSINC instruction.
3911     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3912   }
3913
3914   // Now we know we're dealing with FP values.
3915   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3916
3917   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3918   // and do the comparison.
3919   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3920
3921   AArch64CC::CondCode CC1, CC2;
3922   changeFPCCToAArch64CC(CC, CC1, CC2);
3923   if (CC2 == AArch64CC::AL) {
3924     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3925     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3926
3927     // Note that we inverted the condition above, so we reverse the order of
3928     // the true and false operands here.  This will allow the setcc to be
3929     // matched to a single CSINC instruction.
3930     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3931   } else {
3932     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3933     // totally clean.  Some of them require two CSELs to implement.  As is in
3934     // this case, we emit the first CSEL and then emit a second using the output
3935     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3936
3937     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3938     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3939     SDValue CS1 =
3940         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3941
3942     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3943     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3944   }
3945 }
3946
3947 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3948                                               SDValue RHS, SDValue TVal,
3949                                               SDValue FVal, const SDLoc &dl,
3950                                               SelectionDAG &DAG) const {
3951   // Handle f128 first, because it will result in a comparison of some RTLIB
3952   // call result against zero.
3953   if (LHS.getValueType() == MVT::f128) {
3954     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3955
3956     // If softenSetCCOperands returned a scalar, we need to compare the result
3957     // against zero to select between true and false values.
3958     if (!RHS.getNode()) {
3959       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3960       CC = ISD::SETNE;
3961     }
3962   }
3963
3964   // Also handle f16, for which we need to do a f32 comparison.
3965   if (LHS.getValueType() == MVT::f16) {
3966     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3967     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3968   }
3969
3970   // Next, handle integers.
3971   if (LHS.getValueType().isInteger()) {
3972     assert((LHS.getValueType() == RHS.getValueType()) &&
3973            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3974
3975     unsigned Opcode = AArch64ISD::CSEL;
3976
3977     // If both the TVal and the FVal are constants, see if we can swap them in
3978     // order to for a CSINV or CSINC out of them.
3979     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3980     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3981
3982     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3983       std::swap(TVal, FVal);
3984       std::swap(CTVal, CFVal);
3985       CC = ISD::getSetCCInverse(CC, true);
3986     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3987       std::swap(TVal, FVal);
3988       std::swap(CTVal, CFVal);
3989       CC = ISD::getSetCCInverse(CC, true);
3990     } else if (TVal.getOpcode() == ISD::XOR) {
3991       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3992       // with a CSINV rather than a CSEL.
3993       if (isAllOnesConstant(TVal.getOperand(1))) {
3994         std::swap(TVal, FVal);
3995         std::swap(CTVal, CFVal);
3996         CC = ISD::getSetCCInverse(CC, true);
3997       }
3998     } else if (TVal.getOpcode() == ISD::SUB) {
3999       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4000       // that we can match with a CSNEG rather than a CSEL.
4001       if (isNullConstant(TVal.getOperand(0))) {
4002         std::swap(TVal, FVal);
4003         std::swap(CTVal, CFVal);
4004         CC = ISD::getSetCCInverse(CC, true);
4005       }
4006     } else if (CTVal && CFVal) {
4007       const int64_t TrueVal = CTVal->getSExtValue();
4008       const int64_t FalseVal = CFVal->getSExtValue();
4009       bool Swap = false;
4010
4011       // If both TVal and FVal are constants, see if FVal is the
4012       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4013       // instead of a CSEL in that case.
4014       if (TrueVal == ~FalseVal) {
4015         Opcode = AArch64ISD::CSINV;
4016       } else if (TrueVal == -FalseVal) {
4017         Opcode = AArch64ISD::CSNEG;
4018       } else if (TVal.getValueType() == MVT::i32) {
4019         // If our operands are only 32-bit wide, make sure we use 32-bit
4020         // arithmetic for the check whether we can use CSINC. This ensures that
4021         // the addition in the check will wrap around properly in case there is
4022         // an overflow (which would not be the case if we do the check with
4023         // 64-bit arithmetic).
4024         const uint32_t TrueVal32 = CTVal->getZExtValue();
4025         const uint32_t FalseVal32 = CFVal->getZExtValue();
4026
4027         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4028           Opcode = AArch64ISD::CSINC;
4029
4030           if (TrueVal32 > FalseVal32) {
4031             Swap = true;
4032           }
4033         }
4034         // 64-bit check whether we can use CSINC.
4035       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4036         Opcode = AArch64ISD::CSINC;
4037
4038         if (TrueVal > FalseVal) {
4039           Swap = true;
4040         }
4041       }
4042
4043       // Swap TVal and FVal if necessary.
4044       if (Swap) {
4045         std::swap(TVal, FVal);
4046         std::swap(CTVal, CFVal);
4047         CC = ISD::getSetCCInverse(CC, true);
4048       }
4049
4050       if (Opcode != AArch64ISD::CSEL) {
4051         // Drop FVal since we can get its value by simply inverting/negating
4052         // TVal.
4053         FVal = TVal;
4054       }
4055     }
4056
4057     // Avoid materializing a constant when possible by reusing a known value in
4058     // a register.  However, don't perform this optimization if the known value
4059     // is one, zero or negative one in the case of a CSEL.  We can always
4060     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4061     // FVal, respectively.
4062     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4063     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4064         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4065       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4066       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4067       // "a != C ? x : a" to avoid materializing C.
4068       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4069         TVal = LHS;
4070       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4071         FVal = LHS;
4072     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4073       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4074       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4075       // avoid materializing C.
4076       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4077       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4078         Opcode = AArch64ISD::CSINV;
4079         TVal = LHS;
4080         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4081       }
4082     }
4083
4084     SDValue CCVal;
4085     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4086
4087     EVT VT = TVal.getValueType();
4088     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4089   }
4090
4091   // Now we know we're dealing with FP values.
4092   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4093   assert(LHS.getValueType() == RHS.getValueType());
4094   EVT VT = TVal.getValueType();
4095   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4096
4097   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4098   // clean.  Some of them require two CSELs to implement.
4099   AArch64CC::CondCode CC1, CC2;
4100   changeFPCCToAArch64CC(CC, CC1, CC2);
4101
4102   if (DAG.getTarget().Options.UnsafeFPMath) {
4103     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4104     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4105     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4106     if (RHSVal && RHSVal->isZero()) {
4107       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4108       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4109
4110       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4111           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4112         TVal = LHS;
4113       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4114                CFVal && CFVal->isZero() &&
4115                FVal.getValueType() == LHS.getValueType())
4116         FVal = LHS;
4117     }
4118   }
4119
4120   // Emit first, and possibly only, CSEL.
4121   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4122   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4123
4124   // If we need a second CSEL, emit it, using the output of the first as the
4125   // RHS.  We're effectively OR'ing the two CC's together.
4126   if (CC2 != AArch64CC::AL) {
4127     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4128     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4129   }
4130
4131   // Otherwise, return the output of the first CSEL.
4132   return CS1;
4133 }
4134
4135 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4136                                               SelectionDAG &DAG) const {
4137   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4138   SDValue LHS = Op.getOperand(0);
4139   SDValue RHS = Op.getOperand(1);
4140   SDValue TVal = Op.getOperand(2);
4141   SDValue FVal = Op.getOperand(3);
4142   SDLoc DL(Op);
4143   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4144 }
4145
4146 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4147                                            SelectionDAG &DAG) const {
4148   SDValue CCVal = Op->getOperand(0);
4149   SDValue TVal = Op->getOperand(1);
4150   SDValue FVal = Op->getOperand(2);
4151   SDLoc DL(Op);
4152
4153   unsigned Opc = CCVal.getOpcode();
4154   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4155   // instruction.
4156   if (CCVal.getResNo() == 1 &&
4157       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4158        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4159     // Only lower legal XALUO ops.
4160     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4161       return SDValue();
4162
4163     AArch64CC::CondCode OFCC;
4164     SDValue Value, Overflow;
4165     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4166     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4167
4168     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4169                        CCVal, Overflow);
4170   }
4171
4172   // Lower it the same way as we would lower a SELECT_CC node.
4173   ISD::CondCode CC;
4174   SDValue LHS, RHS;
4175   if (CCVal.getOpcode() == ISD::SETCC) {
4176     LHS = CCVal.getOperand(0);
4177     RHS = CCVal.getOperand(1);
4178     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4179   } else {
4180     LHS = CCVal;
4181     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4182     CC = ISD::SETNE;
4183   }
4184   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4185 }
4186
4187 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4188                                               SelectionDAG &DAG) const {
4189   // Jump table entries as PC relative offsets. No additional tweaking
4190   // is necessary here. Just get the address of the jump table.
4191   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4192   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4193   SDLoc DL(Op);
4194
4195   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4196       !Subtarget->isTargetMachO()) {
4197     const unsigned char MO_NC = AArch64II::MO_NC;
4198     return DAG.getNode(
4199         AArch64ISD::WrapperLarge, DL, PtrVT,
4200         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4201         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4202         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4203         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4204                                AArch64II::MO_G0 | MO_NC));
4205   }
4206
4207   SDValue Hi =
4208       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4209   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4210                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4211   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4212   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4213 }
4214
4215 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4216                                                  SelectionDAG &DAG) const {
4217   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4218   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4219   SDLoc DL(Op);
4220
4221   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4222     // Use the GOT for the large code model on iOS.
4223     if (Subtarget->isTargetMachO()) {
4224       SDValue GotAddr = DAG.getTargetConstantPool(
4225           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4226           AArch64II::MO_GOT);
4227       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4228     }
4229
4230     const unsigned char MO_NC = AArch64II::MO_NC;
4231     return DAG.getNode(
4232         AArch64ISD::WrapperLarge, DL, PtrVT,
4233         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4234                                   CP->getOffset(), AArch64II::MO_G3),
4235         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4236                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4237         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4238                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4239         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4240                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4241   } else {
4242     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4243     // ELF, the only valid one on Darwin.
4244     SDValue Hi =
4245         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4246                                   CP->getOffset(), AArch64II::MO_PAGE);
4247     SDValue Lo = DAG.getTargetConstantPool(
4248         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4249         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4250
4251     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4252     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4253   }
4254 }
4255
4256 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4257                                                SelectionDAG &DAG) const {
4258   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4259   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4260   SDLoc DL(Op);
4261   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4262       !Subtarget->isTargetMachO()) {
4263     const unsigned char MO_NC = AArch64II::MO_NC;
4264     return DAG.getNode(
4265         AArch64ISD::WrapperLarge, DL, PtrVT,
4266         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4267         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4268         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4269         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4270   } else {
4271     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4272     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4273                                                              AArch64II::MO_NC);
4274     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4275     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4276   }
4277 }
4278
4279 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4280                                                  SelectionDAG &DAG) const {
4281   AArch64FunctionInfo *FuncInfo =
4282       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4283
4284   SDLoc DL(Op);
4285   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4286                                  getPointerTy(DAG.getDataLayout()));
4287   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4288   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4289                       MachinePointerInfo(SV));
4290 }
4291
4292 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4293                                                 SelectionDAG &DAG) const {
4294   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4295   // Standard, section B.3.
4296   MachineFunction &MF = DAG.getMachineFunction();
4297   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4298   auto PtrVT = getPointerTy(DAG.getDataLayout());
4299   SDLoc DL(Op);
4300
4301   SDValue Chain = Op.getOperand(0);
4302   SDValue VAList = Op.getOperand(1);
4303   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4304   SmallVector<SDValue, 4> MemOps;
4305
4306   // void *__stack at offset 0
4307   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4308   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4309                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4310
4311   // void *__gr_top at offset 8
4312   int GPRSize = FuncInfo->getVarArgsGPRSize();
4313   if (GPRSize > 0) {
4314     SDValue GRTop, GRTopAddr;
4315
4316     GRTopAddr =
4317         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4318
4319     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4320     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4321                         DAG.getConstant(GPRSize, DL, PtrVT));
4322
4323     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4324                                   MachinePointerInfo(SV, 8),
4325                                   /* Alignment = */ 8));
4326   }
4327
4328   // void *__vr_top at offset 16
4329   int FPRSize = FuncInfo->getVarArgsFPRSize();
4330   if (FPRSize > 0) {
4331     SDValue VRTop, VRTopAddr;
4332     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4333                             DAG.getConstant(16, DL, PtrVT));
4334
4335     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4336     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4337                         DAG.getConstant(FPRSize, DL, PtrVT));
4338
4339     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4340                                   MachinePointerInfo(SV, 16),
4341                                   /* Alignment = */ 8));
4342   }
4343
4344   // int __gr_offs at offset 24
4345   SDValue GROffsAddr =
4346       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4347   MemOps.push_back(DAG.getStore(
4348       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4349       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4350
4351   // int __vr_offs at offset 28
4352   SDValue VROffsAddr =
4353       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4354   MemOps.push_back(DAG.getStore(
4355       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4356       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4357
4358   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4359 }
4360
4361 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4362                                             SelectionDAG &DAG) const {
4363   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4364                                      : LowerAAPCS_VASTART(Op, DAG);
4365 }
4366
4367 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4368                                            SelectionDAG &DAG) const {
4369   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4370   // pointer.
4371   SDLoc DL(Op);
4372   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4373   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4374   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4375
4376   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4377                        Op.getOperand(2),
4378                        DAG.getConstant(VaListSize, DL, MVT::i32),
4379                        8, false, false, false, MachinePointerInfo(DestSV),
4380                        MachinePointerInfo(SrcSV));
4381 }
4382
4383 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4384   assert(Subtarget->isTargetDarwin() &&
4385          "automatic va_arg instruction only works on Darwin");
4386
4387   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4388   EVT VT = Op.getValueType();
4389   SDLoc DL(Op);
4390   SDValue Chain = Op.getOperand(0);
4391   SDValue Addr = Op.getOperand(1);
4392   unsigned Align = Op.getConstantOperandVal(3);
4393   auto PtrVT = getPointerTy(DAG.getDataLayout());
4394
4395   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4396   Chain = VAList.getValue(1);
4397
4398   if (Align > 8) {
4399     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4400     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4401                          DAG.getConstant(Align - 1, DL, PtrVT));
4402     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4403                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4404   }
4405
4406   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4407   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4408
4409   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4410   // up to 64 bits.  At the very least, we have to increase the striding of the
4411   // vaargs list to match this, and for FP values we need to introduce
4412   // FP_ROUND nodes as well.
4413   if (VT.isInteger() && !VT.isVector())
4414     ArgSize = 8;
4415   bool NeedFPTrunc = false;
4416   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4417     ArgSize = 8;
4418     NeedFPTrunc = true;
4419   }
4420
4421   // Increment the pointer, VAList, to the next vaarg
4422   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4423                                DAG.getConstant(ArgSize, DL, PtrVT));
4424   // Store the incremented VAList to the legalized pointer
4425   SDValue APStore =
4426       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4427
4428   // Load the actual argument out of the pointer VAList
4429   if (NeedFPTrunc) {
4430     // Load the value as an f64.
4431     SDValue WideFP =
4432         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4433     // Round the value down to an f32.
4434     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4435                                    DAG.getIntPtrConstant(1, DL));
4436     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4437     // Merge the rounded value with the chain output of the load.
4438     return DAG.getMergeValues(Ops, DL);
4439   }
4440
4441   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4442 }
4443
4444 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4445                                               SelectionDAG &DAG) const {
4446   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4447   MFI.setFrameAddressIsTaken(true);
4448
4449   EVT VT = Op.getValueType();
4450   SDLoc DL(Op);
4451   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4452   SDValue FrameAddr =
4453       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4454   while (Depth--)
4455     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4456                             MachinePointerInfo());
4457   return FrameAddr;
4458 }
4459
4460 // FIXME? Maybe this could be a TableGen attribute on some registers and
4461 // this table could be generated automatically from RegInfo.
4462 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4463                                                   SelectionDAG &DAG) const {
4464   unsigned Reg = StringSwitch<unsigned>(RegName)
4465                        .Case("sp", AArch64::SP)
4466                        .Default(0);
4467   if (Reg)
4468     return Reg;
4469   report_fatal_error(Twine("Invalid register name \""
4470                               + StringRef(RegName)  + "\"."));
4471 }
4472
4473 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4474                                                SelectionDAG &DAG) const {
4475   MachineFunction &MF = DAG.getMachineFunction();
4476   MachineFrameInfo &MFI = MF.getFrameInfo();
4477   MFI.setReturnAddressIsTaken(true);
4478
4479   EVT VT = Op.getValueType();
4480   SDLoc DL(Op);
4481   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4482   if (Depth) {
4483     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4484     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4485     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4486                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4487                        MachinePointerInfo());
4488   }
4489
4490   // Return LR, which contains the return address. Mark it an implicit live-in.
4491   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4492   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4493 }
4494
4495 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4496 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4497 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4498                                                     SelectionDAG &DAG) const {
4499   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4500   EVT VT = Op.getValueType();
4501   unsigned VTBits = VT.getSizeInBits();
4502   SDLoc dl(Op);
4503   SDValue ShOpLo = Op.getOperand(0);
4504   SDValue ShOpHi = Op.getOperand(1);
4505   SDValue ShAmt = Op.getOperand(2);
4506   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4507
4508   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4509
4510   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4511                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4512   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4513
4514   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4515   // is "undef". We wanted 0, so CSEL it directly.
4516   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4517                                ISD::SETEQ, dl, DAG);
4518   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4519   HiBitsForLo =
4520       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4521                   HiBitsForLo, CCVal, Cmp);
4522
4523   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4524                                    DAG.getConstant(VTBits, dl, MVT::i64));
4525
4526   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4527   SDValue LoForNormalShift =
4528       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4529
4530   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4531                        dl, DAG);
4532   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4533   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4534   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4535                            LoForNormalShift, CCVal, Cmp);
4536
4537   // AArch64 shifts larger than the register width are wrapped rather than
4538   // clamped, so we can't just emit "hi >> x".
4539   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4540   SDValue HiForBigShift =
4541       Opc == ISD::SRA
4542           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4543                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4544           : DAG.getConstant(0, dl, VT);
4545   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4546                            HiForNormalShift, CCVal, Cmp);
4547
4548   SDValue Ops[2] = { Lo, Hi };
4549   return DAG.getMergeValues(Ops, dl);
4550 }
4551
4552
4553 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4554 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4555 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4556                                                    SelectionDAG &DAG) const {
4557   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4558   EVT VT = Op.getValueType();
4559   unsigned VTBits = VT.getSizeInBits();
4560   SDLoc dl(Op);
4561   SDValue ShOpLo = Op.getOperand(0);
4562   SDValue ShOpHi = Op.getOperand(1);
4563   SDValue ShAmt = Op.getOperand(2);
4564
4565   assert(Op.getOpcode() == ISD::SHL_PARTS);
4566   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4567                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4568   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4569
4570   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4571   // is "undef". We wanted 0, so CSEL it directly.
4572   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4573                                ISD::SETEQ, dl, DAG);
4574   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4575   LoBitsForHi =
4576       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4577                   LoBitsForHi, CCVal, Cmp);
4578
4579   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4580                                    DAG.getConstant(VTBits, dl, MVT::i64));
4581   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4582   SDValue HiForNormalShift =
4583       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4584
4585   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4586
4587   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4588                        dl, DAG);
4589   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4590   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4591                            HiForNormalShift, CCVal, Cmp);
4592
4593   // AArch64 shifts of larger than register sizes are wrapped rather than
4594   // clamped, so we can't just emit "lo << a" if a is too big.
4595   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4596   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4597   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4598                            LoForNormalShift, CCVal, Cmp);
4599
4600   SDValue Ops[2] = { Lo, Hi };
4601   return DAG.getMergeValues(Ops, dl);
4602 }
4603
4604 bool AArch64TargetLowering::isOffsetFoldingLegal(
4605     const GlobalAddressSDNode *GA) const {
4606   // The AArch64 target doesn't support folding offsets into global addresses.
4607   return false;
4608 }
4609
4610 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4611   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4612   // FIXME: We should be able to handle f128 as well with a clever lowering.
4613   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4614     return true;
4615
4616   if (VT == MVT::f64)
4617     return AArch64_AM::getFP64Imm(Imm) != -1;
4618   else if (VT == MVT::f32)
4619     return AArch64_AM::getFP32Imm(Imm) != -1;
4620   return false;
4621 }
4622
4623 //===----------------------------------------------------------------------===//
4624 //                          AArch64 Optimization Hooks
4625 //===----------------------------------------------------------------------===//
4626
4627 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4628                            SDValue Operand, SelectionDAG &DAG,
4629                            int &ExtraSteps) {
4630   EVT VT = Operand.getValueType();
4631   if (ST->hasNEON() &&
4632       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4633        VT == MVT::f32 || VT == MVT::v1f32 ||
4634        VT == MVT::v2f32 || VT == MVT::v4f32)) {
4635     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4636       // For the reciprocal estimates, convergence is quadratic, so the number
4637       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
4638       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
4639       // the result for float (23 mantissa bits) is 2 and for double (52
4640       // mantissa bits) is 3.
4641       ExtraSteps = VT == MVT::f64 ? 3 : 2;
4642
4643     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4644   }
4645
4646   return SDValue();
4647 }
4648
4649 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4650                                                SelectionDAG &DAG, int Enabled,
4651                                                int &ExtraSteps,
4652                                                bool &UseOneConst,
4653                                                bool Reciprocal) const {
4654   if (Enabled == ReciprocalEstimate::Enabled ||
4655       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4656     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4657                                        DAG, ExtraSteps)) {
4658       SDLoc DL(Operand);
4659       EVT VT = Operand.getValueType();
4660
4661       SDNodeFlags Flags;
4662       Flags.setUnsafeAlgebra(true);
4663
4664       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4665       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4666       for (int i = ExtraSteps; i > 0; --i) {
4667         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4668                                    &Flags);
4669         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4670         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4671       }
4672
4673       if (!Reciprocal) {
4674         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4675                                       VT);
4676         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4677         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4678
4679         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4680         // Correct the result if the operand is 0.0.
4681         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4682                                VT, Eq, Operand, Estimate);
4683       }
4684
4685       ExtraSteps = 0;
4686       return Estimate;
4687     }
4688
4689   return SDValue();
4690 }
4691
4692 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4693                                                 SelectionDAG &DAG, int Enabled,
4694                                                 int &ExtraSteps) const {
4695   if (Enabled == ReciprocalEstimate::Enabled)
4696     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4697                                        DAG, ExtraSteps)) {
4698       SDLoc DL(Operand);
4699       EVT VT = Operand.getValueType();
4700
4701       SDNodeFlags Flags;
4702       Flags.setUnsafeAlgebra(true);
4703
4704       // Newton reciprocal iteration: E * (2 - X * E)
4705       // AArch64 reciprocal iteration instruction: (2 - M * N)
4706       for (int i = ExtraSteps; i > 0; --i) {
4707         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4708                                    Estimate, &Flags);
4709         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4710       }
4711
4712       ExtraSteps = 0;
4713       return Estimate;
4714     }
4715
4716   return SDValue();
4717 }
4718
4719 //===----------------------------------------------------------------------===//
4720 //                          AArch64 Inline Assembly Support
4721 //===----------------------------------------------------------------------===//
4722
4723 // Table of Constraints
4724 // TODO: This is the current set of constraints supported by ARM for the
4725 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4726 //
4727 // r - A general register
4728 // w - An FP/SIMD register of some size in the range v0-v31
4729 // x - An FP/SIMD register of some size in the range v0-v15
4730 // I - Constant that can be used with an ADD instruction
4731 // J - Constant that can be used with a SUB instruction
4732 // K - Constant that can be used with a 32-bit logical instruction
4733 // L - Constant that can be used with a 64-bit logical instruction
4734 // M - Constant that can be used as a 32-bit MOV immediate
4735 // N - Constant that can be used as a 64-bit MOV immediate
4736 // Q - A memory reference with base register and no offset
4737 // S - A symbolic address
4738 // Y - Floating point constant zero
4739 // Z - Integer constant zero
4740 //
4741 //   Note that general register operands will be output using their 64-bit x
4742 // register name, whatever the size of the variable, unless the asm operand
4743 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4744 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4745 // %q modifier.
4746 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4747   // At this point, we have to lower this constraint to something else, so we
4748   // lower it to an "r" or "w". However, by doing this we will force the result
4749   // to be in register, while the X constraint is much more permissive.
4750   //
4751   // Although we are correct (we are free to emit anything, without
4752   // constraints), we might break use cases that would expect us to be more
4753   // efficient and emit something else.
4754   if (!Subtarget->hasFPARMv8())
4755     return "r";
4756
4757   if (ConstraintVT.isFloatingPoint())
4758     return "w";
4759
4760   if (ConstraintVT.isVector() &&
4761      (ConstraintVT.getSizeInBits() == 64 ||
4762       ConstraintVT.getSizeInBits() == 128))
4763     return "w";
4764
4765   return "r";
4766 }
4767
4768 /// getConstraintType - Given a constraint letter, return the type of
4769 /// constraint it is for this target.
4770 AArch64TargetLowering::ConstraintType
4771 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4772   if (Constraint.size() == 1) {
4773     switch (Constraint[0]) {
4774     default:
4775       break;
4776     case 'z':
4777       return C_Other;
4778     case 'x':
4779     case 'w':
4780       return C_RegisterClass;
4781     // An address with a single base register. Due to the way we
4782     // currently handle addresses it is the same as 'r'.
4783     case 'Q':
4784       return C_Memory;
4785     }
4786   }
4787   return TargetLowering::getConstraintType(Constraint);
4788 }
4789
4790 /// Examine constraint type and operand type and determine a weight value.
4791 /// This object must already have been set up with the operand type
4792 /// and the current alternative constraint selected.
4793 TargetLowering::ConstraintWeight
4794 AArch64TargetLowering::getSingleConstraintMatchWeight(
4795     AsmOperandInfo &info, const char *constraint) const {
4796   ConstraintWeight weight = CW_Invalid;
4797   Value *CallOperandVal = info.CallOperandVal;
4798   // If we don't have a value, we can't do a match,
4799   // but allow it at the lowest weight.
4800   if (!CallOperandVal)
4801     return CW_Default;
4802   Type *type = CallOperandVal->getType();
4803   // Look at the constraint type.
4804   switch (*constraint) {
4805   default:
4806     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4807     break;
4808   case 'x':
4809   case 'w':
4810     if (type->isFloatingPointTy() || type->isVectorTy())
4811       weight = CW_Register;
4812     break;
4813   case 'z':
4814     weight = CW_Constant;
4815     break;
4816   }
4817   return weight;
4818 }
4819
4820 std::pair<unsigned, const TargetRegisterClass *>
4821 AArch64TargetLowering::getRegForInlineAsmConstraint(
4822     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4823   if (Constraint.size() == 1) {
4824     switch (Constraint[0]) {
4825     case 'r':
4826       if (VT.getSizeInBits() == 64)
4827         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4828       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4829     case 'w':
4830       if (VT.getSizeInBits() == 16)
4831         return std::make_pair(0U, &AArch64::FPR16RegClass);
4832       if (VT.getSizeInBits() == 32)
4833         return std::make_pair(0U, &AArch64::FPR32RegClass);
4834       if (VT.getSizeInBits() == 64)
4835         return std::make_pair(0U, &AArch64::FPR64RegClass);
4836       if (VT.getSizeInBits() == 128)
4837         return std::make_pair(0U, &AArch64::FPR128RegClass);
4838       break;
4839     // The instructions that this constraint is designed for can
4840     // only take 128-bit registers so just use that regclass.
4841     case 'x':
4842       if (VT.getSizeInBits() == 128)
4843         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4844       break;
4845     }
4846   }
4847   if (StringRef("{cc}").equals_lower(Constraint))
4848     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4849
4850   // Use the default implementation in TargetLowering to convert the register
4851   // constraint into a member of a register class.
4852   std::pair<unsigned, const TargetRegisterClass *> Res;
4853   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4854
4855   // Not found as a standard register?
4856   if (!Res.second) {
4857     unsigned Size = Constraint.size();
4858     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4859         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4860       int RegNo;
4861       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4862       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4863         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4864         // By default we'll emit v0-v31 for this unless there's a modifier where
4865         // we'll emit the correct register as well.
4866         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4867           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4868           Res.second = &AArch64::FPR64RegClass;
4869         } else {
4870           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4871           Res.second = &AArch64::FPR128RegClass;
4872         }
4873       }
4874     }
4875   }
4876
4877   return Res;
4878 }
4879
4880 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4881 /// vector.  If it is invalid, don't add anything to Ops.
4882 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4883     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4884     SelectionDAG &DAG) const {
4885   SDValue Result;
4886
4887   // Currently only support length 1 constraints.
4888   if (Constraint.length() != 1)
4889     return;
4890
4891   char ConstraintLetter = Constraint[0];
4892   switch (ConstraintLetter) {
4893   default:
4894     break;
4895
4896   // This set of constraints deal with valid constants for various instructions.
4897   // Validate and return a target constant for them if we can.
4898   case 'z': {
4899     // 'z' maps to xzr or wzr so it needs an input of 0.
4900     if (!isNullConstant(Op))
4901       return;
4902
4903     if (Op.getValueType() == MVT::i64)
4904       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4905     else
4906       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4907     break;
4908   }
4909
4910   case 'I':
4911   case 'J':
4912   case 'K':
4913   case 'L':
4914   case 'M':
4915   case 'N':
4916     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4917     if (!C)
4918       return;
4919
4920     // Grab the value and do some validation.
4921     uint64_t CVal = C->getZExtValue();
4922     switch (ConstraintLetter) {
4923     // The I constraint applies only to simple ADD or SUB immediate operands:
4924     // i.e. 0 to 4095 with optional shift by 12
4925     // The J constraint applies only to ADD or SUB immediates that would be
4926     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4927     // instruction [or vice versa], in other words -1 to -4095 with optional
4928     // left shift by 12.
4929     case 'I':
4930       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4931         break;
4932       return;
4933     case 'J': {
4934       uint64_t NVal = -C->getSExtValue();
4935       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4936         CVal = C->getSExtValue();
4937         break;
4938       }
4939       return;
4940     }
4941     // The K and L constraints apply *only* to logical immediates, including
4942     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4943     // been removed and MOV should be used). So these constraints have to
4944     // distinguish between bit patterns that are valid 32-bit or 64-bit
4945     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4946     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4947     // versa.
4948     case 'K':
4949       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4950         break;
4951       return;
4952     case 'L':
4953       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4954         break;
4955       return;
4956     // The M and N constraints are a superset of K and L respectively, for use
4957     // with the MOV (immediate) alias. As well as the logical immediates they
4958     // also match 32 or 64-bit immediates that can be loaded either using a
4959     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4960     // (M) or 64-bit 0x1234000000000000 (N) etc.
4961     // As a note some of this code is liberally stolen from the asm parser.
4962     case 'M': {
4963       if (!isUInt<32>(CVal))
4964         return;
4965       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4966         break;
4967       if ((CVal & 0xFFFF) == CVal)
4968         break;
4969       if ((CVal & 0xFFFF0000ULL) == CVal)
4970         break;
4971       uint64_t NCVal = ~(uint32_t)CVal;
4972       if ((NCVal & 0xFFFFULL) == NCVal)
4973         break;
4974       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4975         break;
4976       return;
4977     }
4978     case 'N': {
4979       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4980         break;
4981       if ((CVal & 0xFFFFULL) == CVal)
4982         break;
4983       if ((CVal & 0xFFFF0000ULL) == CVal)
4984         break;
4985       if ((CVal & 0xFFFF00000000ULL) == CVal)
4986         break;
4987       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4988         break;
4989       uint64_t NCVal = ~CVal;
4990       if ((NCVal & 0xFFFFULL) == NCVal)
4991         break;
4992       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4993         break;
4994       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4995         break;
4996       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4997         break;
4998       return;
4999     }
5000     default:
5001       return;
5002     }
5003
5004     // All assembler immediates are 64-bit integers.
5005     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5006     break;
5007   }
5008
5009   if (Result.getNode()) {
5010     Ops.push_back(Result);
5011     return;
5012   }
5013
5014   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5015 }
5016
5017 //===----------------------------------------------------------------------===//
5018 //                     AArch64 Advanced SIMD Support
5019 //===----------------------------------------------------------------------===//
5020
5021 /// WidenVector - Given a value in the V64 register class, produce the
5022 /// equivalent value in the V128 register class.
5023 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5024   EVT VT = V64Reg.getValueType();
5025   unsigned NarrowSize = VT.getVectorNumElements();
5026   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5027   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5028   SDLoc DL(V64Reg);
5029
5030   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5031                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5032 }
5033
5034 /// getExtFactor - Determine the adjustment factor for the position when
5035 /// generating an "extract from vector registers" instruction.
5036 static unsigned getExtFactor(SDValue &V) {
5037   EVT EltType = V.getValueType().getVectorElementType();
5038   return EltType.getSizeInBits() / 8;
5039 }
5040
5041 /// NarrowVector - Given a value in the V128 register class, produce the
5042 /// equivalent value in the V64 register class.
5043 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5044   EVT VT = V128Reg.getValueType();
5045   unsigned WideSize = VT.getVectorNumElements();
5046   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5047   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5048   SDLoc DL(V128Reg);
5049
5050   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5051 }
5052
5053 // Gather data to see if the operation can be modelled as a
5054 // shuffle in combination with VEXTs.
5055 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5056                                                   SelectionDAG &DAG) const {
5057   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5058   SDLoc dl(Op);
5059   EVT VT = Op.getValueType();
5060   unsigned NumElts = VT.getVectorNumElements();
5061
5062   struct ShuffleSourceInfo {
5063     SDValue Vec;
5064     unsigned MinElt;
5065     unsigned MaxElt;
5066
5067     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5068     // be compatible with the shuffle we intend to construct. As a result
5069     // ShuffleVec will be some sliding window into the original Vec.
5070     SDValue ShuffleVec;
5071
5072     // Code should guarantee that element i in Vec starts at element "WindowBase
5073     // + i * WindowScale in ShuffleVec".
5074     int WindowBase;
5075     int WindowScale;
5076
5077     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5078     ShuffleSourceInfo(SDValue Vec)
5079         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5080           WindowScale(1) {}
5081   };
5082
5083   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5084   // node.
5085   SmallVector<ShuffleSourceInfo, 2> Sources;
5086   for (unsigned i = 0; i < NumElts; ++i) {
5087     SDValue V = Op.getOperand(i);
5088     if (V.isUndef())
5089       continue;
5090     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5091              !isa<ConstantSDNode>(V.getOperand(1))) {
5092       // A shuffle can only come from building a vector from various
5093       // elements of other vectors, provided their indices are constant.
5094       return SDValue();
5095     }
5096
5097     // Add this element source to the list if it's not already there.
5098     SDValue SourceVec = V.getOperand(0);
5099     auto Source = find(Sources, SourceVec);
5100     if (Source == Sources.end())
5101       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5102
5103     // Update the minimum and maximum lane number seen.
5104     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5105     Source->MinElt = std::min(Source->MinElt, EltNo);
5106     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5107   }
5108
5109   // Currently only do something sane when at most two source vectors
5110   // are involved.
5111   if (Sources.size() > 2)
5112     return SDValue();
5113
5114   // Find out the smallest element size among result and two sources, and use
5115   // it as element size to build the shuffle_vector.
5116   EVT SmallestEltTy = VT.getVectorElementType();
5117   for (auto &Source : Sources) {
5118     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5119     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5120       SmallestEltTy = SrcEltTy;
5121     }
5122   }
5123   unsigned ResMultiplier =
5124       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5125   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5126   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5127
5128   // If the source vector is too wide or too narrow, we may nevertheless be able
5129   // to construct a compatible shuffle either by concatenating it with UNDEF or
5130   // extracting a suitable range of elements.
5131   for (auto &Src : Sources) {
5132     EVT SrcVT = Src.ShuffleVec.getValueType();
5133
5134     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5135       continue;
5136
5137     // This stage of the search produces a source with the same element type as
5138     // the original, but with a total width matching the BUILD_VECTOR output.
5139     EVT EltVT = SrcVT.getVectorElementType();
5140     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5141     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5142
5143     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5144       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5145       // We can pad out the smaller vector for free, so if it's part of a
5146       // shuffle...
5147       Src.ShuffleVec =
5148           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5149                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5150       continue;
5151     }
5152
5153     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5154
5155     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5156       // Span too large for a VEXT to cope
5157       return SDValue();
5158     }
5159
5160     if (Src.MinElt >= NumSrcElts) {
5161       // The extraction can just take the second half
5162       Src.ShuffleVec =
5163           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5164                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5165       Src.WindowBase = -NumSrcElts;
5166     } else if (Src.MaxElt < NumSrcElts) {
5167       // The extraction can just take the first half
5168       Src.ShuffleVec =
5169           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5170                       DAG.getConstant(0, dl, MVT::i64));
5171     } else {
5172       // An actual VEXT is needed
5173       SDValue VEXTSrc1 =
5174           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5175                       DAG.getConstant(0, dl, MVT::i64));
5176       SDValue VEXTSrc2 =
5177           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5178                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5179       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5180
5181       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5182                                    VEXTSrc2,
5183                                    DAG.getConstant(Imm, dl, MVT::i32));
5184       Src.WindowBase = -Src.MinElt;
5185     }
5186   }
5187
5188   // Another possible incompatibility occurs from the vector element types. We
5189   // can fix this by bitcasting the source vectors to the same type we intend
5190   // for the shuffle.
5191   for (auto &Src : Sources) {
5192     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5193     if (SrcEltTy == SmallestEltTy)
5194       continue;
5195     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5196     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5197     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5198     Src.WindowBase *= Src.WindowScale;
5199   }
5200
5201   // Final sanity check before we try to actually produce a shuffle.
5202   DEBUG(
5203     for (auto Src : Sources)
5204       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5205   );
5206
5207   // The stars all align, our next step is to produce the mask for the shuffle.
5208   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5209   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5210   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5211     SDValue Entry = Op.getOperand(i);
5212     if (Entry.isUndef())
5213       continue;
5214
5215     auto Src = find(Sources, Entry.getOperand(0));
5216     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5217
5218     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5219     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5220     // segment.
5221     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5222     int BitsDefined =
5223         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5224     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5225
5226     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5227     // starting at the appropriate offset.
5228     int *LaneMask = &Mask[i * ResMultiplier];
5229
5230     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5231     ExtractBase += NumElts * (Src - Sources.begin());
5232     for (int j = 0; j < LanesDefined; ++j)
5233       LaneMask[j] = ExtractBase + j;
5234   }
5235
5236   // Final check before we try to produce nonsense...
5237   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5238     return SDValue();
5239
5240   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5241   for (unsigned i = 0; i < Sources.size(); ++i)
5242     ShuffleOps[i] = Sources[i].ShuffleVec;
5243
5244   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5245                                          ShuffleOps[1], Mask);
5246   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5247 }
5248
5249 // check if an EXT instruction can handle the shuffle mask when the
5250 // vector sources of the shuffle are the same.
5251 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5252   unsigned NumElts = VT.getVectorNumElements();
5253
5254   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5255   if (M[0] < 0)
5256     return false;
5257
5258   Imm = M[0];
5259
5260   // If this is a VEXT shuffle, the immediate value is the index of the first
5261   // element.  The other shuffle indices must be the successive elements after
5262   // the first one.
5263   unsigned ExpectedElt = Imm;
5264   for (unsigned i = 1; i < NumElts; ++i) {
5265     // Increment the expected index.  If it wraps around, just follow it
5266     // back to index zero and keep going.
5267     ++ExpectedElt;
5268     if (ExpectedElt == NumElts)
5269       ExpectedElt = 0;
5270
5271     if (M[i] < 0)
5272       continue; // ignore UNDEF indices
5273     if (ExpectedElt != static_cast<unsigned>(M[i]))
5274       return false;
5275   }
5276
5277   return true;
5278 }
5279
5280 // check if an EXT instruction can handle the shuffle mask when the
5281 // vector sources of the shuffle are different.
5282 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5283                       unsigned &Imm) {
5284   // Look for the first non-undef element.
5285   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5286
5287   // Benefit form APInt to handle overflow when calculating expected element.
5288   unsigned NumElts = VT.getVectorNumElements();
5289   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5290   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5291   // The following shuffle indices must be the successive elements after the
5292   // first real element.
5293   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5294       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5295   if (FirstWrongElt != M.end())
5296     return false;
5297
5298   // The index of an EXT is the first element if it is not UNDEF.
5299   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5300   // value of the first element.  E.g.
5301   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5302   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5303   // ExpectedElt is the last mask index plus 1.
5304   Imm = ExpectedElt.getZExtValue();
5305
5306   // There are two difference cases requiring to reverse input vectors.
5307   // For example, for vector <4 x i32> we have the following cases,
5308   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5309   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5310   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5311   // to reverse two input vectors.
5312   if (Imm < NumElts)
5313     ReverseEXT = true;
5314   else
5315     Imm -= NumElts;
5316
5317   return true;
5318 }
5319
5320 /// isREVMask - Check if a vector shuffle corresponds to a REV
5321 /// instruction with the specified blocksize.  (The order of the elements
5322 /// within each block of the vector is reversed.)
5323 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5324   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5325          "Only possible block sizes for REV are: 16, 32, 64");
5326
5327   unsigned EltSz = VT.getScalarSizeInBits();
5328   if (EltSz == 64)
5329     return false;
5330
5331   unsigned NumElts = VT.getVectorNumElements();
5332   unsigned BlockElts = M[0] + 1;
5333   // If the first shuffle index is UNDEF, be optimistic.
5334   if (M[0] < 0)
5335     BlockElts = BlockSize / EltSz;
5336
5337   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5338     return false;
5339
5340   for (unsigned i = 0; i < NumElts; ++i) {
5341     if (M[i] < 0)
5342       continue; // ignore UNDEF indices
5343     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5344       return false;
5345   }
5346
5347   return true;
5348 }
5349
5350 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5351   unsigned NumElts = VT.getVectorNumElements();
5352   WhichResult = (M[0] == 0 ? 0 : 1);
5353   unsigned Idx = WhichResult * NumElts / 2;
5354   for (unsigned i = 0; i != NumElts; i += 2) {
5355     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5356         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5357       return false;
5358     Idx += 1;
5359   }
5360
5361   return true;
5362 }
5363
5364 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5365   unsigned NumElts = VT.getVectorNumElements();
5366   WhichResult = (M[0] == 0 ? 0 : 1);
5367   for (unsigned i = 0; i != NumElts; ++i) {
5368     if (M[i] < 0)
5369       continue; // ignore UNDEF indices
5370     if ((unsigned)M[i] != 2 * i + WhichResult)
5371       return false;
5372   }
5373
5374   return true;
5375 }
5376
5377 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5378   unsigned NumElts = VT.getVectorNumElements();
5379   WhichResult = (M[0] == 0 ? 0 : 1);
5380   for (unsigned i = 0; i < NumElts; i += 2) {
5381     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5382         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5383       return false;
5384   }
5385   return true;
5386 }
5387
5388 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5389 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5390 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5391 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5392   unsigned NumElts = VT.getVectorNumElements();
5393   WhichResult = (M[0] == 0 ? 0 : 1);
5394   unsigned Idx = WhichResult * NumElts / 2;
5395   for (unsigned i = 0; i != NumElts; i += 2) {
5396     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5397         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5398       return false;
5399     Idx += 1;
5400   }
5401
5402   return true;
5403 }
5404
5405 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5406 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5407 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5408 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5409   unsigned Half = VT.getVectorNumElements() / 2;
5410   WhichResult = (M[0] == 0 ? 0 : 1);
5411   for (unsigned j = 0; j != 2; ++j) {
5412     unsigned Idx = WhichResult;
5413     for (unsigned i = 0; i != Half; ++i) {
5414       int MIdx = M[i + j * Half];
5415       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5416         return false;
5417       Idx += 2;
5418     }
5419   }
5420
5421   return true;
5422 }
5423
5424 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5425 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5426 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5427 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5428   unsigned NumElts = VT.getVectorNumElements();
5429   WhichResult = (M[0] == 0 ? 0 : 1);
5430   for (unsigned i = 0; i < NumElts; i += 2) {
5431     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5432         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5433       return false;
5434   }
5435   return true;
5436 }
5437
5438 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5439                       bool &DstIsLeft, int &Anomaly) {
5440   if (M.size() != static_cast<size_t>(NumInputElements))
5441     return false;
5442
5443   int NumLHSMatch = 0, NumRHSMatch = 0;
5444   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5445
5446   for (int i = 0; i < NumInputElements; ++i) {
5447     if (M[i] == -1) {
5448       ++NumLHSMatch;
5449       ++NumRHSMatch;
5450       continue;
5451     }
5452
5453     if (M[i] == i)
5454       ++NumLHSMatch;
5455     else
5456       LastLHSMismatch = i;
5457
5458     if (M[i] == i + NumInputElements)
5459       ++NumRHSMatch;
5460     else
5461       LastRHSMismatch = i;
5462   }
5463
5464   if (NumLHSMatch == NumInputElements - 1) {
5465     DstIsLeft = true;
5466     Anomaly = LastLHSMismatch;
5467     return true;
5468   } else if (NumRHSMatch == NumInputElements - 1) {
5469     DstIsLeft = false;
5470     Anomaly = LastRHSMismatch;
5471     return true;
5472   }
5473
5474   return false;
5475 }
5476
5477 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5478   if (VT.getSizeInBits() != 128)
5479     return false;
5480
5481   unsigned NumElts = VT.getVectorNumElements();
5482
5483   for (int I = 0, E = NumElts / 2; I != E; I++) {
5484     if (Mask[I] != I)
5485       return false;
5486   }
5487
5488   int Offset = NumElts / 2;
5489   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5490     if (Mask[I] != I + SplitLHS * Offset)
5491       return false;
5492   }
5493
5494   return true;
5495 }
5496
5497 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5498   SDLoc DL(Op);
5499   EVT VT = Op.getValueType();
5500   SDValue V0 = Op.getOperand(0);
5501   SDValue V1 = Op.getOperand(1);
5502   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5503
5504   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5505       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5506     return SDValue();
5507
5508   bool SplitV0 = V0.getValueSizeInBits() == 128;
5509
5510   if (!isConcatMask(Mask, VT, SplitV0))
5511     return SDValue();
5512
5513   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5514                                 VT.getVectorNumElements() / 2);
5515   if (SplitV0) {
5516     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5517                      DAG.getConstant(0, DL, MVT::i64));
5518   }
5519   if (V1.getValueSizeInBits() == 128) {
5520     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5521                      DAG.getConstant(0, DL, MVT::i64));
5522   }
5523   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5524 }
5525
5526 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5527 /// the specified operations to build the shuffle.
5528 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5529                                       SDValue RHS, SelectionDAG &DAG,
5530                                       const SDLoc &dl) {
5531   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5532   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5533   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5534
5535   enum {
5536     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5537     OP_VREV,
5538     OP_VDUP0,
5539     OP_VDUP1,
5540     OP_VDUP2,
5541     OP_VDUP3,
5542     OP_VEXT1,
5543     OP_VEXT2,
5544     OP_VEXT3,
5545     OP_VUZPL, // VUZP, left result
5546     OP_VUZPR, // VUZP, right result
5547     OP_VZIPL, // VZIP, left result
5548     OP_VZIPR, // VZIP, right result
5549     OP_VTRNL, // VTRN, left result
5550     OP_VTRNR  // VTRN, right result
5551   };
5552
5553   if (OpNum == OP_COPY) {
5554     if (LHSID == (1 * 9 + 2) * 9 + 3)
5555       return LHS;
5556     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5557     return RHS;
5558   }
5559
5560   SDValue OpLHS, OpRHS;
5561   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5562   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5563   EVT VT = OpLHS.getValueType();
5564
5565   switch (OpNum) {
5566   default:
5567     llvm_unreachable("Unknown shuffle opcode!");
5568   case OP_VREV:
5569     // VREV divides the vector in half and swaps within the half.
5570     if (VT.getVectorElementType() == MVT::i32 ||
5571         VT.getVectorElementType() == MVT::f32)
5572       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5573     // vrev <4 x i16> -> REV32
5574     if (VT.getVectorElementType() == MVT::i16 ||
5575         VT.getVectorElementType() == MVT::f16)
5576       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5577     // vrev <4 x i8> -> REV16
5578     assert(VT.getVectorElementType() == MVT::i8);
5579     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5580   case OP_VDUP0:
5581   case OP_VDUP1:
5582   case OP_VDUP2:
5583   case OP_VDUP3: {
5584     EVT EltTy = VT.getVectorElementType();
5585     unsigned Opcode;
5586     if (EltTy == MVT::i8)
5587       Opcode = AArch64ISD::DUPLANE8;
5588     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5589       Opcode = AArch64ISD::DUPLANE16;
5590     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5591       Opcode = AArch64ISD::DUPLANE32;
5592     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5593       Opcode = AArch64ISD::DUPLANE64;
5594     else
5595       llvm_unreachable("Invalid vector element type?");
5596
5597     if (VT.getSizeInBits() == 64)
5598       OpLHS = WidenVector(OpLHS, DAG);
5599     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5600     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5601   }
5602   case OP_VEXT1:
5603   case OP_VEXT2:
5604   case OP_VEXT3: {
5605     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5606     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5607                        DAG.getConstant(Imm, dl, MVT::i32));
5608   }
5609   case OP_VUZPL:
5610     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5611                        OpRHS);
5612   case OP_VUZPR:
5613     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5614                        OpRHS);
5615   case OP_VZIPL:
5616     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5617                        OpRHS);
5618   case OP_VZIPR:
5619     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5620                        OpRHS);
5621   case OP_VTRNL:
5622     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5623                        OpRHS);
5624   case OP_VTRNR:
5625     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5626                        OpRHS);
5627   }
5628 }
5629
5630 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5631                            SelectionDAG &DAG) {
5632   // Check to see if we can use the TBL instruction.
5633   SDValue V1 = Op.getOperand(0);
5634   SDValue V2 = Op.getOperand(1);
5635   SDLoc DL(Op);
5636
5637   EVT EltVT = Op.getValueType().getVectorElementType();
5638   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5639
5640   SmallVector<SDValue, 8> TBLMask;
5641   for (int Val : ShuffleMask) {
5642     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5643       unsigned Offset = Byte + Val * BytesPerElt;
5644       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5645     }
5646   }
5647
5648   MVT IndexVT = MVT::v8i8;
5649   unsigned IndexLen = 8;
5650   if (Op.getValueSizeInBits() == 128) {
5651     IndexVT = MVT::v16i8;
5652     IndexLen = 16;
5653   }
5654
5655   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5656   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5657
5658   SDValue Shuffle;
5659   if (V2.getNode()->isUndef()) {
5660     if (IndexLen == 8)
5661       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5662     Shuffle = DAG.getNode(
5663         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5664         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5665         DAG.getBuildVector(IndexVT, DL,
5666                            makeArrayRef(TBLMask.data(), IndexLen)));
5667   } else {
5668     if (IndexLen == 8) {
5669       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5670       Shuffle = DAG.getNode(
5671           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5672           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5673           DAG.getBuildVector(IndexVT, DL,
5674                              makeArrayRef(TBLMask.data(), IndexLen)));
5675     } else {
5676       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5677       // cannot currently represent the register constraints on the input
5678       // table registers.
5679       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5680       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5681       //                   IndexLen));
5682       Shuffle = DAG.getNode(
5683           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5684           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5685           V2Cst, DAG.getBuildVector(IndexVT, DL,
5686                                     makeArrayRef(TBLMask.data(), IndexLen)));
5687     }
5688   }
5689   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5690 }
5691
5692 static unsigned getDUPLANEOp(EVT EltType) {
5693   if (EltType == MVT::i8)
5694     return AArch64ISD::DUPLANE8;
5695   if (EltType == MVT::i16 || EltType == MVT::f16)
5696     return AArch64ISD::DUPLANE16;
5697   if (EltType == MVT::i32 || EltType == MVT::f32)
5698     return AArch64ISD::DUPLANE32;
5699   if (EltType == MVT::i64 || EltType == MVT::f64)
5700     return AArch64ISD::DUPLANE64;
5701
5702   llvm_unreachable("Invalid vector element type?");
5703 }
5704
5705 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5706                                                    SelectionDAG &DAG) const {
5707   SDLoc dl(Op);
5708   EVT VT = Op.getValueType();
5709
5710   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5711
5712   // Convert shuffles that are directly supported on NEON to target-specific
5713   // DAG nodes, instead of keeping them as shuffles and matching them again
5714   // during code selection.  This is more efficient and avoids the possibility
5715   // of inconsistencies between legalization and selection.
5716   ArrayRef<int> ShuffleMask = SVN->getMask();
5717
5718   SDValue V1 = Op.getOperand(0);
5719   SDValue V2 = Op.getOperand(1);
5720
5721   if (SVN->isSplat()) {
5722     int Lane = SVN->getSplatIndex();
5723     // If this is undef splat, generate it via "just" vdup, if possible.
5724     if (Lane == -1)
5725       Lane = 0;
5726
5727     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5728       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5729                          V1.getOperand(0));
5730     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5731     // constant. If so, we can just reference the lane's definition directly.
5732     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5733         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5734       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5735
5736     // Otherwise, duplicate from the lane of the input vector.
5737     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5738
5739     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5740     // to make a vector of the same size as this SHUFFLE. We can ignore the
5741     // extract entirely, and canonicalise the concat using WidenVector.
5742     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5743       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5744       V1 = V1.getOperand(0);
5745     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5746       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5747       Lane -= Idx * VT.getVectorNumElements() / 2;
5748       V1 = WidenVector(V1.getOperand(Idx), DAG);
5749     } else if (VT.getSizeInBits() == 64)
5750       V1 = WidenVector(V1, DAG);
5751
5752     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5753   }
5754
5755   if (isREVMask(ShuffleMask, VT, 64))
5756     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5757   if (isREVMask(ShuffleMask, VT, 32))
5758     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5759   if (isREVMask(ShuffleMask, VT, 16))
5760     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5761
5762   bool ReverseEXT = false;
5763   unsigned Imm;
5764   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5765     if (ReverseEXT)
5766       std::swap(V1, V2);
5767     Imm *= getExtFactor(V1);
5768     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5769                        DAG.getConstant(Imm, dl, MVT::i32));
5770   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5771     Imm *= getExtFactor(V1);
5772     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5773                        DAG.getConstant(Imm, dl, MVT::i32));
5774   }
5775
5776   unsigned WhichResult;
5777   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5778     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5779     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5780   }
5781   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5782     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5783     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5784   }
5785   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5786     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5787     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5788   }
5789
5790   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5791     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5792     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5793   }
5794   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5795     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5796     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5797   }
5798   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5799     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5800     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5801   }
5802
5803   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5804     return Concat;
5805
5806   bool DstIsLeft;
5807   int Anomaly;
5808   int NumInputElements = V1.getValueType().getVectorNumElements();
5809   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5810     SDValue DstVec = DstIsLeft ? V1 : V2;
5811     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5812
5813     SDValue SrcVec = V1;
5814     int SrcLane = ShuffleMask[Anomaly];
5815     if (SrcLane >= NumInputElements) {
5816       SrcVec = V2;
5817       SrcLane -= VT.getVectorNumElements();
5818     }
5819     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5820
5821     EVT ScalarVT = VT.getVectorElementType();
5822
5823     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5824       ScalarVT = MVT::i32;
5825
5826     return DAG.getNode(
5827         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5828         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5829         DstLaneV);
5830   }
5831
5832   // If the shuffle is not directly supported and it has 4 elements, use
5833   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5834   unsigned NumElts = VT.getVectorNumElements();
5835   if (NumElts == 4) {
5836     unsigned PFIndexes[4];
5837     for (unsigned i = 0; i != 4; ++i) {
5838       if (ShuffleMask[i] < 0)
5839         PFIndexes[i] = 8;
5840       else
5841         PFIndexes[i] = ShuffleMask[i];
5842     }
5843
5844     // Compute the index in the perfect shuffle table.
5845     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5846                             PFIndexes[2] * 9 + PFIndexes[3];
5847     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5848     unsigned Cost = (PFEntry >> 30);
5849
5850     if (Cost <= 4)
5851       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5852   }
5853
5854   return GenerateTBL(Op, ShuffleMask, DAG);
5855 }
5856
5857 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5858                                APInt &UndefBits) {
5859   EVT VT = BVN->getValueType(0);
5860   APInt SplatBits, SplatUndef;
5861   unsigned SplatBitSize;
5862   bool HasAnyUndefs;
5863   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5864     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5865
5866     for (unsigned i = 0; i < NumSplats; ++i) {
5867       CnstBits <<= SplatBitSize;
5868       UndefBits <<= SplatBitSize;
5869       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5870       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5871     }
5872
5873     return true;
5874   }
5875
5876   return false;
5877 }
5878
5879 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5880                                               SelectionDAG &DAG) const {
5881   BuildVectorSDNode *BVN =
5882       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5883   SDValue LHS = Op.getOperand(0);
5884   SDLoc dl(Op);
5885   EVT VT = Op.getValueType();
5886
5887   if (!BVN)
5888     return Op;
5889
5890   APInt CnstBits(VT.getSizeInBits(), 0);
5891   APInt UndefBits(VT.getSizeInBits(), 0);
5892   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5893     // We only have BIC vector immediate instruction, which is and-not.
5894     CnstBits = ~CnstBits;
5895
5896     // We make use of a little bit of goto ickiness in order to avoid having to
5897     // duplicate the immediate matching logic for the undef toggled case.
5898     bool SecondTry = false;
5899   AttemptModImm:
5900
5901     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5902       CnstBits = CnstBits.zextOrTrunc(64);
5903       uint64_t CnstVal = CnstBits.getZExtValue();
5904
5905       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5906         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5907         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5908         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5909                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5910                                   DAG.getConstant(0, dl, MVT::i32));
5911         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5912       }
5913
5914       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5915         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5916         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5917         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5918                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5919                                   DAG.getConstant(8, dl, MVT::i32));
5920         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5921       }
5922
5923       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5924         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5925         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5926         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5927                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5928                                   DAG.getConstant(16, dl, MVT::i32));
5929         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5930       }
5931
5932       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5933         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5934         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5935         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5936                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5937                                   DAG.getConstant(24, dl, MVT::i32));
5938         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5939       }
5940
5941       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5942         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5943         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5944         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5945                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5946                                   DAG.getConstant(0, dl, MVT::i32));
5947         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5948       }
5949
5950       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5951         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5952         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5953         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5954                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5955                                   DAG.getConstant(8, dl, MVT::i32));
5956         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5957       }
5958     }
5959
5960     if (SecondTry)
5961       goto FailedModImm;
5962     SecondTry = true;
5963     CnstBits = ~UndefBits;
5964     goto AttemptModImm;
5965   }
5966
5967 // We can always fall back to a non-immediate AND.
5968 FailedModImm:
5969   return Op;
5970 }
5971
5972 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5973 // consists of only the same constant int value, returned in reference arg
5974 // ConstVal
5975 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5976                                      uint64_t &ConstVal) {
5977   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5978   if (!Bvec)
5979     return false;
5980   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5981   if (!FirstElt)
5982     return false;
5983   EVT VT = Bvec->getValueType(0);
5984   unsigned NumElts = VT.getVectorNumElements();
5985   for (unsigned i = 1; i < NumElts; ++i)
5986     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5987       return false;
5988   ConstVal = FirstElt->getZExtValue();
5989   return true;
5990 }
5991
5992 static unsigned getIntrinsicID(const SDNode *N) {
5993   unsigned Opcode = N->getOpcode();
5994   switch (Opcode) {
5995   default:
5996     return Intrinsic::not_intrinsic;
5997   case ISD::INTRINSIC_WO_CHAIN: {
5998     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5999     if (IID < Intrinsic::num_intrinsics)
6000       return IID;
6001     return Intrinsic::not_intrinsic;
6002   }
6003   }
6004 }
6005
6006 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6007 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6008 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6009 // Also, logical shift right -> sri, with the same structure.
6010 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6011   EVT VT = N->getValueType(0);
6012
6013   if (!VT.isVector())
6014     return SDValue();
6015
6016   SDLoc DL(N);
6017
6018   // Is the first op an AND?
6019   const SDValue And = N->getOperand(0);
6020   if (And.getOpcode() != ISD::AND)
6021     return SDValue();
6022
6023   // Is the second op an shl or lshr?
6024   SDValue Shift = N->getOperand(1);
6025   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6026   // or AArch64ISD::VLSHR vector, #shift
6027   unsigned ShiftOpc = Shift.getOpcode();
6028   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6029     return SDValue();
6030   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6031
6032   // Is the shift amount constant?
6033   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6034   if (!C2node)
6035     return SDValue();
6036
6037   // Is the and mask vector all constant?
6038   uint64_t C1;
6039   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6040     return SDValue();
6041
6042   // Is C1 == ~C2, taking into account how much one can shift elements of a
6043   // particular size?
6044   uint64_t C2 = C2node->getZExtValue();
6045   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6046   if (C2 > ElemSizeInBits)
6047     return SDValue();
6048   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6049   if ((C1 & ElemMask) != (~C2 & ElemMask))
6050     return SDValue();
6051
6052   SDValue X = And.getOperand(0);
6053   SDValue Y = Shift.getOperand(0);
6054
6055   unsigned Intrin =
6056       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6057   SDValue ResultSLI =
6058       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6059                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6060                   Shift.getOperand(1));
6061
6062   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6063   DEBUG(N->dump(&DAG));
6064   DEBUG(dbgs() << "into: \n");
6065   DEBUG(ResultSLI->dump(&DAG));
6066
6067   ++NumShiftInserts;
6068   return ResultSLI;
6069 }
6070
6071 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6072                                              SelectionDAG &DAG) const {
6073   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6074   if (EnableAArch64SlrGeneration) {
6075     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6076       return Res;
6077   }
6078
6079   BuildVectorSDNode *BVN =
6080       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6081   SDValue LHS = Op.getOperand(1);
6082   SDLoc dl(Op);
6083   EVT VT = Op.getValueType();
6084
6085   // OR commutes, so try swapping the operands.
6086   if (!BVN) {
6087     LHS = Op.getOperand(0);
6088     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6089   }
6090   if (!BVN)
6091     return Op;
6092
6093   APInt CnstBits(VT.getSizeInBits(), 0);
6094   APInt UndefBits(VT.getSizeInBits(), 0);
6095   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6096     // We make use of a little bit of goto ickiness in order to avoid having to
6097     // duplicate the immediate matching logic for the undef toggled case.
6098     bool SecondTry = false;
6099   AttemptModImm:
6100
6101     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6102       CnstBits = CnstBits.zextOrTrunc(64);
6103       uint64_t CnstVal = CnstBits.getZExtValue();
6104
6105       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6106         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6107         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6108         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6109                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6110                                   DAG.getConstant(0, dl, MVT::i32));
6111         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6112       }
6113
6114       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6115         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6116         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6117         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6118                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6119                                   DAG.getConstant(8, dl, MVT::i32));
6120         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6121       }
6122
6123       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6124         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6125         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6126         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6127                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6128                                   DAG.getConstant(16, dl, MVT::i32));
6129         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6130       }
6131
6132       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6133         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6134         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6135         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6136                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6137                                   DAG.getConstant(24, dl, MVT::i32));
6138         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6139       }
6140
6141       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6142         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6143         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6144         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6145                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6146                                   DAG.getConstant(0, dl, MVT::i32));
6147         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6148       }
6149
6150       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6151         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6152         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6153         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6154                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6155                                   DAG.getConstant(8, dl, MVT::i32));
6156         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6157       }
6158     }
6159
6160     if (SecondTry)
6161       goto FailedModImm;
6162     SecondTry = true;
6163     CnstBits = UndefBits;
6164     goto AttemptModImm;
6165   }
6166
6167 // We can always fall back to a non-immediate OR.
6168 FailedModImm:
6169   return Op;
6170 }
6171
6172 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6173 // be truncated to fit element width.
6174 static SDValue NormalizeBuildVector(SDValue Op,
6175                                     SelectionDAG &DAG) {
6176   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6177   SDLoc dl(Op);
6178   EVT VT = Op.getValueType();
6179   EVT EltTy= VT.getVectorElementType();
6180
6181   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6182     return Op;
6183
6184   SmallVector<SDValue, 16> Ops;
6185   for (SDValue Lane : Op->ops()) {
6186     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6187       APInt LowBits(EltTy.getSizeInBits(),
6188                     CstLane->getZExtValue());
6189       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6190     }
6191     Ops.push_back(Lane);
6192   }
6193   return DAG.getBuildVector(VT, dl, Ops);
6194 }
6195
6196 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6197                                                  SelectionDAG &DAG) const {
6198   SDLoc dl(Op);
6199   EVT VT = Op.getValueType();
6200   Op = NormalizeBuildVector(Op, DAG);
6201   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6202
6203   APInt CnstBits(VT.getSizeInBits(), 0);
6204   APInt UndefBits(VT.getSizeInBits(), 0);
6205   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6206     // We make use of a little bit of goto ickiness in order to avoid having to
6207     // duplicate the immediate matching logic for the undef toggled case.
6208     bool SecondTry = false;
6209   AttemptModImm:
6210
6211     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6212       CnstBits = CnstBits.zextOrTrunc(64);
6213       uint64_t CnstVal = CnstBits.getZExtValue();
6214
6215       // Certain magic vector constants (used to express things like NOT
6216       // and NEG) are passed through unmodified.  This allows codegen patterns
6217       // for these operations to match.  Special-purpose patterns will lower
6218       // these immediates to MOVIs if it proves necessary.
6219       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6220         return Op;
6221
6222       // The many faces of MOVI...
6223       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6224         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6225         if (VT.getSizeInBits() == 128) {
6226           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6227                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6228           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6229         }
6230
6231         // Support the V64 version via subregister insertion.
6232         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6233                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6234         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6235       }
6236
6237       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6238         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6239         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6240         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6241                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6242                                   DAG.getConstant(0, dl, MVT::i32));
6243         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6244       }
6245
6246       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6247         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6248         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6249         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6250                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6251                                   DAG.getConstant(8, dl, MVT::i32));
6252         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6253       }
6254
6255       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6256         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6257         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6258         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6259                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6260                                   DAG.getConstant(16, dl, MVT::i32));
6261         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6262       }
6263
6264       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6265         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6266         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6267         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6268                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6269                                   DAG.getConstant(24, dl, MVT::i32));
6270         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6271       }
6272
6273       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6274         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6275         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6276         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6277                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6278                                   DAG.getConstant(0, dl, MVT::i32));
6279         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6280       }
6281
6282       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6283         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6284         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6285         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6286                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6287                                   DAG.getConstant(8, dl, MVT::i32));
6288         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6289       }
6290
6291       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6292         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6293         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6294         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6295                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6296                                   DAG.getConstant(264, dl, MVT::i32));
6297         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6298       }
6299
6300       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6301         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6302         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6303         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6304                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6305                                   DAG.getConstant(272, dl, MVT::i32));
6306         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6307       }
6308
6309       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6310         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6311         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6312         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6313                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6314         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6315       }
6316
6317       // The few faces of FMOV...
6318       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6319         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6320         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6321         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6322                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6323         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6324       }
6325
6326       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6327           VT.getSizeInBits() == 128) {
6328         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6329         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6330                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6331         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6332       }
6333
6334       // The many faces of MVNI...
6335       CnstVal = ~CnstVal;
6336       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6337         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6338         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6339         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6340                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6341                                   DAG.getConstant(0, dl, MVT::i32));
6342         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6343       }
6344
6345       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6346         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6347         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6348         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6349                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6350                                   DAG.getConstant(8, dl, MVT::i32));
6351         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6352       }
6353
6354       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6355         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6356         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6357         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6358                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6359                                   DAG.getConstant(16, dl, MVT::i32));
6360         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6361       }
6362
6363       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6364         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6365         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6366         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6367                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6368                                   DAG.getConstant(24, dl, MVT::i32));
6369         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6370       }
6371
6372       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6373         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6374         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6375         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6376                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6377                                   DAG.getConstant(0, dl, MVT::i32));
6378         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6379       }
6380
6381       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6382         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6383         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6384         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6385                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6386                                   DAG.getConstant(8, dl, MVT::i32));
6387         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6388       }
6389
6390       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6391         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6392         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6393         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6394                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6395                                   DAG.getConstant(264, dl, MVT::i32));
6396         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6397       }
6398
6399       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6400         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6401         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6402         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6403                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6404                                   DAG.getConstant(272, dl, MVT::i32));
6405         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6406       }
6407     }
6408
6409     if (SecondTry)
6410       goto FailedModImm;
6411     SecondTry = true;
6412     CnstBits = UndefBits;
6413     goto AttemptModImm;
6414   }
6415 FailedModImm:
6416
6417   // Scan through the operands to find some interesting properties we can
6418   // exploit:
6419   //   1) If only one value is used, we can use a DUP, or
6420   //   2) if only the low element is not undef, we can just insert that, or
6421   //   3) if only one constant value is used (w/ some non-constant lanes),
6422   //      we can splat the constant value into the whole vector then fill
6423   //      in the non-constant lanes.
6424   //   4) FIXME: If different constant values are used, but we can intelligently
6425   //             select the values we'll be overwriting for the non-constant
6426   //             lanes such that we can directly materialize the vector
6427   //             some other way (MOVI, e.g.), we can be sneaky.
6428   unsigned NumElts = VT.getVectorNumElements();
6429   bool isOnlyLowElement = true;
6430   bool usesOnlyOneValue = true;
6431   bool usesOnlyOneConstantValue = true;
6432   bool isConstant = true;
6433   unsigned NumConstantLanes = 0;
6434   SDValue Value;
6435   SDValue ConstantValue;
6436   for (unsigned i = 0; i < NumElts; ++i) {
6437     SDValue V = Op.getOperand(i);
6438     if (V.isUndef())
6439       continue;
6440     if (i > 0)
6441       isOnlyLowElement = false;
6442     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6443       isConstant = false;
6444
6445     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6446       ++NumConstantLanes;
6447       if (!ConstantValue.getNode())
6448         ConstantValue = V;
6449       else if (ConstantValue != V)
6450         usesOnlyOneConstantValue = false;
6451     }
6452
6453     if (!Value.getNode())
6454       Value = V;
6455     else if (V != Value)
6456       usesOnlyOneValue = false;
6457   }
6458
6459   if (!Value.getNode())
6460     return DAG.getUNDEF(VT);
6461
6462   if (isOnlyLowElement)
6463     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6464
6465   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6466   // i32 and try again.
6467   if (usesOnlyOneValue) {
6468     if (!isConstant) {
6469       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6470           Value.getValueType() != VT)
6471         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6472
6473       // This is actually a DUPLANExx operation, which keeps everything vectory.
6474
6475       // DUPLANE works on 128-bit vectors, widen it if necessary.
6476       SDValue Lane = Value.getOperand(1);
6477       Value = Value.getOperand(0);
6478       if (Value.getValueSizeInBits() == 64)
6479         Value = WidenVector(Value, DAG);
6480
6481       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6482       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6483     }
6484
6485     if (VT.getVectorElementType().isFloatingPoint()) {
6486       SmallVector<SDValue, 8> Ops;
6487       EVT EltTy = VT.getVectorElementType();
6488       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6489               "Unsupported floating-point vector type");
6490       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6491       for (unsigned i = 0; i < NumElts; ++i)
6492         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6493       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6494       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6495       Val = LowerBUILD_VECTOR(Val, DAG);
6496       if (Val.getNode())
6497         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6498     }
6499   }
6500
6501   // If there was only one constant value used and for more than one lane,
6502   // start by splatting that value, then replace the non-constant lanes. This
6503   // is better than the default, which will perform a separate initialization
6504   // for each lane.
6505   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6506     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6507     // Now insert the non-constant lanes.
6508     for (unsigned i = 0; i < NumElts; ++i) {
6509       SDValue V = Op.getOperand(i);
6510       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6511       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6512         // Note that type legalization likely mucked about with the VT of the
6513         // source operand, so we may have to convert it here before inserting.
6514         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6515       }
6516     }
6517     return Val;
6518   }
6519
6520   // If all elements are constants and the case above didn't get hit, fall back
6521   // to the default expansion, which will generate a load from the constant
6522   // pool.
6523   if (isConstant)
6524     return SDValue();
6525
6526   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6527   if (NumElts >= 4) {
6528     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6529       return shuffle;
6530   }
6531
6532   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6533   // know the default expansion would otherwise fall back on something even
6534   // worse. For a vector with one or two non-undef values, that's
6535   // scalar_to_vector for the elements followed by a shuffle (provided the
6536   // shuffle is valid for the target) and materialization element by element
6537   // on the stack followed by a load for everything else.
6538   if (!isConstant && !usesOnlyOneValue) {
6539     SDValue Vec = DAG.getUNDEF(VT);
6540     SDValue Op0 = Op.getOperand(0);
6541     unsigned ElemSize = VT.getScalarSizeInBits();
6542     unsigned i = 0;
6543     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6544     // a) Avoid a RMW dependency on the full vector register, and
6545     // b) Allow the register coalescer to fold away the copy if the
6546     //    value is already in an S or D register.
6547     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6548     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6549     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6550         (ElemSize == 32 || ElemSize == 64)) {
6551       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6552       MachineSDNode *N =
6553           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6554                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6555       Vec = SDValue(N, 0);
6556       ++i;
6557     }
6558     for (; i < NumElts; ++i) {
6559       SDValue V = Op.getOperand(i);
6560       if (V.isUndef())
6561         continue;
6562       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6563       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6564     }
6565     return Vec;
6566   }
6567
6568   // Just use the default expansion. We failed to find a better alternative.
6569   return SDValue();
6570 }
6571
6572 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6573                                                       SelectionDAG &DAG) const {
6574   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6575
6576   // Check for non-constant or out of range lane.
6577   EVT VT = Op.getOperand(0).getValueType();
6578   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6579   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6580     return SDValue();
6581
6582
6583   // Insertion/extraction are legal for V128 types.
6584   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6585       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6586       VT == MVT::v8f16)
6587     return Op;
6588
6589   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6590       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6591     return SDValue();
6592
6593   // For V64 types, we perform insertion by expanding the value
6594   // to a V128 type and perform the insertion on that.
6595   SDLoc DL(Op);
6596   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6597   EVT WideTy = WideVec.getValueType();
6598
6599   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6600                              Op.getOperand(1), Op.getOperand(2));
6601   // Re-narrow the resultant vector.
6602   return NarrowVector(Node, DAG);
6603 }
6604
6605 SDValue
6606 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6607                                                SelectionDAG &DAG) const {
6608   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6609
6610   // Check for non-constant or out of range lane.
6611   EVT VT = Op.getOperand(0).getValueType();
6612   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6613   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6614     return SDValue();
6615
6616
6617   // Insertion/extraction are legal for V128 types.
6618   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6619       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6620       VT == MVT::v8f16)
6621     return Op;
6622
6623   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6624       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6625     return SDValue();
6626
6627   // For V64 types, we perform extraction by expanding the value
6628   // to a V128 type and perform the extraction on that.
6629   SDLoc DL(Op);
6630   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6631   EVT WideTy = WideVec.getValueType();
6632
6633   EVT ExtrTy = WideTy.getVectorElementType();
6634   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6635     ExtrTy = MVT::i32;
6636
6637   // For extractions, we just return the result directly.
6638   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6639                      Op.getOperand(1));
6640 }
6641
6642 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6643                                                       SelectionDAG &DAG) const {
6644   EVT VT = Op.getOperand(0).getValueType();
6645   SDLoc dl(Op);
6646   // Just in case...
6647   if (!VT.isVector())
6648     return SDValue();
6649
6650   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6651   if (!Cst)
6652     return SDValue();
6653   unsigned Val = Cst->getZExtValue();
6654
6655   unsigned Size = Op.getValueSizeInBits();
6656
6657   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6658   if (Val == 0)
6659     return Op;
6660
6661   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6662   // that directly.
6663   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6664     return Op;
6665
6666   return SDValue();
6667 }
6668
6669 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6670                                                EVT VT) const {
6671   if (VT.getVectorNumElements() == 4 &&
6672       (VT.is128BitVector() || VT.is64BitVector())) {
6673     unsigned PFIndexes[4];
6674     for (unsigned i = 0; i != 4; ++i) {
6675       if (M[i] < 0)
6676         PFIndexes[i] = 8;
6677       else
6678         PFIndexes[i] = M[i];
6679     }
6680
6681     // Compute the index in the perfect shuffle table.
6682     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6683                             PFIndexes[2] * 9 + PFIndexes[3];
6684     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6685     unsigned Cost = (PFEntry >> 30);
6686
6687     if (Cost <= 4)
6688       return true;
6689   }
6690
6691   bool DummyBool;
6692   int DummyInt;
6693   unsigned DummyUnsigned;
6694
6695   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6696           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6697           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6698           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6699           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6700           isZIPMask(M, VT, DummyUnsigned) ||
6701           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6702           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6703           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6704           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6705           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6706 }
6707
6708 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6709 /// operand of a vector shift operation, where all the elements of the
6710 /// build_vector must have the same constant integer value.
6711 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6712   // Ignore bit_converts.
6713   while (Op.getOpcode() == ISD::BITCAST)
6714     Op = Op.getOperand(0);
6715   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6716   APInt SplatBits, SplatUndef;
6717   unsigned SplatBitSize;
6718   bool HasAnyUndefs;
6719   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6720                                     HasAnyUndefs, ElementBits) ||
6721       SplatBitSize > ElementBits)
6722     return false;
6723   Cnt = SplatBits.getSExtValue();
6724   return true;
6725 }
6726
6727 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6728 /// operand of a vector shift left operation.  That value must be in the range:
6729 ///   0 <= Value < ElementBits for a left shift; or
6730 ///   0 <= Value <= ElementBits for a long left shift.
6731 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6732   assert(VT.isVector() && "vector shift count is not a vector type");
6733   int64_t ElementBits = VT.getScalarSizeInBits();
6734   if (!getVShiftImm(Op, ElementBits, Cnt))
6735     return false;
6736   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6737 }
6738
6739 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6740 /// operand of a vector shift right operation. The value must be in the range:
6741 ///   1 <= Value <= ElementBits for a right shift; or
6742 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6743   assert(VT.isVector() && "vector shift count is not a vector type");
6744   int64_t ElementBits = VT.getScalarSizeInBits();
6745   if (!getVShiftImm(Op, ElementBits, Cnt))
6746     return false;
6747   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6748 }
6749
6750 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6751                                                       SelectionDAG &DAG) const {
6752   EVT VT = Op.getValueType();
6753   SDLoc DL(Op);
6754   int64_t Cnt;
6755
6756   if (!Op.getOperand(1).getValueType().isVector())
6757     return Op;
6758   unsigned EltSize = VT.getScalarSizeInBits();
6759
6760   switch (Op.getOpcode()) {
6761   default:
6762     llvm_unreachable("unexpected shift opcode");
6763
6764   case ISD::SHL:
6765     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6766       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6767                          DAG.getConstant(Cnt, DL, MVT::i32));
6768     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6769                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6770                                        MVT::i32),
6771                        Op.getOperand(0), Op.getOperand(1));
6772   case ISD::SRA:
6773   case ISD::SRL:
6774     // Right shift immediate
6775     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6776       unsigned Opc =
6777           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6778       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6779                          DAG.getConstant(Cnt, DL, MVT::i32));
6780     }
6781
6782     // Right shift register.  Note, there is not a shift right register
6783     // instruction, but the shift left register instruction takes a signed
6784     // value, where negative numbers specify a right shift.
6785     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6786                                                 : Intrinsic::aarch64_neon_ushl;
6787     // negate the shift amount
6788     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6789     SDValue NegShiftLeft =
6790         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6791                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6792                     NegShift);
6793     return NegShiftLeft;
6794   }
6795
6796   return SDValue();
6797 }
6798
6799 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6800                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6801                                     const SDLoc &dl, SelectionDAG &DAG) {
6802   EVT SrcVT = LHS.getValueType();
6803   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6804          "function only supposed to emit natural comparisons");
6805
6806   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6807   APInt CnstBits(VT.getSizeInBits(), 0);
6808   APInt UndefBits(VT.getSizeInBits(), 0);
6809   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6810   bool IsZero = IsCnst && (CnstBits == 0);
6811
6812   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6813     switch (CC) {
6814     default:
6815       return SDValue();
6816     case AArch64CC::NE: {
6817       SDValue Fcmeq;
6818       if (IsZero)
6819         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6820       else
6821         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6822       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6823     }
6824     case AArch64CC::EQ:
6825       if (IsZero)
6826         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6827       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6828     case AArch64CC::GE:
6829       if (IsZero)
6830         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6831       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6832     case AArch64CC::GT:
6833       if (IsZero)
6834         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6835       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6836     case AArch64CC::LS:
6837       if (IsZero)
6838         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6839       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6840     case AArch64CC::LT:
6841       if (!NoNans)
6842         return SDValue();
6843       // If we ignore NaNs then we can use to the MI implementation.
6844       LLVM_FALLTHROUGH;
6845     case AArch64CC::MI:
6846       if (IsZero)
6847         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6848       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6849     }
6850   }
6851
6852   switch (CC) {
6853   default:
6854     return SDValue();
6855   case AArch64CC::NE: {
6856     SDValue Cmeq;
6857     if (IsZero)
6858       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6859     else
6860       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6861     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6862   }
6863   case AArch64CC::EQ:
6864     if (IsZero)
6865       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6866     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6867   case AArch64CC::GE:
6868     if (IsZero)
6869       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6870     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6871   case AArch64CC::GT:
6872     if (IsZero)
6873       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6874     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6875   case AArch64CC::LE:
6876     if (IsZero)
6877       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6878     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6879   case AArch64CC::LS:
6880     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6881   case AArch64CC::LO:
6882     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6883   case AArch64CC::LT:
6884     if (IsZero)
6885       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6886     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6887   case AArch64CC::HI:
6888     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6889   case AArch64CC::HS:
6890     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6891   }
6892 }
6893
6894 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6895                                            SelectionDAG &DAG) const {
6896   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6897   SDValue LHS = Op.getOperand(0);
6898   SDValue RHS = Op.getOperand(1);
6899   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6900   SDLoc dl(Op);
6901
6902   if (LHS.getValueType().getVectorElementType().isInteger()) {
6903     assert(LHS.getValueType() == RHS.getValueType());
6904     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6905     SDValue Cmp =
6906         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6907     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6908   }
6909
6910   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6911     return SDValue();
6912
6913   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6914          LHS.getValueType().getVectorElementType() == MVT::f64);
6915
6916   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6917   // clean.  Some of them require two branches to implement.
6918   AArch64CC::CondCode CC1, CC2;
6919   bool ShouldInvert;
6920   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6921
6922   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6923   SDValue Cmp =
6924       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6925   if (!Cmp.getNode())
6926     return SDValue();
6927
6928   if (CC2 != AArch64CC::AL) {
6929     SDValue Cmp2 =
6930         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6931     if (!Cmp2.getNode())
6932       return SDValue();
6933
6934     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6935   }
6936
6937   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6938
6939   if (ShouldInvert)
6940     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6941
6942   return Cmp;
6943 }
6944
6945 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6946 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6947 /// specified in the intrinsic calls.
6948 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6949                                                const CallInst &I,
6950                                                unsigned Intrinsic) const {
6951   auto &DL = I.getModule()->getDataLayout();
6952   switch (Intrinsic) {
6953   case Intrinsic::aarch64_neon_ld2:
6954   case Intrinsic::aarch64_neon_ld3:
6955   case Intrinsic::aarch64_neon_ld4:
6956   case Intrinsic::aarch64_neon_ld1x2:
6957   case Intrinsic::aarch64_neon_ld1x3:
6958   case Intrinsic::aarch64_neon_ld1x4:
6959   case Intrinsic::aarch64_neon_ld2lane:
6960   case Intrinsic::aarch64_neon_ld3lane:
6961   case Intrinsic::aarch64_neon_ld4lane:
6962   case Intrinsic::aarch64_neon_ld2r:
6963   case Intrinsic::aarch64_neon_ld3r:
6964   case Intrinsic::aarch64_neon_ld4r: {
6965     Info.opc = ISD::INTRINSIC_W_CHAIN;
6966     // Conservatively set memVT to the entire set of vectors loaded.
6967     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6968     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6969     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6970     Info.offset = 0;
6971     Info.align = 0;
6972     Info.vol = false; // volatile loads with NEON intrinsics not supported
6973     Info.readMem = true;
6974     Info.writeMem = false;
6975     return true;
6976   }
6977   case Intrinsic::aarch64_neon_st2:
6978   case Intrinsic::aarch64_neon_st3:
6979   case Intrinsic::aarch64_neon_st4:
6980   case Intrinsic::aarch64_neon_st1x2:
6981   case Intrinsic::aarch64_neon_st1x3:
6982   case Intrinsic::aarch64_neon_st1x4:
6983   case Intrinsic::aarch64_neon_st2lane:
6984   case Intrinsic::aarch64_neon_st3lane:
6985   case Intrinsic::aarch64_neon_st4lane: {
6986     Info.opc = ISD::INTRINSIC_VOID;
6987     // Conservatively set memVT to the entire set of vectors stored.
6988     unsigned NumElts = 0;
6989     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6990       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6991       if (!ArgTy->isVectorTy())
6992         break;
6993       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6994     }
6995     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6996     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6997     Info.offset = 0;
6998     Info.align = 0;
6999     Info.vol = false; // volatile stores with NEON intrinsics not supported
7000     Info.readMem = false;
7001     Info.writeMem = true;
7002     return true;
7003   }
7004   case Intrinsic::aarch64_ldaxr:
7005   case Intrinsic::aarch64_ldxr: {
7006     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7007     Info.opc = ISD::INTRINSIC_W_CHAIN;
7008     Info.memVT = MVT::getVT(PtrTy->getElementType());
7009     Info.ptrVal = I.getArgOperand(0);
7010     Info.offset = 0;
7011     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7012     Info.vol = true;
7013     Info.readMem = true;
7014     Info.writeMem = false;
7015     return true;
7016   }
7017   case Intrinsic::aarch64_stlxr:
7018   case Intrinsic::aarch64_stxr: {
7019     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7020     Info.opc = ISD::INTRINSIC_W_CHAIN;
7021     Info.memVT = MVT::getVT(PtrTy->getElementType());
7022     Info.ptrVal = I.getArgOperand(1);
7023     Info.offset = 0;
7024     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7025     Info.vol = true;
7026     Info.readMem = false;
7027     Info.writeMem = true;
7028     return true;
7029   }
7030   case Intrinsic::aarch64_ldaxp:
7031   case Intrinsic::aarch64_ldxp: {
7032     Info.opc = ISD::INTRINSIC_W_CHAIN;
7033     Info.memVT = MVT::i128;
7034     Info.ptrVal = I.getArgOperand(0);
7035     Info.offset = 0;
7036     Info.align = 16;
7037     Info.vol = true;
7038     Info.readMem = true;
7039     Info.writeMem = false;
7040     return true;
7041   }
7042   case Intrinsic::aarch64_stlxp:
7043   case Intrinsic::aarch64_stxp: {
7044     Info.opc = ISD::INTRINSIC_W_CHAIN;
7045     Info.memVT = MVT::i128;
7046     Info.ptrVal = I.getArgOperand(2);
7047     Info.offset = 0;
7048     Info.align = 16;
7049     Info.vol = true;
7050     Info.readMem = false;
7051     Info.writeMem = true;
7052     return true;
7053   }
7054   default:
7055     break;
7056   }
7057
7058   return false;
7059 }
7060
7061 // Truncations from 64-bit GPR to 32-bit GPR is free.
7062 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7063   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7064     return false;
7065   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7066   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7067   return NumBits1 > NumBits2;
7068 }
7069 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7070   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7071     return false;
7072   unsigned NumBits1 = VT1.getSizeInBits();
7073   unsigned NumBits2 = VT2.getSizeInBits();
7074   return NumBits1 > NumBits2;
7075 }
7076
7077 /// Check if it is profitable to hoist instruction in then/else to if.
7078 /// Not profitable if I and it's user can form a FMA instruction
7079 /// because we prefer FMSUB/FMADD.
7080 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7081   if (I->getOpcode() != Instruction::FMul)
7082     return true;
7083
7084   if (I->getNumUses() != 1)
7085     return true;
7086
7087   Instruction *User = I->user_back();
7088
7089   if (User &&
7090       !(User->getOpcode() == Instruction::FSub ||
7091         User->getOpcode() == Instruction::FAdd))
7092     return true;
7093
7094   const TargetOptions &Options = getTargetMachine().Options;
7095   const DataLayout &DL = I->getModule()->getDataLayout();
7096   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7097
7098   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7099            isOperationLegalOrCustom(ISD::FMA, VT) &&
7100            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7101             Options.UnsafeFPMath));
7102 }
7103
7104 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7105 // 64-bit GPR.
7106 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7107   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7108     return false;
7109   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7110   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7111   return NumBits1 == 32 && NumBits2 == 64;
7112 }
7113 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7114   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7115     return false;
7116   unsigned NumBits1 = VT1.getSizeInBits();
7117   unsigned NumBits2 = VT2.getSizeInBits();
7118   return NumBits1 == 32 && NumBits2 == 64;
7119 }
7120
7121 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7122   EVT VT1 = Val.getValueType();
7123   if (isZExtFree(VT1, VT2)) {
7124     return true;
7125   }
7126
7127   if (Val.getOpcode() != ISD::LOAD)
7128     return false;
7129
7130   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7131   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7132           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7133           VT1.getSizeInBits() <= 32);
7134 }
7135
7136 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7137   if (isa<FPExtInst>(Ext))
7138     return false;
7139
7140   // Vector types are next free.
7141   if (Ext->getType()->isVectorTy())
7142     return false;
7143
7144   for (const Use &U : Ext->uses()) {
7145     // The extension is free if we can fold it with a left shift in an
7146     // addressing mode or an arithmetic operation: add, sub, and cmp.
7147
7148     // Is there a shift?
7149     const Instruction *Instr = cast<Instruction>(U.getUser());
7150
7151     // Is this a constant shift?
7152     switch (Instr->getOpcode()) {
7153     case Instruction::Shl:
7154       if (!isa<ConstantInt>(Instr->getOperand(1)))
7155         return false;
7156       break;
7157     case Instruction::GetElementPtr: {
7158       gep_type_iterator GTI = gep_type_begin(Instr);
7159       auto &DL = Ext->getModule()->getDataLayout();
7160       std::advance(GTI, U.getOperandNo()-1);
7161       Type *IdxTy = GTI.getIndexedType();
7162       // This extension will end up with a shift because of the scaling factor.
7163       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7164       // Get the shift amount based on the scaling factor:
7165       // log2(sizeof(IdxTy)) - log2(8).
7166       uint64_t ShiftAmt =
7167           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7168       // Is the constant foldable in the shift of the addressing mode?
7169       // I.e., shift amount is between 1 and 4 inclusive.
7170       if (ShiftAmt == 0 || ShiftAmt > 4)
7171         return false;
7172       break;
7173     }
7174     case Instruction::Trunc:
7175       // Check if this is a noop.
7176       // trunc(sext ty1 to ty2) to ty1.
7177       if (Instr->getType() == Ext->getOperand(0)->getType())
7178         continue;
7179       LLVM_FALLTHROUGH;
7180     default:
7181       return false;
7182     }
7183
7184     // At this point we can use the bfm family, so this extension is free
7185     // for that use.
7186   }
7187   return true;
7188 }
7189
7190 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7191                                           unsigned &RequiredAligment) const {
7192   if (!LoadedType.isSimple() ||
7193       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7194     return false;
7195   // Cyclone supports unaligned accesses.
7196   RequiredAligment = 0;
7197   unsigned NumBits = LoadedType.getSizeInBits();
7198   return NumBits == 32 || NumBits == 64;
7199 }
7200
7201 /// \brief Lower an interleaved load into a ldN intrinsic.
7202 ///
7203 /// E.g. Lower an interleaved load (Factor = 2):
7204 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7205 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7206 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7207 ///
7208 ///      Into:
7209 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7210 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7211 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7212 bool AArch64TargetLowering::lowerInterleavedLoad(
7213     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7214     ArrayRef<unsigned> Indices, unsigned Factor) const {
7215   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7216          "Invalid interleave factor");
7217   assert(!Shuffles.empty() && "Empty shufflevector input");
7218   assert(Shuffles.size() == Indices.size() &&
7219          "Unmatched number of shufflevectors and indices");
7220
7221   const DataLayout &DL = LI->getModule()->getDataLayout();
7222
7223   VectorType *VecTy = Shuffles[0]->getType();
7224   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7225
7226   // Skip if we do not have NEON and skip illegal vector types.
7227   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7228     return false;
7229
7230   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7231   // load integer vectors first and then convert to pointer vectors.
7232   Type *EltTy = VecTy->getVectorElementType();
7233   if (EltTy->isPointerTy())
7234     VecTy =
7235         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7236
7237   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7238   Type *Tys[2] = {VecTy, PtrTy};
7239   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7240                                             Intrinsic::aarch64_neon_ld3,
7241                                             Intrinsic::aarch64_neon_ld4};
7242   Function *LdNFunc =
7243       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7244
7245   IRBuilder<> Builder(LI);
7246   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7247
7248   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7249
7250   // Replace uses of each shufflevector with the corresponding vector loaded
7251   // by ldN.
7252   for (unsigned i = 0; i < Shuffles.size(); i++) {
7253     ShuffleVectorInst *SVI = Shuffles[i];
7254     unsigned Index = Indices[i];
7255
7256     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7257
7258     // Convert the integer vector to pointer vector if the element is pointer.
7259     if (EltTy->isPointerTy())
7260       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7261
7262     SVI->replaceAllUsesWith(SubVec);
7263   }
7264
7265   return true;
7266 }
7267
7268 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7269 ///
7270 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7271 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7272                                    unsigned NumElts) {
7273   SmallVector<Constant *, 16> Mask;
7274   for (unsigned i = 0; i < NumElts; i++)
7275     Mask.push_back(Builder.getInt32(Start + i));
7276
7277   return ConstantVector::get(Mask);
7278 }
7279
7280 /// \brief Lower an interleaved store into a stN intrinsic.
7281 ///
7282 /// E.g. Lower an interleaved store (Factor = 3):
7283 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7284 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7285 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7286 ///
7287 ///      Into:
7288 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7289 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7290 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7291 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7292 ///
7293 /// Note that the new shufflevectors will be removed and we'll only generate one
7294 /// st3 instruction in CodeGen.
7295 ///
7296 /// Example for a more general valid mask (Factor 3). Lower:
7297 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7298 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7299 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7300 ///
7301 ///      Into:
7302 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7303 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7304 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7305 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7306 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7307                                                   ShuffleVectorInst *SVI,
7308                                                   unsigned Factor) const {
7309   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7310          "Invalid interleave factor");
7311
7312   VectorType *VecTy = SVI->getType();
7313   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7314          "Invalid interleaved store");
7315
7316   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7317   Type *EltTy = VecTy->getVectorElementType();
7318   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7319
7320   const DataLayout &DL = SI->getModule()->getDataLayout();
7321   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7322
7323   // Skip if we do not have NEON and skip illegal vector types.
7324   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7325     return false;
7326
7327   Value *Op0 = SVI->getOperand(0);
7328   Value *Op1 = SVI->getOperand(1);
7329   IRBuilder<> Builder(SI);
7330
7331   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7332   // vectors to integer vectors.
7333   if (EltTy->isPointerTy()) {
7334     Type *IntTy = DL.getIntPtrType(EltTy);
7335     unsigned NumOpElts =
7336         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7337
7338     // Convert to the corresponding integer vector.
7339     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7340     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7341     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7342
7343     SubVecTy = VectorType::get(IntTy, LaneLen);
7344   }
7345
7346   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7347   Type *Tys[2] = {SubVecTy, PtrTy};
7348   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7349                                              Intrinsic::aarch64_neon_st3,
7350                                              Intrinsic::aarch64_neon_st4};
7351   Function *StNFunc =
7352       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7353
7354   SmallVector<Value *, 5> Ops;
7355
7356   // Split the shufflevector operands into sub vectors for the new stN call.
7357   auto Mask = SVI->getShuffleMask();
7358   for (unsigned i = 0; i < Factor; i++) {
7359     if (Mask[i] >= 0) {
7360       Ops.push_back(Builder.CreateShuffleVector(
7361         Op0, Op1, getSequentialMask(Builder, Mask[i], LaneLen)));
7362     } else {
7363       unsigned StartMask = 0;
7364       for (unsigned j = 1; j < LaneLen; j++) {
7365         if (Mask[j*Factor + i] >= 0) {
7366           StartMask = Mask[j*Factor + i] - j;
7367           break;
7368         }
7369       }
7370       // Note: If all elements in a chunk are undefs, StartMask=0!
7371       // Note: Filling undef gaps with random elements is ok, since
7372       // those elements were being written anyway (with undefs).
7373       // In the case of all undefs we're defaulting to using elems from 0
7374       // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7375       Ops.push_back(Builder.CreateShuffleVector(
7376         Op0, Op1, getSequentialMask(Builder, StartMask, LaneLen)));
7377     }
7378   }
7379
7380   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7381   Builder.CreateCall(StNFunc, Ops);
7382   return true;
7383 }
7384
7385 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7386                        unsigned AlignCheck) {
7387   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7388           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7389 }
7390
7391 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7392                                                unsigned SrcAlign, bool IsMemset,
7393                                                bool ZeroMemset,
7394                                                bool MemcpyStrSrc,
7395                                                MachineFunction &MF) const {
7396   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7397   // instruction to materialize the v2i64 zero and one store (with restrictive
7398   // addressing mode). Just do two i64 store of zero-registers.
7399   bool Fast;
7400   const Function *F = MF.getFunction();
7401   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7402       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7403       (memOpAlign(SrcAlign, DstAlign, 16) ||
7404        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7405     return MVT::f128;
7406
7407   if (Size >= 8 &&
7408       (memOpAlign(SrcAlign, DstAlign, 8) ||
7409        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7410     return MVT::i64;
7411
7412   if (Size >= 4 &&
7413       (memOpAlign(SrcAlign, DstAlign, 4) ||
7414        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7415     return MVT::i32;
7416
7417   return MVT::Other;
7418 }
7419
7420 // 12-bit optionally shifted immediates are legal for adds.
7421 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7422   // Avoid UB for INT64_MIN.
7423   if (Immed == std::numeric_limits<int64_t>::min())
7424     return false;
7425   // Same encoding for add/sub, just flip the sign.
7426   Immed = std::abs(Immed);
7427   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7428 }
7429
7430 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7431 // immediates is the same as for an add or a sub.
7432 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7433   return isLegalAddImmediate(Immed);
7434 }
7435
7436 /// isLegalAddressingMode - Return true if the addressing mode represented
7437 /// by AM is legal for this target, for a load/store of the specified type.
7438 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7439                                                   const AddrMode &AM, Type *Ty,
7440                                                   unsigned AS) const {
7441   // AArch64 has five basic addressing modes:
7442   //  reg
7443   //  reg + 9-bit signed offset
7444   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7445   //  reg1 + reg2
7446   //  reg + SIZE_IN_BYTES * reg
7447
7448   // No global is ever allowed as a base.
7449   if (AM.BaseGV)
7450     return false;
7451
7452   // No reg+reg+imm addressing.
7453   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7454     return false;
7455
7456   // check reg + imm case:
7457   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7458   uint64_t NumBytes = 0;
7459   if (Ty->isSized()) {
7460     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7461     NumBytes = NumBits / 8;
7462     if (!isPowerOf2_64(NumBits))
7463       NumBytes = 0;
7464   }
7465
7466   if (!AM.Scale) {
7467     int64_t Offset = AM.BaseOffs;
7468
7469     // 9-bit signed offset
7470     if (isInt<9>(Offset))
7471       return true;
7472
7473     // 12-bit unsigned offset
7474     unsigned shift = Log2_64(NumBytes);
7475     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7476         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7477         (Offset >> shift) << shift == Offset)
7478       return true;
7479     return false;
7480   }
7481
7482   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7483
7484   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7485 }
7486
7487 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7488                                                 const AddrMode &AM, Type *Ty,
7489                                                 unsigned AS) const {
7490   // Scaling factors are not free at all.
7491   // Operands                     | Rt Latency
7492   // -------------------------------------------
7493   // Rt, [Xn, Xm]                 | 4
7494   // -------------------------------------------
7495   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7496   // Rt, [Xn, Wm, <extend> #imm]  |
7497   if (isLegalAddressingMode(DL, AM, Ty, AS))
7498     // Scale represents reg2 * scale, thus account for 1 if
7499     // it is not equal to 0 or 1.
7500     return AM.Scale != 0 && AM.Scale != 1;
7501   return -1;
7502 }
7503
7504 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7505   VT = VT.getScalarType();
7506
7507   if (!VT.isSimple())
7508     return false;
7509
7510   switch (VT.getSimpleVT().SimpleTy) {
7511   case MVT::f32:
7512   case MVT::f64:
7513     return true;
7514   default:
7515     break;
7516   }
7517
7518   return false;
7519 }
7520
7521 const MCPhysReg *
7522 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7523   // LR is a callee-save register, but we must treat it as clobbered by any call
7524   // site. Hence we include LR in the scratch registers, which are in turn added
7525   // as implicit-defs for stackmaps and patchpoints.
7526   static const MCPhysReg ScratchRegs[] = {
7527     AArch64::X16, AArch64::X17, AArch64::LR, 0
7528   };
7529   return ScratchRegs;
7530 }
7531
7532 bool
7533 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7534   EVT VT = N->getValueType(0);
7535     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7536     // it with shift to let it be lowered to UBFX.
7537   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7538       isa<ConstantSDNode>(N->getOperand(1))) {
7539     uint64_t TruncMask = N->getConstantOperandVal(1);
7540     if (isMask_64(TruncMask) &&
7541       N->getOperand(0).getOpcode() == ISD::SRL &&
7542       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7543       return false;
7544   }
7545   return true;
7546 }
7547
7548 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7549                                                               Type *Ty) const {
7550   assert(Ty->isIntegerTy());
7551
7552   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7553   if (BitSize == 0)
7554     return false;
7555
7556   int64_t Val = Imm.getSExtValue();
7557   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7558     return true;
7559
7560   if ((int64_t)Val < 0)
7561     Val = ~Val;
7562   if (BitSize == 32)
7563     Val &= (1LL << 32) - 1;
7564
7565   unsigned LZ = countLeadingZeros((uint64_t)Val);
7566   unsigned Shift = (63 - LZ) / 16;
7567   // MOVZ is free so return true for one or fewer MOVK.
7568   return Shift < 3;
7569 }
7570
7571 /// Turn vector tests of the signbit in the form of:
7572 ///   xor (sra X, elt_size(X)-1), -1
7573 /// into:
7574 ///   cmge X, X, #0
7575 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7576                                          const AArch64Subtarget *Subtarget) {
7577   EVT VT = N->getValueType(0);
7578   if (!Subtarget->hasNEON() || !VT.isVector())
7579     return SDValue();
7580
7581   // There must be a shift right algebraic before the xor, and the xor must be a
7582   // 'not' operation.
7583   SDValue Shift = N->getOperand(0);
7584   SDValue Ones = N->getOperand(1);
7585   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7586       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7587     return SDValue();
7588
7589   // The shift should be smearing the sign bit across each vector element.
7590   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7591   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7592   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7593     return SDValue();
7594
7595   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7596 }
7597
7598 // Generate SUBS and CSEL for integer abs.
7599 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7600   EVT VT = N->getValueType(0);
7601
7602   SDValue N0 = N->getOperand(0);
7603   SDValue N1 = N->getOperand(1);
7604   SDLoc DL(N);
7605
7606   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7607   // and change it to SUB and CSEL.
7608   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7609       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7610       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7611     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7612       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7613         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7614                                   N0.getOperand(0));
7615         // Generate SUBS & CSEL.
7616         SDValue Cmp =
7617             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7618                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7619         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7620                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7621                            SDValue(Cmp.getNode(), 1));
7622       }
7623   return SDValue();
7624 }
7625
7626 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7627                                  TargetLowering::DAGCombinerInfo &DCI,
7628                                  const AArch64Subtarget *Subtarget) {
7629   if (DCI.isBeforeLegalizeOps())
7630     return SDValue();
7631
7632   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7633     return Cmp;
7634
7635   return performIntegerAbsCombine(N, DAG);
7636 }
7637
7638 SDValue
7639 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7640                                      SelectionDAG &DAG,
7641                                      std::vector<SDNode *> *Created) const {
7642   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7643   if (isIntDivCheap(N->getValueType(0), Attr))
7644     return SDValue(N,0); // Lower SDIV as SDIV
7645
7646   // fold (sdiv X, pow2)
7647   EVT VT = N->getValueType(0);
7648   if ((VT != MVT::i32 && VT != MVT::i64) ||
7649       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7650     return SDValue();
7651
7652   SDLoc DL(N);
7653   SDValue N0 = N->getOperand(0);
7654   unsigned Lg2 = Divisor.countTrailingZeros();
7655   SDValue Zero = DAG.getConstant(0, DL, VT);
7656   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7657
7658   // Add (N0 < 0) ? Pow2 - 1 : 0;
7659   SDValue CCVal;
7660   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7661   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7662   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7663
7664   if (Created) {
7665     Created->push_back(Cmp.getNode());
7666     Created->push_back(Add.getNode());
7667     Created->push_back(CSel.getNode());
7668   }
7669
7670   // Divide by pow2.
7671   SDValue SRA =
7672       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7673
7674   // If we're dividing by a positive value, we're done.  Otherwise, we must
7675   // negate the result.
7676   if (Divisor.isNonNegative())
7677     return SRA;
7678
7679   if (Created)
7680     Created->push_back(SRA.getNode());
7681   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7682 }
7683
7684 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7685                                  TargetLowering::DAGCombinerInfo &DCI,
7686                                  const AArch64Subtarget *Subtarget) {
7687   if (DCI.isBeforeLegalizeOps())
7688     return SDValue();
7689
7690   // The below optimizations require a constant RHS.
7691   if (!isa<ConstantSDNode>(N->getOperand(1)))
7692     return SDValue();
7693
7694   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7695   const APInt &ConstValue = C->getAPIntValue();
7696
7697   // Multiplication of a power of two plus/minus one can be done more
7698   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7699   // future CPUs have a cheaper MADD instruction, this may need to be
7700   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7701   // 64-bit is 5 cycles, so this is always a win.
7702   // More aggressively, some multiplications N0 * C can be lowered to
7703   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7704   // e.g. 6=3*2=(2+1)*2.
7705   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7706   // which equals to (1+2)*16-(1+2).
7707   SDValue N0 = N->getOperand(0);
7708   // TrailingZeroes is used to test if the mul can be lowered to
7709   // shift+add+shift.
7710   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7711   if (TrailingZeroes) {
7712     // Conservatively do not lower to shift+add+shift if the mul might be
7713     // folded into smul or umul.
7714     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7715                             isZeroExtended(N0.getNode(), DAG)))
7716       return SDValue();
7717     // Conservatively do not lower to shift+add+shift if the mul might be
7718     // folded into madd or msub.
7719     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7720                            N->use_begin()->getOpcode() == ISD::SUB))
7721       return SDValue();
7722   }
7723   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7724   // and shift+add+shift.
7725   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7726
7727   unsigned ShiftAmt, AddSubOpc;
7728   // Is the shifted value the LHS operand of the add/sub?
7729   bool ShiftValUseIsN0 = true;
7730   // Do we need to negate the result?
7731   bool NegateResult = false;
7732
7733   if (ConstValue.isNonNegative()) {
7734     // (mul x, 2^N + 1) => (add (shl x, N), x)
7735     // (mul x, 2^N - 1) => (sub (shl x, N), x)
7736     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7737     APInt SCVMinus1 = ShiftedConstValue - 1;
7738     APInt CVPlus1 = ConstValue + 1;
7739     if (SCVMinus1.isPowerOf2()) {
7740       ShiftAmt = SCVMinus1.logBase2();
7741       AddSubOpc = ISD::ADD;
7742     } else if (CVPlus1.isPowerOf2()) {
7743       ShiftAmt = CVPlus1.logBase2();
7744       AddSubOpc = ISD::SUB;
7745     } else
7746       return SDValue();
7747   } else {
7748     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7749     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7750     APInt CVNegPlus1 = -ConstValue + 1;
7751     APInt CVNegMinus1 = -ConstValue - 1;
7752     if (CVNegPlus1.isPowerOf2()) {
7753       ShiftAmt = CVNegPlus1.logBase2();
7754       AddSubOpc = ISD::SUB;
7755       ShiftValUseIsN0 = false;
7756     } else if (CVNegMinus1.isPowerOf2()) {
7757       ShiftAmt = CVNegMinus1.logBase2();
7758       AddSubOpc = ISD::ADD;
7759       NegateResult = true;
7760     } else
7761       return SDValue();
7762   }
7763
7764   SDLoc DL(N);
7765   EVT VT = N->getValueType(0);
7766   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
7767                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
7768
7769   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7770   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7771   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
7772   assert(!(NegateResult && TrailingZeroes) &&
7773          "NegateResult and TrailingZeroes cannot both be true for now.");
7774   // Negate the result.
7775   if (NegateResult)
7776     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7777   // Shift the result.
7778   if (TrailingZeroes)
7779     return DAG.getNode(ISD::SHL, DL, VT, Res,
7780                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7781   return Res;
7782 }
7783
7784 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7785                                                          SelectionDAG &DAG) {
7786   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7787   // optimize away operation when it's from a constant.
7788   //
7789   // The general transformation is:
7790   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7791   //       AND(VECTOR_CMP(x,y), constant2)
7792   //    constant2 = UNARYOP(constant)
7793
7794   // Early exit if this isn't a vector operation, the operand of the
7795   // unary operation isn't a bitwise AND, or if the sizes of the operations
7796   // aren't the same.
7797   EVT VT = N->getValueType(0);
7798   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7799       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7800       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7801     return SDValue();
7802
7803   // Now check that the other operand of the AND is a constant. We could
7804   // make the transformation for non-constant splats as well, but it's unclear
7805   // that would be a benefit as it would not eliminate any operations, just
7806   // perform one more step in scalar code before moving to the vector unit.
7807   if (BuildVectorSDNode *BV =
7808           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7809     // Bail out if the vector isn't a constant.
7810     if (!BV->isConstant())
7811       return SDValue();
7812
7813     // Everything checks out. Build up the new and improved node.
7814     SDLoc DL(N);
7815     EVT IntVT = BV->getValueType(0);
7816     // Create a new constant of the appropriate type for the transformed
7817     // DAG.
7818     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7819     // The AND node needs bitcasts to/from an integer vector type around it.
7820     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7821     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7822                                  N->getOperand(0)->getOperand(0), MaskConst);
7823     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7824     return Res;
7825   }
7826
7827   return SDValue();
7828 }
7829
7830 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7831                                      const AArch64Subtarget *Subtarget) {
7832   // First try to optimize away the conversion when it's conditionally from
7833   // a constant. Vectors only.
7834   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7835     return Res;
7836
7837   EVT VT = N->getValueType(0);
7838   if (VT != MVT::f32 && VT != MVT::f64)
7839     return SDValue();
7840
7841   // Only optimize when the source and destination types have the same width.
7842   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7843     return SDValue();
7844
7845   // If the result of an integer load is only used by an integer-to-float
7846   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7847   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7848   SDValue N0 = N->getOperand(0);
7849   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7850       // Do not change the width of a volatile load.
7851       !cast<LoadSDNode>(N0)->isVolatile()) {
7852     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7853     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7854                                LN0->getPointerInfo(), LN0->getAlignment(),
7855                                LN0->getMemOperand()->getFlags());
7856
7857     // Make sure successors of the original load stay after it by updating them
7858     // to use the new Chain.
7859     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7860
7861     unsigned Opcode =
7862         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7863     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7864   }
7865
7866   return SDValue();
7867 }
7868
7869 /// Fold a floating-point multiply by power of two into floating-point to
7870 /// fixed-point conversion.
7871 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7872                                      TargetLowering::DAGCombinerInfo &DCI,
7873                                      const AArch64Subtarget *Subtarget) {
7874   if (!Subtarget->hasNEON())
7875     return SDValue();
7876
7877   SDValue Op = N->getOperand(0);
7878   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7879       Op.getOpcode() != ISD::FMUL)
7880     return SDValue();
7881
7882   SDValue ConstVec = Op->getOperand(1);
7883   if (!isa<BuildVectorSDNode>(ConstVec))
7884     return SDValue();
7885
7886   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7887   uint32_t FloatBits = FloatTy.getSizeInBits();
7888   if (FloatBits != 32 && FloatBits != 64)
7889     return SDValue();
7890
7891   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7892   uint32_t IntBits = IntTy.getSizeInBits();
7893   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7894     return SDValue();
7895
7896   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7897   if (IntBits > FloatBits)
7898     return SDValue();
7899
7900   BitVector UndefElements;
7901   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7902   int32_t Bits = IntBits == 64 ? 64 : 32;
7903   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7904   if (C == -1 || C == 0 || C > Bits)
7905     return SDValue();
7906
7907   MVT ResTy;
7908   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7909   switch (NumLanes) {
7910   default:
7911     return SDValue();
7912   case 2:
7913     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7914     break;
7915   case 4:
7916     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7917     break;
7918   }
7919
7920   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7921     return SDValue();
7922
7923   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7924          "Illegal vector type after legalization");
7925
7926   SDLoc DL(N);
7927   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7928   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7929                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7930   SDValue FixConv =
7931       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7932                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7933                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7934   // We can handle smaller integers by generating an extra trunc.
7935   if (IntBits < FloatBits)
7936     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7937
7938   return FixConv;
7939 }
7940
7941 /// Fold a floating-point divide by power of two into fixed-point to
7942 /// floating-point conversion.
7943 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7944                                   TargetLowering::DAGCombinerInfo &DCI,
7945                                   const AArch64Subtarget *Subtarget) {
7946   if (!Subtarget->hasNEON())
7947     return SDValue();
7948
7949   SDValue Op = N->getOperand(0);
7950   unsigned Opc = Op->getOpcode();
7951   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7952       !Op.getOperand(0).getValueType().isSimple() ||
7953       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7954     return SDValue();
7955
7956   SDValue ConstVec = N->getOperand(1);
7957   if (!isa<BuildVectorSDNode>(ConstVec))
7958     return SDValue();
7959
7960   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7961   int32_t IntBits = IntTy.getSizeInBits();
7962   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7963     return SDValue();
7964
7965   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7966   int32_t FloatBits = FloatTy.getSizeInBits();
7967   if (FloatBits != 32 && FloatBits != 64)
7968     return SDValue();
7969
7970   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7971   if (IntBits > FloatBits)
7972     return SDValue();
7973
7974   BitVector UndefElements;
7975   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7976   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7977   if (C == -1 || C == 0 || C > FloatBits)
7978     return SDValue();
7979
7980   MVT ResTy;
7981   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7982   switch (NumLanes) {
7983   default:
7984     return SDValue();
7985   case 2:
7986     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7987     break;
7988   case 4:
7989     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7990     break;
7991   }
7992
7993   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7994     return SDValue();
7995
7996   SDLoc DL(N);
7997   SDValue ConvInput = Op.getOperand(0);
7998   bool IsSigned = Opc == ISD::SINT_TO_FP;
7999   if (IntBits < FloatBits)
8000     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8001                             ResTy, ConvInput);
8002
8003   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8004                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
8005   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8006                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8007                      DAG.getConstant(C, DL, MVT::i32));
8008 }
8009
8010 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8011 /// searches for and classifies those shifts.
8012 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8013                          bool &FromHi) {
8014   if (N.getOpcode() == ISD::SHL)
8015     FromHi = false;
8016   else if (N.getOpcode() == ISD::SRL)
8017     FromHi = true;
8018   else
8019     return false;
8020
8021   if (!isa<ConstantSDNode>(N.getOperand(1)))
8022     return false;
8023
8024   ShiftAmount = N->getConstantOperandVal(1);
8025   Src = N->getOperand(0);
8026   return true;
8027 }
8028
8029 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8030 /// registers viewed as a high/low pair. This function looks for the pattern:
8031 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8032 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8033 /// independent.
8034 static SDValue tryCombineToEXTR(SDNode *N,
8035                                 TargetLowering::DAGCombinerInfo &DCI) {
8036   SelectionDAG &DAG = DCI.DAG;
8037   SDLoc DL(N);
8038   EVT VT = N->getValueType(0);
8039
8040   assert(N->getOpcode() == ISD::OR && "Unexpected root");
8041
8042   if (VT != MVT::i32 && VT != MVT::i64)
8043     return SDValue();
8044
8045   SDValue LHS;
8046   uint32_t ShiftLHS = 0;
8047   bool LHSFromHi = 0;
8048   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8049     return SDValue();
8050
8051   SDValue RHS;
8052   uint32_t ShiftRHS = 0;
8053   bool RHSFromHi = 0;
8054   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8055     return SDValue();
8056
8057   // If they're both trying to come from the high part of the register, they're
8058   // not really an EXTR.
8059   if (LHSFromHi == RHSFromHi)
8060     return SDValue();
8061
8062   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8063     return SDValue();
8064
8065   if (LHSFromHi) {
8066     std::swap(LHS, RHS);
8067     std::swap(ShiftLHS, ShiftRHS);
8068   }
8069
8070   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8071                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
8072 }
8073
8074 static SDValue tryCombineToBSL(SDNode *N,
8075                                 TargetLowering::DAGCombinerInfo &DCI) {
8076   EVT VT = N->getValueType(0);
8077   SelectionDAG &DAG = DCI.DAG;
8078   SDLoc DL(N);
8079
8080   if (!VT.isVector())
8081     return SDValue();
8082
8083   SDValue N0 = N->getOperand(0);
8084   if (N0.getOpcode() != ISD::AND)
8085     return SDValue();
8086
8087   SDValue N1 = N->getOperand(1);
8088   if (N1.getOpcode() != ISD::AND)
8089     return SDValue();
8090
8091   // We only have to look for constant vectors here since the general, variable
8092   // case can be handled in TableGen.
8093   unsigned Bits = VT.getScalarSizeInBits();
8094   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8095   for (int i = 1; i >= 0; --i)
8096     for (int j = 1; j >= 0; --j) {
8097       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8098       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8099       if (!BVN0 || !BVN1)
8100         continue;
8101
8102       bool FoundMatch = true;
8103       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8104         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8105         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8106         if (!CN0 || !CN1 ||
8107             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8108           FoundMatch = false;
8109           break;
8110         }
8111       }
8112
8113       if (FoundMatch)
8114         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8115                            N0->getOperand(1 - i), N1->getOperand(1 - j));
8116     }
8117
8118   return SDValue();
8119 }
8120
8121 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8122                                 const AArch64Subtarget *Subtarget) {
8123   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8124   SelectionDAG &DAG = DCI.DAG;
8125   EVT VT = N->getValueType(0);
8126
8127   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8128     return SDValue();
8129
8130   if (SDValue Res = tryCombineToEXTR(N, DCI))
8131     return Res;
8132
8133   if (SDValue Res = tryCombineToBSL(N, DCI))
8134     return Res;
8135
8136   return SDValue();
8137 }
8138
8139 static SDValue performSRLCombine(SDNode *N,
8140                                  TargetLowering::DAGCombinerInfo &DCI) {
8141   SelectionDAG &DAG = DCI.DAG;
8142   EVT VT = N->getValueType(0);
8143   if (VT != MVT::i32 && VT != MVT::i64)
8144     return SDValue();
8145
8146   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8147   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8148   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8149   SDValue N0 = N->getOperand(0);
8150   if (N0.getOpcode() == ISD::BSWAP) {
8151     SDLoc DL(N);
8152     SDValue N1 = N->getOperand(1);
8153     SDValue N00 = N0.getOperand(0);
8154     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8155       uint64_t ShiftAmt = C->getZExtValue();
8156       if (VT == MVT::i32 && ShiftAmt == 16 &&
8157           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8158         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8159       if (VT == MVT::i64 && ShiftAmt == 32 &&
8160           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8161         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8162     }
8163   }
8164   return SDValue();
8165 }
8166
8167 static SDValue performBitcastCombine(SDNode *N,
8168                                      TargetLowering::DAGCombinerInfo &DCI,
8169                                      SelectionDAG &DAG) {
8170   // Wait 'til after everything is legalized to try this. That way we have
8171   // legal vector types and such.
8172   if (DCI.isBeforeLegalizeOps())
8173     return SDValue();
8174
8175   // Remove extraneous bitcasts around an extract_subvector.
8176   // For example,
8177   //    (v4i16 (bitconvert
8178   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8179   //  becomes
8180   //    (extract_subvector ((v8i16 ...), (i64 4)))
8181
8182   // Only interested in 64-bit vectors as the ultimate result.
8183   EVT VT = N->getValueType(0);
8184   if (!VT.isVector())
8185     return SDValue();
8186   if (VT.getSimpleVT().getSizeInBits() != 64)
8187     return SDValue();
8188   // Is the operand an extract_subvector starting at the beginning or halfway
8189   // point of the vector? A low half may also come through as an
8190   // EXTRACT_SUBREG, so look for that, too.
8191   SDValue Op0 = N->getOperand(0);
8192   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8193       !(Op0->isMachineOpcode() &&
8194         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8195     return SDValue();
8196   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8197   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8198     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8199       return SDValue();
8200   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8201     if (idx != AArch64::dsub)
8202       return SDValue();
8203     // The dsub reference is equivalent to a lane zero subvector reference.
8204     idx = 0;
8205   }
8206   // Look through the bitcast of the input to the extract.
8207   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8208     return SDValue();
8209   SDValue Source = Op0->getOperand(0)->getOperand(0);
8210   // If the source type has twice the number of elements as our destination
8211   // type, we know this is an extract of the high or low half of the vector.
8212   EVT SVT = Source->getValueType(0);
8213   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8214     return SDValue();
8215
8216   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8217
8218   // Create the simplified form to just extract the low or high half of the
8219   // vector directly rather than bothering with the bitcasts.
8220   SDLoc dl(N);
8221   unsigned NumElements = VT.getVectorNumElements();
8222   if (idx) {
8223     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8224     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8225   } else {
8226     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8227     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8228                                       Source, SubReg),
8229                    0);
8230   }
8231 }
8232
8233 static SDValue performConcatVectorsCombine(SDNode *N,
8234                                            TargetLowering::DAGCombinerInfo &DCI,
8235                                            SelectionDAG &DAG) {
8236   SDLoc dl(N);
8237   EVT VT = N->getValueType(0);
8238   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8239
8240   // Optimize concat_vectors of truncated vectors, where the intermediate
8241   // type is illegal, to avoid said illegality,  e.g.,
8242   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8243   //                          (v2i16 (truncate (v2i64)))))
8244   // ->
8245   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8246   //                                    (v4i32 (bitcast (v2i64))),
8247   //                                    <0, 2, 4, 6>)))
8248   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8249   // on both input and result type, so we might generate worse code.
8250   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8251   if (N->getNumOperands() == 2 &&
8252       N0->getOpcode() == ISD::TRUNCATE &&
8253       N1->getOpcode() == ISD::TRUNCATE) {
8254     SDValue N00 = N0->getOperand(0);
8255     SDValue N10 = N1->getOperand(0);
8256     EVT N00VT = N00.getValueType();
8257
8258     if (N00VT == N10.getValueType() &&
8259         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8260         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8261       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8262       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8263       for (size_t i = 0; i < Mask.size(); ++i)
8264         Mask[i] = i * 2;
8265       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8266                          DAG.getVectorShuffle(
8267                              MidVT, dl,
8268                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8269                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8270     }
8271   }
8272
8273   // Wait 'til after everything is legalized to try this. That way we have
8274   // legal vector types and such.
8275   if (DCI.isBeforeLegalizeOps())
8276     return SDValue();
8277
8278   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8279   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8280   // canonicalise to that.
8281   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8282     assert(VT.getScalarSizeInBits() == 64);
8283     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8284                        DAG.getConstant(0, dl, MVT::i64));
8285   }
8286
8287   // Canonicalise concat_vectors so that the right-hand vector has as few
8288   // bit-casts as possible before its real operation. The primary matching
8289   // destination for these operations will be the narrowing "2" instructions,
8290   // which depend on the operation being performed on this right-hand vector.
8291   // For example,
8292   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8293   // becomes
8294   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8295
8296   if (N1->getOpcode() != ISD::BITCAST)
8297     return SDValue();
8298   SDValue RHS = N1->getOperand(0);
8299   MVT RHSTy = RHS.getValueType().getSimpleVT();
8300   // If the RHS is not a vector, this is not the pattern we're looking for.
8301   if (!RHSTy.isVector())
8302     return SDValue();
8303
8304   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8305
8306   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8307                                   RHSTy.getVectorNumElements() * 2);
8308   return DAG.getNode(ISD::BITCAST, dl, VT,
8309                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8310                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8311                                  RHS));
8312 }
8313
8314 static SDValue tryCombineFixedPointConvert(SDNode *N,
8315                                            TargetLowering::DAGCombinerInfo &DCI,
8316                                            SelectionDAG &DAG) {
8317   // Wait 'til after everything is legalized to try this. That way we have
8318   // legal vector types and such.
8319   if (DCI.isBeforeLegalizeOps())
8320     return SDValue();
8321   // Transform a scalar conversion of a value from a lane extract into a
8322   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8323   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8324   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8325   //
8326   // The second form interacts better with instruction selection and the
8327   // register allocator to avoid cross-class register copies that aren't
8328   // coalescable due to a lane reference.
8329
8330   // Check the operand and see if it originates from a lane extract.
8331   SDValue Op1 = N->getOperand(1);
8332   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8333     // Yep, no additional predication needed. Perform the transform.
8334     SDValue IID = N->getOperand(0);
8335     SDValue Shift = N->getOperand(2);
8336     SDValue Vec = Op1.getOperand(0);
8337     SDValue Lane = Op1.getOperand(1);
8338     EVT ResTy = N->getValueType(0);
8339     EVT VecResTy;
8340     SDLoc DL(N);
8341
8342     // The vector width should be 128 bits by the time we get here, even
8343     // if it started as 64 bits (the extract_vector handling will have
8344     // done so).
8345     assert(Vec.getValueSizeInBits() == 128 &&
8346            "unexpected vector size on extract_vector_elt!");
8347     if (Vec.getValueType() == MVT::v4i32)
8348       VecResTy = MVT::v4f32;
8349     else if (Vec.getValueType() == MVT::v2i64)
8350       VecResTy = MVT::v2f64;
8351     else
8352       llvm_unreachable("unexpected vector type!");
8353
8354     SDValue Convert =
8355         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8356     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8357   }
8358   return SDValue();
8359 }
8360
8361 // AArch64 high-vector "long" operations are formed by performing the non-high
8362 // version on an extract_subvector of each operand which gets the high half:
8363 //
8364 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8365 //
8366 // However, there are cases which don't have an extract_high explicitly, but
8367 // have another operation that can be made compatible with one for free. For
8368 // example:
8369 //
8370 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8371 //
8372 // This routine does the actual conversion of such DUPs, once outer routines
8373 // have determined that everything else is in order.
8374 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8375 // similarly here.
8376 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8377   switch (N.getOpcode()) {
8378   case AArch64ISD::DUP:
8379   case AArch64ISD::DUPLANE8:
8380   case AArch64ISD::DUPLANE16:
8381   case AArch64ISD::DUPLANE32:
8382   case AArch64ISD::DUPLANE64:
8383   case AArch64ISD::MOVI:
8384   case AArch64ISD::MOVIshift:
8385   case AArch64ISD::MOVIedit:
8386   case AArch64ISD::MOVImsl:
8387   case AArch64ISD::MVNIshift:
8388   case AArch64ISD::MVNImsl:
8389     break;
8390   default:
8391     // FMOV could be supported, but isn't very useful, as it would only occur
8392     // if you passed a bitcast' floating point immediate to an eligible long
8393     // integer op (addl, smull, ...).
8394     return SDValue();
8395   }
8396
8397   MVT NarrowTy = N.getSimpleValueType();
8398   if (!NarrowTy.is64BitVector())
8399     return SDValue();
8400
8401   MVT ElementTy = NarrowTy.getVectorElementType();
8402   unsigned NumElems = NarrowTy.getVectorNumElements();
8403   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8404
8405   SDLoc dl(N);
8406   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8407                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8408                      DAG.getConstant(NumElems, dl, MVT::i64));
8409 }
8410
8411 static bool isEssentiallyExtractSubvector(SDValue N) {
8412   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8413     return true;
8414
8415   return N.getOpcode() == ISD::BITCAST &&
8416          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8417 }
8418
8419 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8420 struct GenericSetCCInfo {
8421   const SDValue *Opnd0;
8422   const SDValue *Opnd1;
8423   ISD::CondCode CC;
8424 };
8425
8426 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8427 struct AArch64SetCCInfo {
8428   const SDValue *Cmp;
8429   AArch64CC::CondCode CC;
8430 };
8431
8432 /// \brief Helper structure to keep track of SetCC information.
8433 union SetCCInfo {
8434   GenericSetCCInfo Generic;
8435   AArch64SetCCInfo AArch64;
8436 };
8437
8438 /// \brief Helper structure to be able to read SetCC information.  If set to
8439 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8440 /// GenericSetCCInfo.
8441 struct SetCCInfoAndKind {
8442   SetCCInfo Info;
8443   bool IsAArch64;
8444 };
8445
8446 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8447 /// an
8448 /// AArch64 lowered one.
8449 /// \p SetCCInfo is filled accordingly.
8450 /// \post SetCCInfo is meanginfull only when this function returns true.
8451 /// \return True when Op is a kind of SET_CC operation.
8452 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8453   // If this is a setcc, this is straight forward.
8454   if (Op.getOpcode() == ISD::SETCC) {
8455     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8456     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8457     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8458     SetCCInfo.IsAArch64 = false;
8459     return true;
8460   }
8461   // Otherwise, check if this is a matching csel instruction.
8462   // In other words:
8463   // - csel 1, 0, cc
8464   // - csel 0, 1, !cc
8465   if (Op.getOpcode() != AArch64ISD::CSEL)
8466     return false;
8467   // Set the information about the operands.
8468   // TODO: we want the operands of the Cmp not the csel
8469   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8470   SetCCInfo.IsAArch64 = true;
8471   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8472       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8473
8474   // Check that the operands matches the constraints:
8475   // (1) Both operands must be constants.
8476   // (2) One must be 1 and the other must be 0.
8477   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8478   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8479
8480   // Check (1).
8481   if (!TValue || !FValue)
8482     return false;
8483
8484   // Check (2).
8485   if (!TValue->isOne()) {
8486     // Update the comparison when we are interested in !cc.
8487     std::swap(TValue, FValue);
8488     SetCCInfo.Info.AArch64.CC =
8489         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8490   }
8491   return TValue->isOne() && FValue->isNullValue();
8492 }
8493
8494 // Returns true if Op is setcc or zext of setcc.
8495 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8496   if (isSetCC(Op, Info))
8497     return true;
8498   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8499     isSetCC(Op->getOperand(0), Info));
8500 }
8501
8502 // The folding we want to perform is:
8503 // (add x, [zext] (setcc cc ...) )
8504 //   -->
8505 // (csel x, (add x, 1), !cc ...)
8506 //
8507 // The latter will get matched to a CSINC instruction.
8508 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8509   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8510   SDValue LHS = Op->getOperand(0);
8511   SDValue RHS = Op->getOperand(1);
8512   SetCCInfoAndKind InfoAndKind;
8513
8514   // If neither operand is a SET_CC, give up.
8515   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8516     std::swap(LHS, RHS);
8517     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8518       return SDValue();
8519   }
8520
8521   // FIXME: This could be generatized to work for FP comparisons.
8522   EVT CmpVT = InfoAndKind.IsAArch64
8523                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8524                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8525   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8526     return SDValue();
8527
8528   SDValue CCVal;
8529   SDValue Cmp;
8530   SDLoc dl(Op);
8531   if (InfoAndKind.IsAArch64) {
8532     CCVal = DAG.getConstant(
8533         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8534         MVT::i32);
8535     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8536   } else
8537     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8538                       *InfoAndKind.Info.Generic.Opnd1,
8539                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8540                       CCVal, DAG, dl);
8541
8542   EVT VT = Op->getValueType(0);
8543   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8544   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8545 }
8546
8547 // The basic add/sub long vector instructions have variants with "2" on the end
8548 // which act on the high-half of their inputs. They are normally matched by
8549 // patterns like:
8550 //
8551 // (add (zeroext (extract_high LHS)),
8552 //      (zeroext (extract_high RHS)))
8553 // -> uaddl2 vD, vN, vM
8554 //
8555 // However, if one of the extracts is something like a duplicate, this
8556 // instruction can still be used profitably. This function puts the DAG into a
8557 // more appropriate form for those patterns to trigger.
8558 static SDValue performAddSubLongCombine(SDNode *N,
8559                                         TargetLowering::DAGCombinerInfo &DCI,
8560                                         SelectionDAG &DAG) {
8561   if (DCI.isBeforeLegalizeOps())
8562     return SDValue();
8563
8564   MVT VT = N->getSimpleValueType(0);
8565   if (!VT.is128BitVector()) {
8566     if (N->getOpcode() == ISD::ADD)
8567       return performSetccAddFolding(N, DAG);
8568     return SDValue();
8569   }
8570
8571   // Make sure both branches are extended in the same way.
8572   SDValue LHS = N->getOperand(0);
8573   SDValue RHS = N->getOperand(1);
8574   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8575        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8576       LHS.getOpcode() != RHS.getOpcode())
8577     return SDValue();
8578
8579   unsigned ExtType = LHS.getOpcode();
8580
8581   // It's not worth doing if at least one of the inputs isn't already an
8582   // extract, but we don't know which it'll be so we have to try both.
8583   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8584     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8585     if (!RHS.getNode())
8586       return SDValue();
8587
8588     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8589   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8590     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8591     if (!LHS.getNode())
8592       return SDValue();
8593
8594     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8595   }
8596
8597   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8598 }
8599
8600 // Massage DAGs which we can use the high-half "long" operations on into
8601 // something isel will recognize better. E.g.
8602 //
8603 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8604 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8605 //                     (extract_high (v2i64 (dup128 scalar)))))
8606 //
8607 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8608                                        TargetLowering::DAGCombinerInfo &DCI,
8609                                        SelectionDAG &DAG) {
8610   if (DCI.isBeforeLegalizeOps())
8611     return SDValue();
8612
8613   SDValue LHS = N->getOperand(1);
8614   SDValue RHS = N->getOperand(2);
8615   assert(LHS.getValueType().is64BitVector() &&
8616          RHS.getValueType().is64BitVector() &&
8617          "unexpected shape for long operation");
8618
8619   // Either node could be a DUP, but it's not worth doing both of them (you'd
8620   // just as well use the non-high version) so look for a corresponding extract
8621   // operation on the other "wing".
8622   if (isEssentiallyExtractSubvector(LHS)) {
8623     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8624     if (!RHS.getNode())
8625       return SDValue();
8626   } else if (isEssentiallyExtractSubvector(RHS)) {
8627     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8628     if (!LHS.getNode())
8629       return SDValue();
8630   }
8631
8632   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8633                      N->getOperand(0), LHS, RHS);
8634 }
8635
8636 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8637   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8638   unsigned ElemBits = ElemTy.getSizeInBits();
8639
8640   int64_t ShiftAmount;
8641   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8642     APInt SplatValue, SplatUndef;
8643     unsigned SplatBitSize;
8644     bool HasAnyUndefs;
8645     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8646                               HasAnyUndefs, ElemBits) ||
8647         SplatBitSize != ElemBits)
8648       return SDValue();
8649
8650     ShiftAmount = SplatValue.getSExtValue();
8651   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8652     ShiftAmount = CVN->getSExtValue();
8653   } else
8654     return SDValue();
8655
8656   unsigned Opcode;
8657   bool IsRightShift;
8658   switch (IID) {
8659   default:
8660     llvm_unreachable("Unknown shift intrinsic");
8661   case Intrinsic::aarch64_neon_sqshl:
8662     Opcode = AArch64ISD::SQSHL_I;
8663     IsRightShift = false;
8664     break;
8665   case Intrinsic::aarch64_neon_uqshl:
8666     Opcode = AArch64ISD::UQSHL_I;
8667     IsRightShift = false;
8668     break;
8669   case Intrinsic::aarch64_neon_srshl:
8670     Opcode = AArch64ISD::SRSHR_I;
8671     IsRightShift = true;
8672     break;
8673   case Intrinsic::aarch64_neon_urshl:
8674     Opcode = AArch64ISD::URSHR_I;
8675     IsRightShift = true;
8676     break;
8677   case Intrinsic::aarch64_neon_sqshlu:
8678     Opcode = AArch64ISD::SQSHLU_I;
8679     IsRightShift = false;
8680     break;
8681   }
8682
8683   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8684     SDLoc dl(N);
8685     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8686                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8687   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8688     SDLoc dl(N);
8689     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8690                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8691   }
8692
8693   return SDValue();
8694 }
8695
8696 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8697 // the intrinsics must be legal and take an i32, this means there's almost
8698 // certainly going to be a zext in the DAG which we can eliminate.
8699 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8700   SDValue AndN = N->getOperand(2);
8701   if (AndN.getOpcode() != ISD::AND)
8702     return SDValue();
8703
8704   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8705   if (!CMask || CMask->getZExtValue() != Mask)
8706     return SDValue();
8707
8708   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8709                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8710 }
8711
8712 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8713                                            SelectionDAG &DAG) {
8714   SDLoc dl(N);
8715   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8716                      DAG.getNode(Opc, dl,
8717                                  N->getOperand(1).getSimpleValueType(),
8718                                  N->getOperand(1)),
8719                      DAG.getConstant(0, dl, MVT::i64));
8720 }
8721
8722 static SDValue performIntrinsicCombine(SDNode *N,
8723                                        TargetLowering::DAGCombinerInfo &DCI,
8724                                        const AArch64Subtarget *Subtarget) {
8725   SelectionDAG &DAG = DCI.DAG;
8726   unsigned IID = getIntrinsicID(N);
8727   switch (IID) {
8728   default:
8729     break;
8730   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8731   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8732     return tryCombineFixedPointConvert(N, DCI, DAG);
8733   case Intrinsic::aarch64_neon_saddv:
8734     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8735   case Intrinsic::aarch64_neon_uaddv:
8736     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8737   case Intrinsic::aarch64_neon_sminv:
8738     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8739   case Intrinsic::aarch64_neon_uminv:
8740     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8741   case Intrinsic::aarch64_neon_smaxv:
8742     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8743   case Intrinsic::aarch64_neon_umaxv:
8744     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8745   case Intrinsic::aarch64_neon_fmax:
8746     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8747                        N->getOperand(1), N->getOperand(2));
8748   case Intrinsic::aarch64_neon_fmin:
8749     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8750                        N->getOperand(1), N->getOperand(2));
8751   case Intrinsic::aarch64_neon_fmaxnm:
8752     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8753                        N->getOperand(1), N->getOperand(2));
8754   case Intrinsic::aarch64_neon_fminnm:
8755     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8756                        N->getOperand(1), N->getOperand(2));
8757   case Intrinsic::aarch64_neon_smull:
8758   case Intrinsic::aarch64_neon_umull:
8759   case Intrinsic::aarch64_neon_pmull:
8760   case Intrinsic::aarch64_neon_sqdmull:
8761     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8762   case Intrinsic::aarch64_neon_sqshl:
8763   case Intrinsic::aarch64_neon_uqshl:
8764   case Intrinsic::aarch64_neon_sqshlu:
8765   case Intrinsic::aarch64_neon_srshl:
8766   case Intrinsic::aarch64_neon_urshl:
8767     return tryCombineShiftImm(IID, N, DAG);
8768   case Intrinsic::aarch64_crc32b:
8769   case Intrinsic::aarch64_crc32cb:
8770     return tryCombineCRC32(0xff, N, DAG);
8771   case Intrinsic::aarch64_crc32h:
8772   case Intrinsic::aarch64_crc32ch:
8773     return tryCombineCRC32(0xffff, N, DAG);
8774   }
8775   return SDValue();
8776 }
8777
8778 static SDValue performExtendCombine(SDNode *N,
8779                                     TargetLowering::DAGCombinerInfo &DCI,
8780                                     SelectionDAG &DAG) {
8781   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8782   // we can convert that DUP into another extract_high (of a bigger DUP), which
8783   // helps the backend to decide that an sabdl2 would be useful, saving a real
8784   // extract_high operation.
8785   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8786       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8787     SDNode *ABDNode = N->getOperand(0).getNode();
8788     unsigned IID = getIntrinsicID(ABDNode);
8789     if (IID == Intrinsic::aarch64_neon_sabd ||
8790         IID == Intrinsic::aarch64_neon_uabd) {
8791       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8792       if (!NewABD.getNode())
8793         return SDValue();
8794
8795       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8796                          NewABD);
8797     }
8798   }
8799
8800   // This is effectively a custom type legalization for AArch64.
8801   //
8802   // Type legalization will split an extend of a small, legal, type to a larger
8803   // illegal type by first splitting the destination type, often creating
8804   // illegal source types, which then get legalized in isel-confusing ways,
8805   // leading to really terrible codegen. E.g.,
8806   //   %result = v8i32 sext v8i8 %value
8807   // becomes
8808   //   %losrc = extract_subreg %value, ...
8809   //   %hisrc = extract_subreg %value, ...
8810   //   %lo = v4i32 sext v4i8 %losrc
8811   //   %hi = v4i32 sext v4i8 %hisrc
8812   // Things go rapidly downhill from there.
8813   //
8814   // For AArch64, the [sz]ext vector instructions can only go up one element
8815   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8816   // take two instructions.
8817   //
8818   // This implies that the most efficient way to do the extend from v8i8
8819   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8820   // the normal splitting to happen for the v8i16->v8i32.
8821
8822   // This is pre-legalization to catch some cases where the default
8823   // type legalization will create ill-tempered code.
8824   if (!DCI.isBeforeLegalizeOps())
8825     return SDValue();
8826
8827   // We're only interested in cleaning things up for non-legal vector types
8828   // here. If both the source and destination are legal, things will just
8829   // work naturally without any fiddling.
8830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8831   EVT ResVT = N->getValueType(0);
8832   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8833     return SDValue();
8834   // If the vector type isn't a simple VT, it's beyond the scope of what
8835   // we're  worried about here. Let legalization do its thing and hope for
8836   // the best.
8837   SDValue Src = N->getOperand(0);
8838   EVT SrcVT = Src->getValueType(0);
8839   if (!ResVT.isSimple() || !SrcVT.isSimple())
8840     return SDValue();
8841
8842   // If the source VT is a 64-bit vector, we can play games and get the
8843   // better results we want.
8844   if (SrcVT.getSizeInBits() != 64)
8845     return SDValue();
8846
8847   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8848   unsigned ElementCount = SrcVT.getVectorNumElements();
8849   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8850   SDLoc DL(N);
8851   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8852
8853   // Now split the rest of the operation into two halves, each with a 64
8854   // bit source.
8855   EVT LoVT, HiVT;
8856   SDValue Lo, Hi;
8857   unsigned NumElements = ResVT.getVectorNumElements();
8858   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8859   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8860                                  ResVT.getVectorElementType(), NumElements / 2);
8861
8862   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8863                                LoVT.getVectorNumElements());
8864   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8865                    DAG.getConstant(0, DL, MVT::i64));
8866   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8867                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8868   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8869   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8870
8871   // Now combine the parts back together so we still have a single result
8872   // like the combiner expects.
8873   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8874 }
8875
8876 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8877                                SDValue SplatVal, unsigned NumVecElts) {
8878   unsigned OrigAlignment = St.getAlignment();
8879   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
8880
8881   // Create scalar stores. This is at least as good as the code sequence for a
8882   // split unaligned store which is a dup.s, ext.b, and two stores.
8883   // Most of the time the three stores should be replaced by store pair
8884   // instructions (stp).
8885   SDLoc DL(&St);
8886   SDValue BasePtr = St.getBasePtr();
8887   SDValue NewST1 =
8888       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(),
8889                    OrigAlignment, St.getMemOperand()->getFlags());
8890
8891   unsigned Offset = EltOffset;
8892   while (--NumVecElts) {
8893     unsigned Alignment = MinAlign(OrigAlignment, Offset);
8894     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8895                                     DAG.getConstant(Offset, DL, MVT::i64));
8896     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8897                           St.getPointerInfo(), Alignment,
8898                           St.getMemOperand()->getFlags());
8899     Offset += EltOffset;
8900   }
8901   return NewST1;
8902 }
8903
8904 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
8905 /// load store optimizer pass will merge them to store pair stores.  This should
8906 /// be better than a movi to create the vector zero followed by a vector store
8907 /// if the zero constant is not re-used, since one instructions and one register
8908 /// live range will be removed.
8909 ///
8910 /// For example, the final generated code should be:
8911 ///
8912 ///   stp xzr, xzr, [x0]
8913 ///
8914 /// instead of:
8915 ///
8916 ///   movi v0.2d, #0
8917 ///   str q0, [x0]
8918 ///
8919 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8920   SDValue StVal = St.getValue();
8921   EVT VT = StVal.getValueType();
8922
8923   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8924   // 2, 3 or 4 i32 elements.
8925   int NumVecElts = VT.getVectorNumElements();
8926   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8927          VT.getVectorElementType().getSizeInBits() == 64) ||
8928         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8929          VT.getVectorElementType().getSizeInBits() == 32)))
8930     return SDValue();
8931
8932   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8933     return SDValue();
8934
8935   // If the zero constant has more than one use then the vector store could be
8936   // better since the constant mov will be amortized and stp q instructions
8937   // should be able to be formed.
8938   if (!StVal.hasOneUse())
8939     return SDValue();
8940
8941   // If the immediate offset of the address operand is too large for the stp
8942   // instruction, then bail out.
8943   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8944     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
8945     if (Offset < -512 || Offset > 504)
8946       return SDValue();
8947   }
8948
8949   for (int I = 0; I < NumVecElts; ++I) {
8950     SDValue EltVal = StVal.getOperand(I);
8951     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
8952       return SDValue();
8953   }
8954
8955   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
8956   // undoing this transformation.
8957   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
8958                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
8959                          : DAG.getRegister(AArch64::XZR, MVT::i64);
8960   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
8961 }
8962
8963 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8964 /// value. The load store optimizer pass will merge them to store pair stores.
8965 /// This has better performance than a splat of the scalar followed by a split
8966 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8967 /// followed by an ext.b and two stores.
8968 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8969   SDValue StVal = St.getValue();
8970   EVT VT = StVal.getValueType();
8971
8972   // Don't replace floating point stores, they possibly won't be transformed to
8973   // stp because of the store pair suppress pass.
8974   if (VT.isFloatingPoint())
8975     return SDValue();
8976
8977   // We can express a splat as store pair(s) for 2 or 4 elements.
8978   unsigned NumVecElts = VT.getVectorNumElements();
8979   if (NumVecElts != 4 && NumVecElts != 2)
8980     return SDValue();
8981
8982   // Check that this is a splat.
8983   // Make sure that each of the relevant vector element locations are inserted
8984   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
8985   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
8986   SDValue SplatVal;
8987   for (unsigned I = 0; I < NumVecElts; ++I) {
8988     // Check for insert vector elements.
8989     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8990       return SDValue();
8991
8992     // Check that same value is inserted at each vector element.
8993     if (I == 0)
8994       SplatVal = StVal.getOperand(1);
8995     else if (StVal.getOperand(1) != SplatVal)
8996       return SDValue();
8997
8998     // Check insert element index.
8999     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9000     if (!CIndex)
9001       return SDValue();
9002     uint64_t IndexVal = CIndex->getZExtValue();
9003     if (IndexVal >= NumVecElts)
9004       return SDValue();
9005     IndexNotInserted.reset(IndexVal);
9006
9007     StVal = StVal.getOperand(0);
9008   }
9009   // Check that all vector element locations were inserted to.
9010   if (IndexNotInserted.any())
9011       return SDValue();
9012
9013   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9014 }
9015
9016 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9017                            SelectionDAG &DAG,
9018                            const AArch64Subtarget *Subtarget) {
9019   if (!DCI.isBeforeLegalize())
9020     return SDValue();
9021
9022   StoreSDNode *S = cast<StoreSDNode>(N);
9023   if (S->isVolatile())
9024     return SDValue();
9025
9026   SDValue StVal = S->getValue();
9027   EVT VT = StVal.getValueType();
9028   if (!VT.isVector())
9029     return SDValue();
9030
9031   // If we get a splat of zeros, convert this vector store to a store of
9032   // scalars. They will be merged into store pairs of xzr thereby removing one
9033   // instruction and one register.
9034   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9035     return ReplacedZeroSplat;
9036
9037   // FIXME: The logic for deciding if an unaligned store should be split should
9038   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9039   // a call to that function here.
9040
9041   if (!Subtarget->isMisaligned128StoreSlow())
9042     return SDValue();
9043
9044   // Don't split at -Oz.
9045   if (DAG.getMachineFunction().getFunction()->optForMinSize())
9046     return SDValue();
9047
9048   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9049   // those up regresses performance on micro-benchmarks and olden/bh.
9050   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9051     return SDValue();
9052
9053   // Split unaligned 16B stores. They are terrible for performance.
9054   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9055   // extensions can use this to mark that it does not want splitting to happen
9056   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9057   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9058   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9059       S->getAlignment() <= 2)
9060     return SDValue();
9061
9062   // If we get a splat of a scalar convert this vector store to a store of
9063   // scalars. They will be merged into store pairs thereby removing two
9064   // instructions.
9065   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9066     return ReplacedSplat;
9067
9068   SDLoc DL(S);
9069   unsigned NumElts = VT.getVectorNumElements() / 2;
9070   // Split VT into two.
9071   EVT HalfVT =
9072       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9073   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9074                                    DAG.getConstant(0, DL, MVT::i64));
9075   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9076                                    DAG.getConstant(NumElts, DL, MVT::i64));
9077   SDValue BasePtr = S->getBasePtr();
9078   SDValue NewST1 =
9079       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9080                    S->getAlignment(), S->getMemOperand()->getFlags());
9081   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9082                                   DAG.getConstant(8, DL, MVT::i64));
9083   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9084                       S->getPointerInfo(), S->getAlignment(),
9085                       S->getMemOperand()->getFlags());
9086 }
9087
9088 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9089 /// post-increment LD1R.
9090 static SDValue performPostLD1Combine(SDNode *N,
9091                                      TargetLowering::DAGCombinerInfo &DCI,
9092                                      bool IsLaneOp) {
9093   if (DCI.isBeforeLegalizeOps())
9094     return SDValue();
9095
9096   SelectionDAG &DAG = DCI.DAG;
9097   EVT VT = N->getValueType(0);
9098
9099   unsigned LoadIdx = IsLaneOp ? 1 : 0;
9100   SDNode *LD = N->getOperand(LoadIdx).getNode();
9101   // If it is not LOAD, can not do such combine.
9102   if (LD->getOpcode() != ISD::LOAD)
9103     return SDValue();
9104
9105   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9106   EVT MemVT = LoadSDN->getMemoryVT();
9107   // Check if memory operand is the same type as the vector element.
9108   if (MemVT != VT.getVectorElementType())
9109     return SDValue();
9110
9111   // Check if there are other uses. If so, do not combine as it will introduce
9112   // an extra load.
9113   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9114        ++UI) {
9115     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9116       continue;
9117     if (*UI != N)
9118       return SDValue();
9119   }
9120
9121   SDValue Addr = LD->getOperand(1);
9122   SDValue Vector = N->getOperand(0);
9123   // Search for a use of the address operand that is an increment.
9124   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9125        Addr.getNode()->use_end(); UI != UE; ++UI) {
9126     SDNode *User = *UI;
9127     if (User->getOpcode() != ISD::ADD
9128         || UI.getUse().getResNo() != Addr.getResNo())
9129       continue;
9130
9131     // Check that the add is independent of the load.  Otherwise, folding it
9132     // would create a cycle.
9133     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9134       continue;
9135     // Also check that add is not used in the vector operand.  This would also
9136     // create a cycle.
9137     if (User->isPredecessorOf(Vector.getNode()))
9138       continue;
9139
9140     // If the increment is a constant, it must match the memory ref size.
9141     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9142     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9143       uint32_t IncVal = CInc->getZExtValue();
9144       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9145       if (IncVal != NumBytes)
9146         continue;
9147       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9148     }
9149
9150     // Finally, check that the vector doesn't depend on the load.
9151     // Again, this would create a cycle.
9152     // The load depending on the vector is fine, as that's the case for the
9153     // LD1*post we'll eventually generate anyway.
9154     if (LoadSDN->isPredecessorOf(Vector.getNode()))
9155       continue;
9156
9157     SmallVector<SDValue, 8> Ops;
9158     Ops.push_back(LD->getOperand(0));  // Chain
9159     if (IsLaneOp) {
9160       Ops.push_back(Vector);           // The vector to be inserted
9161       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9162     }
9163     Ops.push_back(Addr);
9164     Ops.push_back(Inc);
9165
9166     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9167     SDVTList SDTys = DAG.getVTList(Tys);
9168     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9169     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9170                                            MemVT,
9171                                            LoadSDN->getMemOperand());
9172
9173     // Update the uses.
9174     SDValue NewResults[] = {
9175         SDValue(LD, 0),            // The result of load
9176         SDValue(UpdN.getNode(), 2) // Chain
9177     };
9178     DCI.CombineTo(LD, NewResults);
9179     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
9180     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
9181
9182     break;
9183   }
9184   return SDValue();
9185 }
9186
9187 /// Simplify \Addr given that the top byte of it is ignored by HW during
9188 /// address translation.
9189 static bool performTBISimplification(SDValue Addr,
9190                                      TargetLowering::DAGCombinerInfo &DCI,
9191                                      SelectionDAG &DAG) {
9192   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9193   APInt KnownZero, KnownOne;
9194   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9195                                         DCI.isBeforeLegalizeOps());
9196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9197   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9198     DCI.CommitTargetLoweringOpt(TLO);
9199     return true;
9200   }
9201   return false;
9202 }
9203
9204 static SDValue performSTORECombine(SDNode *N,
9205                                    TargetLowering::DAGCombinerInfo &DCI,
9206                                    SelectionDAG &DAG,
9207                                    const AArch64Subtarget *Subtarget) {
9208   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9209     return Split;
9210
9211   if (Subtarget->supportsAddressTopByteIgnored() &&
9212       performTBISimplification(N->getOperand(2), DCI, DAG))
9213     return SDValue(N, 0);
9214
9215   return SDValue();
9216 }
9217
9218   /// This function handles the log2-shuffle pattern produced by the
9219 /// LoopVectorizer for the across vector reduction. It consists of
9220 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9221 /// are reduced, where s is an induction variable from 0 to
9222 /// log2(NumVectorElements).
9223 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9224                                                      unsigned Op,
9225                                                      SelectionDAG &DAG) {
9226   EVT VTy = OpV->getOperand(0).getValueType();
9227   if (!VTy.isVector())
9228     return SDValue();
9229
9230   int NumVecElts = VTy.getVectorNumElements();
9231   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9232     if (NumVecElts != 4)
9233       return SDValue();
9234   } else {
9235     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9236       return SDValue();
9237   }
9238
9239   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9240   SDValue PreOp = OpV;
9241   // Iterate over each step of the across vector reduction.
9242   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9243     SDValue CurOp = PreOp.getOperand(0);
9244     SDValue Shuffle = PreOp.getOperand(1);
9245     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9246       // Try to swap the 1st and 2nd operand as add and min/max instructions
9247       // are commutative.
9248       CurOp = PreOp.getOperand(1);
9249       Shuffle = PreOp.getOperand(0);
9250       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9251         return SDValue();
9252     }
9253
9254     // Check if the input vector is fed by the operator we want to handle,
9255     // except the last step; the very first input vector is not necessarily
9256     // the same operator we are handling.
9257     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9258       return SDValue();
9259
9260     // Check if it forms one step of the across vector reduction.
9261     // E.g.,
9262     //   %cur = add %1, %0
9263     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
9264     //   %pre = add %cur, %shuffle
9265     if (Shuffle.getOperand(0) != CurOp)
9266       return SDValue();
9267
9268     int NumMaskElts = 1 << CurStep;
9269     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9270     // Check mask values in each step.
9271     // We expect the shuffle mask in each step follows a specific pattern
9272     // denoted here by the <M, U> form, where M is a sequence of integers
9273     // starting from NumMaskElts, increasing by 1, and the number integers
9274     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9275     // of undef in U should be NumVecElts - NumMaskElts.
9276     // E.g., for <8 x i16>, mask values in each step should be :
9277     //   step 0 : <1,u,u,u,u,u,u,u>
9278     //   step 1 : <2,3,u,u,u,u,u,u>
9279     //   step 2 : <4,5,6,7,u,u,u,u>
9280     for (int i = 0; i < NumVecElts; ++i)
9281       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9282           (i >= NumMaskElts && !(Mask[i] < 0)))
9283         return SDValue();
9284
9285     PreOp = CurOp;
9286   }
9287   unsigned Opcode;
9288   bool IsIntrinsic = false;
9289
9290   switch (Op) {
9291   default:
9292     llvm_unreachable("Unexpected operator for across vector reduction");
9293   case ISD::ADD:
9294     Opcode = AArch64ISD::UADDV;
9295     break;
9296   case ISD::SMAX:
9297     Opcode = AArch64ISD::SMAXV;
9298     break;
9299   case ISD::UMAX:
9300     Opcode = AArch64ISD::UMAXV;
9301     break;
9302   case ISD::SMIN:
9303     Opcode = AArch64ISD::SMINV;
9304     break;
9305   case ISD::UMIN:
9306     Opcode = AArch64ISD::UMINV;
9307     break;
9308   case ISD::FMAXNUM:
9309     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9310     IsIntrinsic = true;
9311     break;
9312   case ISD::FMINNUM:
9313     Opcode = Intrinsic::aarch64_neon_fminnmv;
9314     IsIntrinsic = true;
9315     break;
9316   }
9317   SDLoc DL(N);
9318
9319   return IsIntrinsic
9320              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9321                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9322              : DAG.getNode(
9323                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9324                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9325                    DAG.getConstant(0, DL, MVT::i64));
9326 }
9327
9328 /// Target-specific DAG combine for the across vector min/max reductions.
9329 /// This function specifically handles the final clean-up step of the vector
9330 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9331 /// pattern, which narrows down and finds the final min/max value from all
9332 /// elements of the vector.
9333 /// For example, for a <16 x i8> vector :
9334 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9335 ///   %smax0 = smax %arr, svn0
9336 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9337 ///   %smax1 = smax %smax0, %svn1
9338 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9339 ///   %smax2 = smax %smax1, svn2
9340 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9341 ///   %sc = setcc %smax2, %svn3, gt
9342 ///   %n0 = extract_vector_elt %sc, #0
9343 ///   %n1 = extract_vector_elt %smax2, #0
9344 ///   %n2 = extract_vector_elt $smax2, #1
9345 ///   %result = select %n0, %n1, n2
9346 ///     becomes :
9347 ///   %1 = smaxv %0
9348 ///   %result = extract_vector_elt %1, 0
9349 static SDValue
9350 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9351                                         const AArch64Subtarget *Subtarget) {
9352   if (!Subtarget->hasNEON())
9353     return SDValue();
9354
9355   SDValue N0 = N->getOperand(0);
9356   SDValue IfTrue = N->getOperand(1);
9357   SDValue IfFalse = N->getOperand(2);
9358
9359   // Check if the SELECT merges up the final result of the min/max
9360   // from a vector.
9361   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9362       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9363       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9364     return SDValue();
9365
9366   // Expect N0 is fed by SETCC.
9367   SDValue SetCC = N0.getOperand(0);
9368   EVT SetCCVT = SetCC.getValueType();
9369   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9370       SetCCVT.getVectorElementType() != MVT::i1)
9371     return SDValue();
9372
9373   SDValue VectorOp = SetCC.getOperand(0);
9374   unsigned Op = VectorOp->getOpcode();
9375   // Check if the input vector is fed by the operator we want to handle.
9376   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9377       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9378     return SDValue();
9379
9380   EVT VTy = VectorOp.getValueType();
9381   if (!VTy.isVector())
9382     return SDValue();
9383
9384   if (VTy.getSizeInBits() < 64)
9385     return SDValue();
9386
9387   EVT EltTy = VTy.getVectorElementType();
9388   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9389     if (EltTy != MVT::f32)
9390       return SDValue();
9391   } else {
9392     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9393       return SDValue();
9394   }
9395
9396   // Check if extracting from the same vector.
9397   // For example,
9398   //   %sc = setcc %vector, %svn1, gt
9399   //   %n0 = extract_vector_elt %sc, #0
9400   //   %n1 = extract_vector_elt %vector, #0
9401   //   %n2 = extract_vector_elt $vector, #1
9402   if (!(VectorOp == IfTrue->getOperand(0) &&
9403         VectorOp == IfFalse->getOperand(0)))
9404     return SDValue();
9405
9406   // Check if the condition code is matched with the operator type.
9407   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9408   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9409       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9410       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9411       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9412       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9413        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9414        CC != ISD::SETGE) ||
9415       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9416        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9417        CC != ISD::SETLE))
9418     return SDValue();
9419
9420   // Expect to check only lane 0 from the vector SETCC.
9421   if (!isNullConstant(N0.getOperand(1)))
9422     return SDValue();
9423
9424   // Expect to extract the true value from lane 0.
9425   if (!isNullConstant(IfTrue.getOperand(1)))
9426     return SDValue();
9427
9428   // Expect to extract the false value from lane 1.
9429   if (!isOneConstant(IfFalse.getOperand(1)))
9430     return SDValue();
9431
9432   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9433 }
9434
9435 /// Target-specific DAG combine for the across vector add reduction.
9436 /// This function specifically handles the final clean-up step of the vector
9437 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9438 /// pattern, which adds all elements of a vector together.
9439 /// For example, for a <4 x i32> vector :
9440 ///   %1 = vector_shuffle %0, <2,3,u,u>
9441 ///   %2 = add %0, %1
9442 ///   %3 = vector_shuffle %2, <1,u,u,u>
9443 ///   %4 = add %2, %3
9444 ///   %result = extract_vector_elt %4, 0
9445 /// becomes :
9446 ///   %0 = uaddv %0
9447 ///   %result = extract_vector_elt %0, 0
9448 static SDValue
9449 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9450                                      const AArch64Subtarget *Subtarget) {
9451   if (!Subtarget->hasNEON())
9452     return SDValue();
9453   SDValue N0 = N->getOperand(0);
9454   SDValue N1 = N->getOperand(1);
9455
9456   // Check if the input vector is fed by the ADD.
9457   if (N0->getOpcode() != ISD::ADD)
9458     return SDValue();
9459
9460   // The vector extract idx must constant zero because we only expect the final
9461   // result of the reduction is placed in lane 0.
9462   if (!isNullConstant(N1))
9463     return SDValue();
9464
9465   EVT VTy = N0.getValueType();
9466   if (!VTy.isVector())
9467     return SDValue();
9468
9469   EVT EltTy = VTy.getVectorElementType();
9470   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9471     return SDValue();
9472
9473   if (VTy.getSizeInBits() < 64)
9474     return SDValue();
9475
9476   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9477 }
9478
9479 /// Target-specific DAG combine function for NEON load/store intrinsics
9480 /// to merge base address updates.
9481 static SDValue performNEONPostLDSTCombine(SDNode *N,
9482                                           TargetLowering::DAGCombinerInfo &DCI,
9483                                           SelectionDAG &DAG) {
9484   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9485     return SDValue();
9486
9487   unsigned AddrOpIdx = N->getNumOperands() - 1;
9488   SDValue Addr = N->getOperand(AddrOpIdx);
9489
9490   // Search for a use of the address operand that is an increment.
9491   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9492        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9493     SDNode *User = *UI;
9494     if (User->getOpcode() != ISD::ADD ||
9495         UI.getUse().getResNo() != Addr.getResNo())
9496       continue;
9497
9498     // Check that the add is independent of the load/store.  Otherwise, folding
9499     // it would create a cycle.
9500     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9501       continue;
9502
9503     // Find the new opcode for the updating load/store.
9504     bool IsStore = false;
9505     bool IsLaneOp = false;
9506     bool IsDupOp = false;
9507     unsigned NewOpc = 0;
9508     unsigned NumVecs = 0;
9509     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9510     switch (IntNo) {
9511     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9512     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9513       NumVecs = 2; break;
9514     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9515       NumVecs = 3; break;
9516     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9517       NumVecs = 4; break;
9518     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9519       NumVecs = 2; IsStore = true; break;
9520     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9521       NumVecs = 3; IsStore = true; break;
9522     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9523       NumVecs = 4; IsStore = true; break;
9524     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9525       NumVecs = 2; break;
9526     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9527       NumVecs = 3; break;
9528     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9529       NumVecs = 4; break;
9530     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9531       NumVecs = 2; IsStore = true; break;
9532     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9533       NumVecs = 3; IsStore = true; break;
9534     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9535       NumVecs = 4; IsStore = true; break;
9536     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9537       NumVecs = 2; IsDupOp = true; break;
9538     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9539       NumVecs = 3; IsDupOp = true; break;
9540     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9541       NumVecs = 4; IsDupOp = true; break;
9542     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9543       NumVecs = 2; IsLaneOp = true; break;
9544     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9545       NumVecs = 3; IsLaneOp = true; break;
9546     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9547       NumVecs = 4; IsLaneOp = true; break;
9548     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9549       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9550     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9551       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9552     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9553       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9554     }
9555
9556     EVT VecTy;
9557     if (IsStore)
9558       VecTy = N->getOperand(2).getValueType();
9559     else
9560       VecTy = N->getValueType(0);
9561
9562     // If the increment is a constant, it must match the memory ref size.
9563     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9564     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9565       uint32_t IncVal = CInc->getZExtValue();
9566       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9567       if (IsLaneOp || IsDupOp)
9568         NumBytes /= VecTy.getVectorNumElements();
9569       if (IncVal != NumBytes)
9570         continue;
9571       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9572     }
9573     SmallVector<SDValue, 8> Ops;
9574     Ops.push_back(N->getOperand(0)); // Incoming chain
9575     // Load lane and store have vector list as input.
9576     if (IsLaneOp || IsStore)
9577       for (unsigned i = 2; i < AddrOpIdx; ++i)
9578         Ops.push_back(N->getOperand(i));
9579     Ops.push_back(Addr); // Base register
9580     Ops.push_back(Inc);
9581
9582     // Return Types.
9583     EVT Tys[6];
9584     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9585     unsigned n;
9586     for (n = 0; n < NumResultVecs; ++n)
9587       Tys[n] = VecTy;
9588     Tys[n++] = MVT::i64;  // Type of write back register
9589     Tys[n] = MVT::Other;  // Type of the chain
9590     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9591
9592     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9593     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9594                                            MemInt->getMemoryVT(),
9595                                            MemInt->getMemOperand());
9596
9597     // Update the uses.
9598     std::vector<SDValue> NewResults;
9599     for (unsigned i = 0; i < NumResultVecs; ++i) {
9600       NewResults.push_back(SDValue(UpdN.getNode(), i));
9601     }
9602     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9603     DCI.CombineTo(N, NewResults);
9604     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9605
9606     break;
9607   }
9608   return SDValue();
9609 }
9610
9611 // Checks to see if the value is the prescribed width and returns information
9612 // about its extension mode.
9613 static
9614 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9615   ExtType = ISD::NON_EXTLOAD;
9616   switch(V.getNode()->getOpcode()) {
9617   default:
9618     return false;
9619   case ISD::LOAD: {
9620     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9621     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9622        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9623       ExtType = LoadNode->getExtensionType();
9624       return true;
9625     }
9626     return false;
9627   }
9628   case ISD::AssertSext: {
9629     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9630     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9631        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9632       ExtType = ISD::SEXTLOAD;
9633       return true;
9634     }
9635     return false;
9636   }
9637   case ISD::AssertZext: {
9638     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9639     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9640        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9641       ExtType = ISD::ZEXTLOAD;
9642       return true;
9643     }
9644     return false;
9645   }
9646   case ISD::Constant:
9647   case ISD::TargetConstant: {
9648     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9649            1LL << (width - 1);
9650   }
9651   }
9652
9653   return true;
9654 }
9655
9656 // This function does a whole lot of voodoo to determine if the tests are
9657 // equivalent without and with a mask. Essentially what happens is that given a
9658 // DAG resembling:
9659 //
9660 //  +-------------+ +-------------+ +-------------+ +-------------+
9661 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9662 //  +-------------+ +-------------+ +-------------+ +-------------+
9663 //           |           |           |               |
9664 //           V           V           |    +----------+
9665 //          +-------------+  +----+  |    |
9666 //          |     ADD     |  |0xff|  |    |
9667 //          +-------------+  +----+  |    |
9668 //                  |           |    |    |
9669 //                  V           V    |    |
9670 //                 +-------------+   |    |
9671 //                 |     AND     |   |    |
9672 //                 +-------------+   |    |
9673 //                      |            |    |
9674 //                      +-----+      |    |
9675 //                            |      |    |
9676 //                            V      V    V
9677 //                           +-------------+
9678 //                           |     CMP     |
9679 //                           +-------------+
9680 //
9681 // The AND node may be safely removed for some combinations of inputs. In
9682 // particular we need to take into account the extension type of the Input,
9683 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9684 // width of the input (this can work for any width inputs, the above graph is
9685 // specific to 8 bits.
9686 //
9687 // The specific equations were worked out by generating output tables for each
9688 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9689 // problem was simplified by working with 4 bit inputs, which means we only
9690 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9691 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9692 // patterns present in both extensions (0,7). For every distinct set of
9693 // AddConstant and CompConstants bit patterns we can consider the masked and
9694 // unmasked versions to be equivalent if the result of this function is true for
9695 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9696 //
9697 //   sub      w8, w0, w1
9698 //   and      w10, w8, #0x0f
9699 //   cmp      w8, w2
9700 //   cset     w9, AArch64CC
9701 //   cmp      w10, w2
9702 //   cset     w11, AArch64CC
9703 //   cmp      w9, w11
9704 //   cset     w0, eq
9705 //   ret
9706 //
9707 // Since the above function shows when the outputs are equivalent it defines
9708 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9709 // would be expensive to run during compiles. The equations below were written
9710 // in a test harness that confirmed they gave equivalent outputs to the above
9711 // for all inputs function, so they can be used determine if the removal is
9712 // legal instead.
9713 //
9714 // isEquivalentMaskless() is the code for testing if the AND can be removed
9715 // factored out of the DAG recognition as the DAG can take several forms.
9716
9717 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9718                                  ISD::LoadExtType ExtType, int AddConstant,
9719                                  int CompConstant) {
9720   // By being careful about our equations and only writing the in term
9721   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9722   // make them generally applicable to all bit widths.
9723   int MaxUInt = (1 << width);
9724
9725   // For the purposes of these comparisons sign extending the type is
9726   // equivalent to zero extending the add and displacing it by half the integer
9727   // width. Provided we are careful and make sure our equations are valid over
9728   // the whole range we can just adjust the input and avoid writing equations
9729   // for sign extended inputs.
9730   if (ExtType == ISD::SEXTLOAD)
9731     AddConstant -= (1 << (width-1));
9732
9733   switch(CC) {
9734   case AArch64CC::LE:
9735   case AArch64CC::GT: {
9736     if ((AddConstant == 0) ||
9737         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9738         (AddConstant >= 0 && CompConstant < 0) ||
9739         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9740       return true;
9741   } break;
9742   case AArch64CC::LT:
9743   case AArch64CC::GE: {
9744     if ((AddConstant == 0) ||
9745         (AddConstant >= 0 && CompConstant <= 0) ||
9746         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9747       return true;
9748   } break;
9749   case AArch64CC::HI:
9750   case AArch64CC::LS: {
9751     if ((AddConstant >= 0 && CompConstant < 0) ||
9752        (AddConstant <= 0 && CompConstant >= -1 &&
9753         CompConstant < AddConstant + MaxUInt))
9754       return true;
9755   } break;
9756   case AArch64CC::PL:
9757   case AArch64CC::MI: {
9758     if ((AddConstant == 0) ||
9759         (AddConstant > 0 && CompConstant <= 0) ||
9760         (AddConstant < 0 && CompConstant <= AddConstant))
9761       return true;
9762   } break;
9763   case AArch64CC::LO:
9764   case AArch64CC::HS: {
9765     if ((AddConstant >= 0 && CompConstant <= 0) ||
9766         (AddConstant <= 0 && CompConstant >= 0 &&
9767          CompConstant <= AddConstant + MaxUInt))
9768       return true;
9769   } break;
9770   case AArch64CC::EQ:
9771   case AArch64CC::NE: {
9772     if ((AddConstant > 0 && CompConstant < 0) ||
9773         (AddConstant < 0 && CompConstant >= 0 &&
9774          CompConstant < AddConstant + MaxUInt) ||
9775         (AddConstant >= 0 && CompConstant >= 0 &&
9776          CompConstant >= AddConstant) ||
9777         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9778
9779       return true;
9780   } break;
9781   case AArch64CC::VS:
9782   case AArch64CC::VC:
9783   case AArch64CC::AL:
9784   case AArch64CC::NV:
9785     return true;
9786   case AArch64CC::Invalid:
9787     break;
9788   }
9789
9790   return false;
9791 }
9792
9793 static
9794 SDValue performCONDCombine(SDNode *N,
9795                            TargetLowering::DAGCombinerInfo &DCI,
9796                            SelectionDAG &DAG, unsigned CCIndex,
9797                            unsigned CmpIndex) {
9798   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9799   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9800   unsigned CondOpcode = SubsNode->getOpcode();
9801
9802   if (CondOpcode != AArch64ISD::SUBS)
9803     return SDValue();
9804
9805   // There is a SUBS feeding this condition. Is it fed by a mask we can
9806   // use?
9807
9808   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9809   unsigned MaskBits = 0;
9810
9811   if (AndNode->getOpcode() != ISD::AND)
9812     return SDValue();
9813
9814   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9815     uint32_t CNV = CN->getZExtValue();
9816     if (CNV == 255)
9817       MaskBits = 8;
9818     else if (CNV == 65535)
9819       MaskBits = 16;
9820   }
9821
9822   if (!MaskBits)
9823     return SDValue();
9824
9825   SDValue AddValue = AndNode->getOperand(0);
9826
9827   if (AddValue.getOpcode() != ISD::ADD)
9828     return SDValue();
9829
9830   // The basic dag structure is correct, grab the inputs and validate them.
9831
9832   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9833   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9834   SDValue SubsInputValue = SubsNode->getOperand(1);
9835
9836   // The mask is present and the provenance of all the values is a smaller type,
9837   // lets see if the mask is superfluous.
9838
9839   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9840       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9841     return SDValue();
9842
9843   ISD::LoadExtType ExtType;
9844
9845   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9846       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9847       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9848     return SDValue();
9849
9850   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9851                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9852                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9853     return SDValue();
9854
9855   // The AND is not necessary, remove it.
9856
9857   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9858                                SubsNode->getValueType(1));
9859   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9860
9861   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9862   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9863
9864   return SDValue(N, 0);
9865 }
9866
9867 // Optimize compare with zero and branch.
9868 static SDValue performBRCONDCombine(SDNode *N,
9869                                     TargetLowering::DAGCombinerInfo &DCI,
9870                                     SelectionDAG &DAG) {
9871   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9872     N = NV.getNode();
9873   SDValue Chain = N->getOperand(0);
9874   SDValue Dest = N->getOperand(1);
9875   SDValue CCVal = N->getOperand(2);
9876   SDValue Cmp = N->getOperand(3);
9877
9878   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9879   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9880   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9881     return SDValue();
9882
9883   unsigned CmpOpc = Cmp.getOpcode();
9884   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9885     return SDValue();
9886
9887   // Only attempt folding if there is only one use of the flag and no use of the
9888   // value.
9889   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9890     return SDValue();
9891
9892   SDValue LHS = Cmp.getOperand(0);
9893   SDValue RHS = Cmp.getOperand(1);
9894
9895   assert(LHS.getValueType() == RHS.getValueType() &&
9896          "Expected the value type to be the same for both operands!");
9897   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9898     return SDValue();
9899
9900   if (isNullConstant(LHS))
9901     std::swap(LHS, RHS);
9902
9903   if (!isNullConstant(RHS))
9904     return SDValue();
9905
9906   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9907       LHS.getOpcode() == ISD::SRL)
9908     return SDValue();
9909
9910   // Fold the compare into the branch instruction.
9911   SDValue BR;
9912   if (CC == AArch64CC::EQ)
9913     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9914   else
9915     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9916
9917   // Do not add new nodes to DAG combiner worklist.
9918   DCI.CombineTo(N, BR, false);
9919
9920   return SDValue();
9921 }
9922
9923 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9924 // as well as whether the test should be inverted.  This code is required to
9925 // catch these cases (as opposed to standard dag combines) because
9926 // AArch64ISD::TBZ is matched during legalization.
9927 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9928                                  SelectionDAG &DAG) {
9929
9930   if (!Op->hasOneUse())
9931     return Op;
9932
9933   // We don't handle undef/constant-fold cases below, as they should have
9934   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9935   // etc.)
9936
9937   // (tbz (trunc x), b) -> (tbz x, b)
9938   // This case is just here to enable more of the below cases to be caught.
9939   if (Op->getOpcode() == ISD::TRUNCATE &&
9940       Bit < Op->getValueType(0).getSizeInBits()) {
9941     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9942   }
9943
9944   if (Op->getNumOperands() != 2)
9945     return Op;
9946
9947   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9948   if (!C)
9949     return Op;
9950
9951   switch (Op->getOpcode()) {
9952   default:
9953     return Op;
9954
9955   // (tbz (and x, m), b) -> (tbz x, b)
9956   case ISD::AND:
9957     if ((C->getZExtValue() >> Bit) & 1)
9958       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9959     return Op;
9960
9961   // (tbz (shl x, c), b) -> (tbz x, b-c)
9962   case ISD::SHL:
9963     if (C->getZExtValue() <= Bit &&
9964         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9965       Bit = Bit - C->getZExtValue();
9966       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9967     }
9968     return Op;
9969
9970   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9971   case ISD::SRA:
9972     Bit = Bit + C->getZExtValue();
9973     if (Bit >= Op->getValueType(0).getSizeInBits())
9974       Bit = Op->getValueType(0).getSizeInBits() - 1;
9975     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9976
9977   // (tbz (srl x, c), b) -> (tbz x, b+c)
9978   case ISD::SRL:
9979     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9980       Bit = Bit + C->getZExtValue();
9981       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9982     }
9983     return Op;
9984
9985   // (tbz (xor x, -1), b) -> (tbnz x, b)
9986   case ISD::XOR:
9987     if ((C->getZExtValue() >> Bit) & 1)
9988       Invert = !Invert;
9989     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9990   }
9991 }
9992
9993 // Optimize test single bit zero/non-zero and branch.
9994 static SDValue performTBZCombine(SDNode *N,
9995                                  TargetLowering::DAGCombinerInfo &DCI,
9996                                  SelectionDAG &DAG) {
9997   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9998   bool Invert = false;
9999   SDValue TestSrc = N->getOperand(1);
10000   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10001
10002   if (TestSrc == NewTestSrc)
10003     return SDValue();
10004
10005   unsigned NewOpc = N->getOpcode();
10006   if (Invert) {
10007     if (NewOpc == AArch64ISD::TBZ)
10008       NewOpc = AArch64ISD::TBNZ;
10009     else {
10010       assert(NewOpc == AArch64ISD::TBNZ);
10011       NewOpc = AArch64ISD::TBZ;
10012     }
10013   }
10014
10015   SDLoc DL(N);
10016   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10017                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10018 }
10019
10020 // vselect (v1i1 setcc) ->
10021 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10022 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10023 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10024 // such VSELECT.
10025 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10026   SDValue N0 = N->getOperand(0);
10027   EVT CCVT = N0.getValueType();
10028
10029   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10030       CCVT.getVectorElementType() != MVT::i1)
10031     return SDValue();
10032
10033   EVT ResVT = N->getValueType(0);
10034   EVT CmpVT = N0.getOperand(0).getValueType();
10035   // Only combine when the result type is of the same size as the compared
10036   // operands.
10037   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10038     return SDValue();
10039
10040   SDValue IfTrue = N->getOperand(1);
10041   SDValue IfFalse = N->getOperand(2);
10042   SDValue SetCC =
10043       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10044                    N0.getOperand(0), N0.getOperand(1),
10045                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10046   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10047                      IfTrue, IfFalse);
10048 }
10049
10050 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10051 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10052 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10053 /// with a vector one followed by a DUP shuffle on the result.
10054 static SDValue performSelectCombine(SDNode *N,
10055                                     TargetLowering::DAGCombinerInfo &DCI) {
10056   SelectionDAG &DAG = DCI.DAG;
10057   SDValue N0 = N->getOperand(0);
10058   EVT ResVT = N->getValueType(0);
10059
10060   if (N0.getOpcode() != ISD::SETCC)
10061     return SDValue();
10062
10063   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10064   // scalar SetCCResultType. We also don't expect vectors, because we assume
10065   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10066   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10067          "Scalar-SETCC feeding SELECT has unexpected result type!");
10068
10069   // If NumMaskElts == 0, the comparison is larger than select result. The
10070   // largest real NEON comparison is 64-bits per lane, which means the result is
10071   // at most 32-bits and an illegal vector. Just bail out for now.
10072   EVT SrcVT = N0.getOperand(0).getValueType();
10073
10074   // Don't try to do this optimization when the setcc itself has i1 operands.
10075   // There are no legal vectors of i1, so this would be pointless.
10076   if (SrcVT == MVT::i1)
10077     return SDValue();
10078
10079   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10080   if (!ResVT.isVector() || NumMaskElts == 0)
10081     return SDValue();
10082
10083   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10084   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10085
10086   // Also bail out if the vector CCVT isn't the same size as ResVT.
10087   // This can happen if the SETCC operand size doesn't divide the ResVT size
10088   // (e.g., f64 vs v3f32).
10089   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10090     return SDValue();
10091
10092   // Make sure we didn't create illegal types, if we're not supposed to.
10093   assert(DCI.isBeforeLegalize() ||
10094          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10095
10096   // First perform a vector comparison, where lane 0 is the one we're interested
10097   // in.
10098   SDLoc DL(N0);
10099   SDValue LHS =
10100       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10101   SDValue RHS =
10102       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10103   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10104
10105   // Now duplicate the comparison mask we want across all other lanes.
10106   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10107   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10108   Mask = DAG.getNode(ISD::BITCAST, DL,
10109                      ResVT.changeVectorElementTypeToInteger(), Mask);
10110
10111   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10112 }
10113
10114 /// Get rid of unnecessary NVCASTs (that don't change the type).
10115 static SDValue performNVCASTCombine(SDNode *N) {
10116   if (N->getValueType(0) == N->getOperand(0).getValueType())
10117     return N->getOperand(0);
10118
10119   return SDValue();
10120 }
10121
10122 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10123                                                  DAGCombinerInfo &DCI) const {
10124   SelectionDAG &DAG = DCI.DAG;
10125   switch (N->getOpcode()) {
10126   default:
10127     break;
10128   case ISD::ADD:
10129   case ISD::SUB:
10130     return performAddSubLongCombine(N, DCI, DAG);
10131   case ISD::XOR:
10132     return performXorCombine(N, DAG, DCI, Subtarget);
10133   case ISD::MUL:
10134     return performMulCombine(N, DAG, DCI, Subtarget);
10135   case ISD::SINT_TO_FP:
10136   case ISD::UINT_TO_FP:
10137     return performIntToFpCombine(N, DAG, Subtarget);
10138   case ISD::FP_TO_SINT:
10139   case ISD::FP_TO_UINT:
10140     return performFpToIntCombine(N, DAG, DCI, Subtarget);
10141   case ISD::FDIV:
10142     return performFDivCombine(N, DAG, DCI, Subtarget);
10143   case ISD::OR:
10144     return performORCombine(N, DCI, Subtarget);
10145   case ISD::SRL:
10146     return performSRLCombine(N, DCI);
10147   case ISD::INTRINSIC_WO_CHAIN:
10148     return performIntrinsicCombine(N, DCI, Subtarget);
10149   case ISD::ANY_EXTEND:
10150   case ISD::ZERO_EXTEND:
10151   case ISD::SIGN_EXTEND:
10152     return performExtendCombine(N, DCI, DAG);
10153   case ISD::BITCAST:
10154     return performBitcastCombine(N, DCI, DAG);
10155   case ISD::CONCAT_VECTORS:
10156     return performConcatVectorsCombine(N, DCI, DAG);
10157   case ISD::SELECT: {
10158     SDValue RV = performSelectCombine(N, DCI);
10159     if (!RV.getNode())
10160       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10161     return RV;
10162   }
10163   case ISD::VSELECT:
10164     return performVSelectCombine(N, DCI.DAG);
10165   case ISD::LOAD:
10166     if (performTBISimplification(N->getOperand(1), DCI, DAG))
10167       return SDValue(N, 0);
10168     break;
10169   case ISD::STORE:
10170     return performSTORECombine(N, DCI, DAG, Subtarget);
10171   case AArch64ISD::BRCOND:
10172     return performBRCONDCombine(N, DCI, DAG);
10173   case AArch64ISD::TBNZ:
10174   case AArch64ISD::TBZ:
10175     return performTBZCombine(N, DCI, DAG);
10176   case AArch64ISD::CSEL:
10177     return performCONDCombine(N, DCI, DAG, 2, 3);
10178   case AArch64ISD::DUP:
10179     return performPostLD1Combine(N, DCI, false);
10180   case AArch64ISD::NVCAST:
10181     return performNVCASTCombine(N);
10182   case ISD::INSERT_VECTOR_ELT:
10183     return performPostLD1Combine(N, DCI, true);
10184   case ISD::EXTRACT_VECTOR_ELT:
10185     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10186   case ISD::INTRINSIC_VOID:
10187   case ISD::INTRINSIC_W_CHAIN:
10188     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10189     case Intrinsic::aarch64_neon_ld2:
10190     case Intrinsic::aarch64_neon_ld3:
10191     case Intrinsic::aarch64_neon_ld4:
10192     case Intrinsic::aarch64_neon_ld1x2:
10193     case Intrinsic::aarch64_neon_ld1x3:
10194     case Intrinsic::aarch64_neon_ld1x4:
10195     case Intrinsic::aarch64_neon_ld2lane:
10196     case Intrinsic::aarch64_neon_ld3lane:
10197     case Intrinsic::aarch64_neon_ld4lane:
10198     case Intrinsic::aarch64_neon_ld2r:
10199     case Intrinsic::aarch64_neon_ld3r:
10200     case Intrinsic::aarch64_neon_ld4r:
10201     case Intrinsic::aarch64_neon_st2:
10202     case Intrinsic::aarch64_neon_st3:
10203     case Intrinsic::aarch64_neon_st4:
10204     case Intrinsic::aarch64_neon_st1x2:
10205     case Intrinsic::aarch64_neon_st1x3:
10206     case Intrinsic::aarch64_neon_st1x4:
10207     case Intrinsic::aarch64_neon_st2lane:
10208     case Intrinsic::aarch64_neon_st3lane:
10209     case Intrinsic::aarch64_neon_st4lane:
10210       return performNEONPostLDSTCombine(N, DCI, DAG);
10211     default:
10212       break;
10213     }
10214   }
10215   return SDValue();
10216 }
10217
10218 // Check if the return value is used as only a return value, as otherwise
10219 // we can't perform a tail-call. In particular, we need to check for
10220 // target ISD nodes that are returns and any other "odd" constructs
10221 // that the generic analysis code won't necessarily catch.
10222 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10223                                                SDValue &Chain) const {
10224   if (N->getNumValues() != 1)
10225     return false;
10226   if (!N->hasNUsesOfValue(1, 0))
10227     return false;
10228
10229   SDValue TCChain = Chain;
10230   SDNode *Copy = *N->use_begin();
10231   if (Copy->getOpcode() == ISD::CopyToReg) {
10232     // If the copy has a glue operand, we conservatively assume it isn't safe to
10233     // perform a tail call.
10234     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10235         MVT::Glue)
10236       return false;
10237     TCChain = Copy->getOperand(0);
10238   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10239     return false;
10240
10241   bool HasRet = false;
10242   for (SDNode *Node : Copy->uses()) {
10243     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10244       return false;
10245     HasRet = true;
10246   }
10247
10248   if (!HasRet)
10249     return false;
10250
10251   Chain = TCChain;
10252   return true;
10253 }
10254
10255 // Return whether the an instruction can potentially be optimized to a tail
10256 // call. This will cause the optimizers to attempt to move, or duplicate,
10257 // return instructions to help enable tail call optimizations for this
10258 // instruction.
10259 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
10260   return CI->isTailCall();
10261 }
10262
10263 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10264                                                    SDValue &Offset,
10265                                                    ISD::MemIndexedMode &AM,
10266                                                    bool &IsInc,
10267                                                    SelectionDAG &DAG) const {
10268   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10269     return false;
10270
10271   Base = Op->getOperand(0);
10272   // All of the indexed addressing mode instructions take a signed
10273   // 9 bit immediate offset.
10274   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10275     int64_t RHSC = RHS->getSExtValue();
10276     if (Op->getOpcode() == ISD::SUB)
10277       RHSC = -(uint64_t)RHSC;
10278     if (!isInt<9>(RHSC))
10279       return false;
10280     IsInc = (Op->getOpcode() == ISD::ADD);
10281     Offset = Op->getOperand(1);
10282     return true;
10283   }
10284   return false;
10285 }
10286
10287 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10288                                                       SDValue &Offset,
10289                                                       ISD::MemIndexedMode &AM,
10290                                                       SelectionDAG &DAG) const {
10291   EVT VT;
10292   SDValue Ptr;
10293   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10294     VT = LD->getMemoryVT();
10295     Ptr = LD->getBasePtr();
10296   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10297     VT = ST->getMemoryVT();
10298     Ptr = ST->getBasePtr();
10299   } else
10300     return false;
10301
10302   bool IsInc;
10303   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10304     return false;
10305   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10306   return true;
10307 }
10308
10309 bool AArch64TargetLowering::getPostIndexedAddressParts(
10310     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10311     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10312   EVT VT;
10313   SDValue Ptr;
10314   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10315     VT = LD->getMemoryVT();
10316     Ptr = LD->getBasePtr();
10317   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10318     VT = ST->getMemoryVT();
10319     Ptr = ST->getBasePtr();
10320   } else
10321     return false;
10322
10323   bool IsInc;
10324   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10325     return false;
10326   // Post-indexing updates the base, so it's not a valid transform
10327   // if that's not the same as the load's pointer.
10328   if (Ptr != Base)
10329     return false;
10330   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10331   return true;
10332 }
10333
10334 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10335                                   SelectionDAG &DAG) {
10336   SDLoc DL(N);
10337   SDValue Op = N->getOperand(0);
10338
10339   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10340     return;
10341
10342   Op = SDValue(
10343       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10344                          DAG.getUNDEF(MVT::i32), Op,
10345                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10346       0);
10347   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10348   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10349 }
10350
10351 static void ReplaceReductionResults(SDNode *N,
10352                                     SmallVectorImpl<SDValue> &Results,
10353                                     SelectionDAG &DAG, unsigned InterOp,
10354                                     unsigned AcrossOp) {
10355   EVT LoVT, HiVT;
10356   SDValue Lo, Hi;
10357   SDLoc dl(N);
10358   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10359   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10360   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10361   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10362   Results.push_back(SplitVal);
10363 }
10364
10365 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10366   SDLoc DL(N);
10367   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10368   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10369                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10370                                        DAG.getConstant(64, DL, MVT::i64)));
10371   return std::make_pair(Lo, Hi);
10372 }
10373
10374 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10375                                        SmallVectorImpl<SDValue> & Results,
10376                                        SelectionDAG &DAG) {
10377   assert(N->getValueType(0) == MVT::i128 &&
10378          "AtomicCmpSwap on types less than 128 should be legal");
10379   auto Desired = splitInt128(N->getOperand(2), DAG);
10380   auto New = splitInt128(N->getOperand(3), DAG);
10381   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10382                    New.first,        New.second,    N->getOperand(0)};
10383   SDNode *CmpSwap = DAG.getMachineNode(
10384       AArch64::CMP_SWAP_128, SDLoc(N),
10385       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10386
10387   MachineFunction &MF = DAG.getMachineFunction();
10388   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10389   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10390   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10391
10392   Results.push_back(SDValue(CmpSwap, 0));
10393   Results.push_back(SDValue(CmpSwap, 1));
10394   Results.push_back(SDValue(CmpSwap, 3));
10395 }
10396
10397 void AArch64TargetLowering::ReplaceNodeResults(
10398     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10399   switch (N->getOpcode()) {
10400   default:
10401     llvm_unreachable("Don't know how to custom expand this");
10402   case ISD::BITCAST:
10403     ReplaceBITCASTResults(N, Results, DAG);
10404     return;
10405   case AArch64ISD::SADDV:
10406     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10407     return;
10408   case AArch64ISD::UADDV:
10409     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10410     return;
10411   case AArch64ISD::SMINV:
10412     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10413     return;
10414   case AArch64ISD::UMINV:
10415     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10416     return;
10417   case AArch64ISD::SMAXV:
10418     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10419     return;
10420   case AArch64ISD::UMAXV:
10421     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10422     return;
10423   case ISD::FP_TO_UINT:
10424   case ISD::FP_TO_SINT:
10425     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10426     // Let normal code take care of it by not adding anything to Results.
10427     return;
10428   case ISD::ATOMIC_CMP_SWAP:
10429     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10430     return;
10431   }
10432 }
10433
10434 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10435   if (!Subtarget->isTargetAndroid())
10436     return true;
10437   return TargetLowering::useLoadStackGuardNode();
10438 }
10439
10440 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10441   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10442   // reciprocal if there are three or more FDIVs.
10443   return 3;
10444 }
10445
10446 TargetLoweringBase::LegalizeTypeAction
10447 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10448   MVT SVT = VT.getSimpleVT();
10449   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10450   // v4i16, v2i32 instead of to promote.
10451   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10452       || SVT == MVT::v1f32)
10453     return TypeWidenVector;
10454
10455   return TargetLoweringBase::getPreferredVectorAction(VT);
10456 }
10457
10458 // Loads and stores less than 128-bits are already atomic; ones above that
10459 // are doomed anyway, so defer to the default libcall and blame the OS when
10460 // things go wrong.
10461 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10462   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10463   return Size == 128;
10464 }
10465
10466 // Loads and stores less than 128-bits are already atomic; ones above that
10467 // are doomed anyway, so defer to the default libcall and blame the OS when
10468 // things go wrong.
10469 TargetLowering::AtomicExpansionKind
10470 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10471   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10472   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10473 }
10474
10475 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10476 TargetLowering::AtomicExpansionKind
10477 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10478   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10479   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10480 }
10481
10482 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10483     AtomicCmpXchgInst *AI) const {
10484   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10485   // implement cmpxchg without spilling. If the address being exchanged is also
10486   // on the stack and close enough to the spill slot, this can lead to a
10487   // situation where the monitor always gets cleared and the atomic operation
10488   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10489   return getTargetMachine().getOptLevel() != 0;
10490 }
10491
10492 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10493                                              AtomicOrdering Ord) const {
10494   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10495   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10496   bool IsAcquire = isAcquireOrStronger(Ord);
10497
10498   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10499   // intrinsic must return {i64, i64} and we have to recombine them into a
10500   // single i128 here.
10501   if (ValTy->getPrimitiveSizeInBits() == 128) {
10502     Intrinsic::ID Int =
10503         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10504     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10505
10506     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10507     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10508
10509     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10510     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10511     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10512     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10513     return Builder.CreateOr(
10514         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10515   }
10516
10517   Type *Tys[] = { Addr->getType() };
10518   Intrinsic::ID Int =
10519       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10520   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10521
10522   return Builder.CreateTruncOrBitCast(
10523       Builder.CreateCall(Ldxr, Addr),
10524       cast<PointerType>(Addr->getType())->getElementType());
10525 }
10526
10527 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10528     IRBuilder<> &Builder) const {
10529   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10530   Builder.CreateCall(
10531       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10532 }
10533
10534 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10535                                                    Value *Val, Value *Addr,
10536                                                    AtomicOrdering Ord) const {
10537   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10538   bool IsRelease = isReleaseOrStronger(Ord);
10539
10540   // Since the intrinsics must have legal type, the i128 intrinsics take two
10541   // parameters: "i64, i64". We must marshal Val into the appropriate form
10542   // before the call.
10543   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10544     Intrinsic::ID Int =
10545         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10546     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10547     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10548
10549     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10550     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10551     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10552     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10553   }
10554
10555   Intrinsic::ID Int =
10556       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10557   Type *Tys[] = { Addr->getType() };
10558   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10559
10560   return Builder.CreateCall(Stxr,
10561                             {Builder.CreateZExtOrBitCast(
10562                                  Val, Stxr->getFunctionType()->getParamType(0)),
10563                              Addr});
10564 }
10565
10566 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10567     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10568   return Ty->isArrayTy();
10569 }
10570
10571 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10572                                                             EVT) const {
10573   return false;
10574 }
10575
10576 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10577   if (!Subtarget->isTargetAndroid())
10578     return TargetLowering::getIRStackGuard(IRB);
10579
10580   // Android provides a fixed TLS slot for the stack cookie. See the definition
10581   // of TLS_SLOT_STACK_GUARD in
10582   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10583   const unsigned TlsOffset = 0x28;
10584   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10585   Function *ThreadPointerFunc =
10586       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10587   return IRB.CreatePointerCast(
10588       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10589       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10590 }
10591
10592 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10593   if (!Subtarget->isTargetAndroid())
10594     return TargetLowering::getSafeStackPointerLocation(IRB);
10595
10596   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10597   // definition of TLS_SLOT_SAFESTACK in
10598   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10599   const unsigned TlsOffset = 0x48;
10600   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10601   Function *ThreadPointerFunc =
10602       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10603   return IRB.CreatePointerCast(
10604       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10605       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10606 }
10607
10608 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10609   // Update IsSplitCSR in AArch64unctionInfo.
10610   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10611   AFI->setIsSplitCSR(true);
10612 }
10613
10614 void AArch64TargetLowering::insertCopiesSplitCSR(
10615     MachineBasicBlock *Entry,
10616     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10617   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10618   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10619   if (!IStart)
10620     return;
10621
10622   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10623   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10624   MachineBasicBlock::iterator MBBI = Entry->begin();
10625   for (const MCPhysReg *I = IStart; *I; ++I) {
10626     const TargetRegisterClass *RC = nullptr;
10627     if (AArch64::GPR64RegClass.contains(*I))
10628       RC = &AArch64::GPR64RegClass;
10629     else if (AArch64::FPR64RegClass.contains(*I))
10630       RC = &AArch64::FPR64RegClass;
10631     else
10632       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10633
10634     unsigned NewVR = MRI->createVirtualRegister(RC);
10635     // Create copy from CSR to a virtual register.
10636     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10637     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10638     // nounwind. If we want to generalize this later, we may need to emit
10639     // CFI pseudo-instructions.
10640     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10641                Attribute::NoUnwind) &&
10642            "Function should be nounwind in insertCopiesSplitCSR!");
10643     Entry->addLiveIn(*I);
10644     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10645         .addReg(*I);
10646
10647     // Insert the copy-back instructions right before the terminator.
10648     for (auto *Exit : Exits)
10649       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10650               TII->get(TargetOpcode::COPY), *I)
10651           .addReg(NewVR);
10652   }
10653 }
10654
10655 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10656   // Integer division on AArch64 is expensive. However, when aggressively
10657   // optimizing for code size, we prefer to use a div instruction, as it is
10658   // usually smaller than the alternative sequence.
10659   // The exception to this is vector division. Since AArch64 doesn't have vector
10660   // integer division, leaving the division as-is is a loss even in terms of
10661   // size, because it will have to be scalarized, while the alternative code
10662   // sequence can be performed in vector form.
10663   bool OptSize =
10664       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10665   return OptSize && !VT.isVector();
10666 }