14d2f6fb61ac69c2503b28dd6d5058f67294ff78
[oota-llvm.git] / 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 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147   // Virtually no operation on f128 is legal, but LLVM can't expand them when
148   // there's a valid register class, so we need custom operations in most cases.
149   setOperationAction(ISD::FABS, MVT::f128, Expand);
150   setOperationAction(ISD::FADD, MVT::f128, Custom);
151   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152   setOperationAction(ISD::FCOS, MVT::f128, Expand);
153   setOperationAction(ISD::FDIV, MVT::f128, Custom);
154   setOperationAction(ISD::FMA, MVT::f128, Expand);
155   setOperationAction(ISD::FMUL, MVT::f128, Custom);
156   setOperationAction(ISD::FNEG, MVT::f128, Expand);
157   setOperationAction(ISD::FPOW, MVT::f128, Expand);
158   setOperationAction(ISD::FREM, MVT::f128, Expand);
159   setOperationAction(ISD::FRINT, MVT::f128, Expand);
160   setOperationAction(ISD::FSIN, MVT::f128, Expand);
161   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163   setOperationAction(ISD::FSUB, MVT::f128, Custom);
164   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165   setOperationAction(ISD::SETCC, MVT::f128, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167   setOperationAction(ISD::SELECT, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171   // Lowering for many of the conversions is actually specified by the non-f128
172   // type. The LowerXXX function will be trivial when f128 isn't involved.
173   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188   // Variable arguments.
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Custom);
191   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194   // Variable-sized objects.
195   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
199   // Constant pool entries
200   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201
202   // BlockAddress
203   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204
205   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206   setOperationAction(ISD::ADDC, MVT::i32, Custom);
207   setOperationAction(ISD::ADDE, MVT::i32, Custom);
208   setOperationAction(ISD::SUBC, MVT::i32, Custom);
209   setOperationAction(ISD::SUBE, MVT::i32, Custom);
210   setOperationAction(ISD::ADDC, MVT::i64, Custom);
211   setOperationAction(ISD::ADDE, MVT::i64, Custom);
212   setOperationAction(ISD::SUBC, MVT::i64, Custom);
213   setOperationAction(ISD::SUBE, MVT::i64, Custom);
214
215   // AArch64 lacks both left-rotate and popcount instructions.
216   setOperationAction(ISD::ROTL, MVT::i32, Expand);
217   setOperationAction(ISD::ROTL, MVT::i64, Expand);
218   for (MVT VT : MVT::vector_valuetypes()) {
219     setOperationAction(ISD::ROTL, VT, Expand);
220     setOperationAction(ISD::ROTR, VT, Expand);
221   }
222
223   // AArch64 doesn't have {U|S}MUL_LOHI.
224   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226
227
228   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229   // counterparts, which AArch64 supports directly.
230   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234
235   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237
238   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
240   setOperationAction(ISD::SREM, MVT::i32, Expand);
241   setOperationAction(ISD::SREM, MVT::i64, Expand);
242   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
244   setOperationAction(ISD::UREM, MVT::i32, Expand);
245   setOperationAction(ISD::UREM, MVT::i64, Expand);
246
247   // Custom lower Add/Sub/Mul with overflow.
248   setOperationAction(ISD::SADDO, MVT::i32, Custom);
249   setOperationAction(ISD::SADDO, MVT::i64, Custom);
250   setOperationAction(ISD::UADDO, MVT::i32, Custom);
251   setOperationAction(ISD::UADDO, MVT::i64, Custom);
252   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
253   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
254   setOperationAction(ISD::USUBO, MVT::i32, Custom);
255   setOperationAction(ISD::USUBO, MVT::i64, Custom);
256   setOperationAction(ISD::SMULO, MVT::i32, Custom);
257   setOperationAction(ISD::SMULO, MVT::i64, Custom);
258   setOperationAction(ISD::UMULO, MVT::i32, Custom);
259   setOperationAction(ISD::UMULO, MVT::i64, Custom);
260
261   setOperationAction(ISD::FSIN, MVT::f32, Expand);
262   setOperationAction(ISD::FSIN, MVT::f64, Expand);
263   setOperationAction(ISD::FCOS, MVT::f32, Expand);
264   setOperationAction(ISD::FCOS, MVT::f64, Expand);
265   setOperationAction(ISD::FPOW, MVT::f32, Expand);
266   setOperationAction(ISD::FPOW, MVT::f64, Expand);
267   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
268   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
269
270   // f16 is a storage-only type, always promote it to f32.
271   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
272   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
273   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
274   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
275   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
276   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
277   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
278   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
279   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
280   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
281   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
282   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
283   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
284   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
285   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
286   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
287   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
288   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
289   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
290   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
291   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
292   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
293   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
294   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
295   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
296   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
297   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
298   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
299   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
300   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
301   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
302   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
303   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
304   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
305
306   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
307   // known to be safe.
308   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
309   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
310   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
311   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
312   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
313   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
314   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
315   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
318   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
320
321   // Expand all other v4f16 operations.
322   // FIXME: We could generate better code by promoting some operations to
323   // a pair of v4f32s
324   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
325   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
326   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
327   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
328   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
329   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
330   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
331   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
332   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
333   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
334   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
335   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
336   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
337   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
338   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
339   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
340   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
341   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
342   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
343   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
344   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
345   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
346   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
347   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
348   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
349   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
350
351
352   // v8f16 is also a storage-only type, so expand it.
353   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
354   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
355   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
356   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
357   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
358   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
359   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
360   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
361   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
362   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
363   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
364   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
365   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
366   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
367   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
368   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
369   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
371   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
372   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
373   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
374   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
375   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
376   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
377   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
378   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
379   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
380   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
381   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
382   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
383   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
384
385   // AArch64 has implementations of a lot of rounding-like FP operations.
386   for (MVT Ty : {MVT::f32, MVT::f64}) {
387     setOperationAction(ISD::FFLOOR, Ty, Legal);
388     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
389     setOperationAction(ISD::FCEIL, Ty, Legal);
390     setOperationAction(ISD::FRINT, Ty, Legal);
391     setOperationAction(ISD::FTRUNC, Ty, Legal);
392     setOperationAction(ISD::FROUND, Ty, Legal);
393     setOperationAction(ISD::FMINNUM, Ty, Legal);
394     setOperationAction(ISD::FMAXNUM, Ty, Legal);
395     setOperationAction(ISD::FMINNAN, Ty, Legal);
396     setOperationAction(ISD::FMAXNAN, Ty, Legal);
397   }
398
399   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
400
401   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
402   // This requires the Performance Monitors extension.
403   if (Subtarget->hasPerfMon())
404     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
405
406   if (Subtarget->isTargetMachO()) {
407     // For iOS, we don't want to the normal expansion of a libcall to
408     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
409     // traffic.
410     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
411     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
412   } else {
413     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
414     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
415   }
416
417   // Make floating-point constants legal for the large code model, so they don't
418   // become loads from the constant pool.
419   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
420     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
421     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
422   }
423
424   // AArch64 does not have floating-point extending loads, i1 sign-extending
425   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
426   for (MVT VT : MVT::fp_valuetypes()) {
427     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
431   }
432   for (MVT VT : MVT::integer_valuetypes())
433     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
434
435   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
436   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
438   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
442
443   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
444   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
445
446   // Indexed loads and stores are supported.
447   for (unsigned im = (unsigned)ISD::PRE_INC;
448        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
449     setIndexedLoadAction(im, MVT::i8, Legal);
450     setIndexedLoadAction(im, MVT::i16, Legal);
451     setIndexedLoadAction(im, MVT::i32, Legal);
452     setIndexedLoadAction(im, MVT::i64, Legal);
453     setIndexedLoadAction(im, MVT::f64, Legal);
454     setIndexedLoadAction(im, MVT::f32, Legal);
455     setIndexedLoadAction(im, MVT::f16, Legal);
456     setIndexedStoreAction(im, MVT::i8, Legal);
457     setIndexedStoreAction(im, MVT::i16, Legal);
458     setIndexedStoreAction(im, MVT::i32, Legal);
459     setIndexedStoreAction(im, MVT::i64, Legal);
460     setIndexedStoreAction(im, MVT::f64, Legal);
461     setIndexedStoreAction(im, MVT::f32, Legal);
462     setIndexedStoreAction(im, MVT::f16, Legal);
463   }
464
465   // Trap.
466   setOperationAction(ISD::TRAP, MVT::Other, Legal);
467
468   // We combine OR nodes for bitfield operations.
469   setTargetDAGCombine(ISD::OR);
470
471   // Vector add and sub nodes may conceal a high-half opportunity.
472   // Also, try to fold ADD into CSINC/CSINV..
473   setTargetDAGCombine(ISD::ADD);
474   setTargetDAGCombine(ISD::SUB);
475
476   setTargetDAGCombine(ISD::XOR);
477   setTargetDAGCombine(ISD::SINT_TO_FP);
478   setTargetDAGCombine(ISD::UINT_TO_FP);
479
480   setTargetDAGCombine(ISD::FP_TO_SINT);
481   setTargetDAGCombine(ISD::FP_TO_UINT);
482   setTargetDAGCombine(ISD::FDIV);
483
484   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
485
486   setTargetDAGCombine(ISD::ANY_EXTEND);
487   setTargetDAGCombine(ISD::ZERO_EXTEND);
488   setTargetDAGCombine(ISD::SIGN_EXTEND);
489   setTargetDAGCombine(ISD::BITCAST);
490   setTargetDAGCombine(ISD::CONCAT_VECTORS);
491   setTargetDAGCombine(ISD::STORE);
492   if (Subtarget->supportsAddressTopByteIgnored())
493     setTargetDAGCombine(ISD::LOAD);
494
495   setTargetDAGCombine(ISD::MUL);
496
497   setTargetDAGCombine(ISD::SELECT);
498   setTargetDAGCombine(ISD::VSELECT);
499
500   setTargetDAGCombine(ISD::INTRINSIC_VOID);
501   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
503   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
504
505   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
506   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
507   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
508
509   setStackPointerRegisterToSaveRestore(AArch64::SP);
510
511   setSchedulingPreference(Sched::Hybrid);
512
513   // Enable TBZ/TBNZ
514   MaskAndBranchFoldingIsLegal = true;
515   EnableExtLdPromotion = true;
516
517   setMinFunctionAlignment(2);
518
519   setHasExtractBitsInsn(true);
520
521   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
522
523   if (Subtarget->hasNEON()) {
524     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
525     // silliness like this:
526     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
527     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
528     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
529     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
530     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
531     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
532     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
533     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
534     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
535     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
536     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
537     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
538     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
539     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
540     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
543     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
544     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
545     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
546     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
547     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
548     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
549     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
550     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
551
552     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
553     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
554     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
555     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
556     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
557
558     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559
560     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
561     // elements smaller than i32, so promote the input to i32 first.
562     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
563     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
564     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
565     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
566     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
567     // -> v8f16 conversions.
568     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
569     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
570     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
571     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
572     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
573     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
575     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
576     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
577     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
578     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
579     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
581
582     // AArch64 doesn't have MUL.2d:
583     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
584     // Custom handling for some quad-vector types to detect MULL.
585     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
586     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
587     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
588
589     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
590     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
591     // Likewise, narrowing and extending vector loads/stores aren't handled
592     // directly.
593     for (MVT VT : MVT::vector_valuetypes()) {
594       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
595
596       setOperationAction(ISD::MULHS, VT, Expand);
597       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
598       setOperationAction(ISD::MULHU, VT, Expand);
599       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
600
601       setOperationAction(ISD::BSWAP, VT, Expand);
602
603       for (MVT InnerVT : MVT::vector_valuetypes()) {
604         setTruncStoreAction(VT, InnerVT, Expand);
605         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
606         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
607         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
608       }
609     }
610
611     // AArch64 has implementations of a lot of rounding-like FP operations.
612     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
613       setOperationAction(ISD::FFLOOR, Ty, Legal);
614       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
615       setOperationAction(ISD::FCEIL, Ty, Legal);
616       setOperationAction(ISD::FRINT, Ty, Legal);
617       setOperationAction(ISD::FTRUNC, Ty, Legal);
618       setOperationAction(ISD::FROUND, Ty, Legal);
619     }
620   }
621
622   // Prefer likely predicted branches to selects on out-of-order cores.
623   if (Subtarget->isCortexA57())
624     PredictableSelectIsExpensive = true;
625 }
626
627 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
628   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
629     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
631
632     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
634   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
635     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
636     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
637
638     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
639     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
640   }
641
642   // Mark vector float intrinsics as expand.
643   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
644     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
652     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
653
654     // But we do support custom-lowering for FCOPYSIGN.
655     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
656   }
657
658   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
669   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
670
671   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
672   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
673   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
674   for (MVT InnerVT : MVT::all_valuetypes())
675     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
676
677   // CNT supports only B element sizes.
678   if (VT != MVT::v8i8 && VT != MVT::v16i8)
679     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
680
681   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
682   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
683   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
684   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
685   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
686
687   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
688   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
689
690   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
691   // i64.
692   if (!VT.isFloatingPoint() &&
693       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
694     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
695                             ISD::SABSDIFF, ISD::UABSDIFF})
696       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
697
698   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
699   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
700     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
701                             ISD::FMINNUM, ISD::FMAXNUM})
702       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
703
704   if (Subtarget->isLittleEndian()) {
705     for (unsigned im = (unsigned)ISD::PRE_INC;
706          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
707       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
708       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
709     }
710   }
711 }
712
713 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
714   addRegisterClass(VT, &AArch64::FPR64RegClass);
715   addTypeForNEON(VT, MVT::v2i32);
716 }
717
718 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
719   addRegisterClass(VT, &AArch64::FPR128RegClass);
720   addTypeForNEON(VT, MVT::v4i32);
721 }
722
723 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
724                                               EVT VT) const {
725   if (!VT.isVector())
726     return MVT::i32;
727   return VT.changeVectorElementTypeToInteger();
728 }
729
730 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
731 /// Mask are known to be either zero or one and return them in the
732 /// KnownZero/KnownOne bitsets.
733 void AArch64TargetLowering::computeKnownBitsForTargetNode(
734     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
735     const SelectionDAG &DAG, unsigned Depth) const {
736   switch (Op.getOpcode()) {
737   default:
738     break;
739   case AArch64ISD::CSEL: {
740     APInt KnownZero2, KnownOne2;
741     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
742     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
743     KnownZero &= KnownZero2;
744     KnownOne &= KnownOne2;
745     break;
746   }
747   case ISD::INTRINSIC_W_CHAIN: {
748     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
749     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
750     switch (IntID) {
751     default: return;
752     case Intrinsic::aarch64_ldaxr:
753     case Intrinsic::aarch64_ldxr: {
754       unsigned BitWidth = KnownOne.getBitWidth();
755       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
756       unsigned MemBits = VT.getScalarType().getSizeInBits();
757       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
758       return;
759     }
760     }
761     break;
762   }
763   case ISD::INTRINSIC_WO_CHAIN:
764   case ISD::INTRINSIC_VOID: {
765     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
766     switch (IntNo) {
767     default:
768       break;
769     case Intrinsic::aarch64_neon_umaxv:
770     case Intrinsic::aarch64_neon_uminv: {
771       // Figure out the datatype of the vector operand. The UMINV instruction
772       // will zero extend the result, so we can mark as known zero all the
773       // bits larger than the element datatype. 32-bit or larget doesn't need
774       // this as those are legal types and will be handled by isel directly.
775       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
776       unsigned BitWidth = KnownZero.getBitWidth();
777       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
778         assert(BitWidth >= 8 && "Unexpected width!");
779         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
780         KnownZero |= Mask;
781       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
782         assert(BitWidth >= 16 && "Unexpected width!");
783         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
784         KnownZero |= Mask;
785       }
786       break;
787     } break;
788     }
789   }
790   }
791 }
792
793 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
794                                                   EVT) const {
795   return MVT::i64;
796 }
797
798 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
799                                                            unsigned AddrSpace,
800                                                            unsigned Align,
801                                                            bool *Fast) const {
802   if (Subtarget->requiresStrictAlign())
803     return false;
804
805   // FIXME: This is mostly true for Cyclone, but not necessarily others.
806   if (Fast) {
807     // FIXME: Define an attribute for slow unaligned accesses instead of
808     // relying on the CPU type as a proxy.
809     // On Cyclone, unaligned 128-bit stores are slow.
810     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
811             // See comments in performSTORECombine() for more details about
812             // these conditions.
813
814             // Code that uses clang vector extensions can mark that it
815             // wants unaligned accesses to be treated as fast by
816             // underspecifying alignment to be 1 or 2.
817             Align <= 2 ||
818
819             // Disregard v2i64. Memcpy lowering produces those and splitting
820             // them regresses performance on micro-benchmarks and olden/bh.
821             VT == MVT::v2i64;
822   }
823   return true;
824 }
825
826 FastISel *
827 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
828                                       const TargetLibraryInfo *libInfo) const {
829   return AArch64::createFastISel(funcInfo, libInfo);
830 }
831
832 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
833   switch ((AArch64ISD::NodeType)Opcode) {
834   case AArch64ISD::FIRST_NUMBER:      break;
835   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
836   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
837   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
838   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
839   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
840   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
841   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
842   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
843   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
844   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
845   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
846   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
847   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
848   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
849   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
850   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
851   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
852   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
853   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
854   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
855   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
856   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
857   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
858   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
859   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
860   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
861   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
862   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
863   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
864   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
865   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
866   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
867   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
868   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
869   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
870   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
871   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
872   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
873   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
874   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
875   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
876   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
877   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
878   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
879   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
880   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
881   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
882   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
883   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
884   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
885   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
886   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
887   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
888   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
889   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
890   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
891   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
892   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
893   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
894   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
895   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
896   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
897   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
898   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
899   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
900   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
901   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
902   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
903   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
904   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
905   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
906   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
907   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
908   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
909   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
910   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
911   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
912   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
913   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
914   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
915   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
916   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
917   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
918   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
919   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
920   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
921   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
922   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
923   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
924   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
925   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
926   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
927   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
928   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
929   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
930   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
931   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
932   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
933   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
934   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
935   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
936   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
937   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
938   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
939   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
940   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
941   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
942   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
943   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
944   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
945   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
946   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
947   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
948   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
949   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
950   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
951   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
952   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
953   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
954   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
955   }
956   return nullptr;
957 }
958
959 MachineBasicBlock *
960 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
961                                     MachineBasicBlock *MBB) const {
962   // We materialise the F128CSEL pseudo-instruction as some control flow and a
963   // phi node:
964
965   // OrigBB:
966   //     [... previous instrs leading to comparison ...]
967   //     b.ne TrueBB
968   //     b EndBB
969   // TrueBB:
970   //     ; Fallthrough
971   // EndBB:
972   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
973
974   MachineFunction *MF = MBB->getParent();
975   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
976   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
977   DebugLoc DL = MI->getDebugLoc();
978   MachineFunction::iterator It = ++MBB->getIterator();
979
980   unsigned DestReg = MI->getOperand(0).getReg();
981   unsigned IfTrueReg = MI->getOperand(1).getReg();
982   unsigned IfFalseReg = MI->getOperand(2).getReg();
983   unsigned CondCode = MI->getOperand(3).getImm();
984   bool NZCVKilled = MI->getOperand(4).isKill();
985
986   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
987   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
988   MF->insert(It, TrueBB);
989   MF->insert(It, EndBB);
990
991   // Transfer rest of current basic-block to EndBB
992   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
993                 MBB->end());
994   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
995
996   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
997   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
998   MBB->addSuccessor(TrueBB);
999   MBB->addSuccessor(EndBB);
1000
1001   // TrueBB falls through to the end.
1002   TrueBB->addSuccessor(EndBB);
1003
1004   if (!NZCVKilled) {
1005     TrueBB->addLiveIn(AArch64::NZCV);
1006     EndBB->addLiveIn(AArch64::NZCV);
1007   }
1008
1009   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1010       .addReg(IfTrueReg)
1011       .addMBB(TrueBB)
1012       .addReg(IfFalseReg)
1013       .addMBB(MBB);
1014
1015   MI->eraseFromParent();
1016   return EndBB;
1017 }
1018
1019 MachineBasicBlock *
1020 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1021                                                  MachineBasicBlock *BB) const {
1022   switch (MI->getOpcode()) {
1023   default:
1024 #ifndef NDEBUG
1025     MI->dump();
1026 #endif
1027     llvm_unreachable("Unexpected instruction for custom inserter!");
1028
1029   case AArch64::F128CSEL:
1030     return EmitF128CSEL(MI, BB);
1031
1032   case TargetOpcode::STACKMAP:
1033   case TargetOpcode::PATCHPOINT:
1034     return emitPatchPoint(MI, BB);
1035   }
1036 }
1037
1038 //===----------------------------------------------------------------------===//
1039 // AArch64 Lowering private implementation.
1040 //===----------------------------------------------------------------------===//
1041
1042 //===----------------------------------------------------------------------===//
1043 // Lowering Code
1044 //===----------------------------------------------------------------------===//
1045
1046 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1047 /// CC
1048 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1049   switch (CC) {
1050   default:
1051     llvm_unreachable("Unknown condition code!");
1052   case ISD::SETNE:
1053     return AArch64CC::NE;
1054   case ISD::SETEQ:
1055     return AArch64CC::EQ;
1056   case ISD::SETGT:
1057     return AArch64CC::GT;
1058   case ISD::SETGE:
1059     return AArch64CC::GE;
1060   case ISD::SETLT:
1061     return AArch64CC::LT;
1062   case ISD::SETLE:
1063     return AArch64CC::LE;
1064   case ISD::SETUGT:
1065     return AArch64CC::HI;
1066   case ISD::SETUGE:
1067     return AArch64CC::HS;
1068   case ISD::SETULT:
1069     return AArch64CC::LO;
1070   case ISD::SETULE:
1071     return AArch64CC::LS;
1072   }
1073 }
1074
1075 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1076 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1077                                   AArch64CC::CondCode &CondCode,
1078                                   AArch64CC::CondCode &CondCode2) {
1079   CondCode2 = AArch64CC::AL;
1080   switch (CC) {
1081   default:
1082     llvm_unreachable("Unknown FP condition!");
1083   case ISD::SETEQ:
1084   case ISD::SETOEQ:
1085     CondCode = AArch64CC::EQ;
1086     break;
1087   case ISD::SETGT:
1088   case ISD::SETOGT:
1089     CondCode = AArch64CC::GT;
1090     break;
1091   case ISD::SETGE:
1092   case ISD::SETOGE:
1093     CondCode = AArch64CC::GE;
1094     break;
1095   case ISD::SETOLT:
1096     CondCode = AArch64CC::MI;
1097     break;
1098   case ISD::SETOLE:
1099     CondCode = AArch64CC::LS;
1100     break;
1101   case ISD::SETONE:
1102     CondCode = AArch64CC::MI;
1103     CondCode2 = AArch64CC::GT;
1104     break;
1105   case ISD::SETO:
1106     CondCode = AArch64CC::VC;
1107     break;
1108   case ISD::SETUO:
1109     CondCode = AArch64CC::VS;
1110     break;
1111   case ISD::SETUEQ:
1112     CondCode = AArch64CC::EQ;
1113     CondCode2 = AArch64CC::VS;
1114     break;
1115   case ISD::SETUGT:
1116     CondCode = AArch64CC::HI;
1117     break;
1118   case ISD::SETUGE:
1119     CondCode = AArch64CC::PL;
1120     break;
1121   case ISD::SETLT:
1122   case ISD::SETULT:
1123     CondCode = AArch64CC::LT;
1124     break;
1125   case ISD::SETLE:
1126   case ISD::SETULE:
1127     CondCode = AArch64CC::LE;
1128     break;
1129   case ISD::SETNE:
1130   case ISD::SETUNE:
1131     CondCode = AArch64CC::NE;
1132     break;
1133   }
1134 }
1135
1136 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1137 /// CC usable with the vector instructions. Fewer operations are available
1138 /// without a real NZCV register, so we have to use less efficient combinations
1139 /// to get the same effect.
1140 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1141                                         AArch64CC::CondCode &CondCode,
1142                                         AArch64CC::CondCode &CondCode2,
1143                                         bool &Invert) {
1144   Invert = false;
1145   switch (CC) {
1146   default:
1147     // Mostly the scalar mappings work fine.
1148     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1149     break;
1150   case ISD::SETUO:
1151     Invert = true; // Fallthrough
1152   case ISD::SETO:
1153     CondCode = AArch64CC::MI;
1154     CondCode2 = AArch64CC::GE;
1155     break;
1156   case ISD::SETUEQ:
1157   case ISD::SETULT:
1158   case ISD::SETULE:
1159   case ISD::SETUGT:
1160   case ISD::SETUGE:
1161     // All of the compare-mask comparisons are ordered, but we can switch
1162     // between the two by a double inversion. E.g. ULE == !OGT.
1163     Invert = true;
1164     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1165     break;
1166   }
1167 }
1168
1169 static bool isLegalArithImmed(uint64_t C) {
1170   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1171   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1172 }
1173
1174 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1175                               SDLoc dl, SelectionDAG &DAG) {
1176   EVT VT = LHS.getValueType();
1177
1178   if (VT.isFloatingPoint())
1179     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1180
1181   // The CMP instruction is just an alias for SUBS, and representing it as
1182   // SUBS means that it's possible to get CSE with subtract operations.
1183   // A later phase can perform the optimization of setting the destination
1184   // register to WZR/XZR if it ends up being unused.
1185   unsigned Opcode = AArch64ISD::SUBS;
1186
1187   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1188       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1189       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1190     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1191     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1192     // can be set differently by this operation. It comes down to whether
1193     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1194     // everything is fine. If not then the optimization is wrong. Thus general
1195     // comparisons are only valid if op2 != 0.
1196
1197     // So, finally, the only LLVM-native comparisons that don't mention C and V
1198     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1199     // the absence of information about op2.
1200     Opcode = AArch64ISD::ADDS;
1201     RHS = RHS.getOperand(1);
1202   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1203              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1204              !isUnsignedIntSetCC(CC)) {
1205     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1206     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1207     // of the signed comparisons.
1208     Opcode = AArch64ISD::ANDS;
1209     RHS = LHS.getOperand(1);
1210     LHS = LHS.getOperand(0);
1211   }
1212
1213   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1214       .getValue(1);
1215 }
1216
1217 /// \defgroup AArch64CCMP CMP;CCMP matching
1218 ///
1219 /// These functions deal with the formation of CMP;CCMP;... sequences.
1220 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1221 /// a comparison. They set the NZCV flags to a predefined value if their
1222 /// predicate is false. This allows to express arbitrary conjunctions, for
1223 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1224 /// expressed as:
1225 ///   cmp A
1226 ///   ccmp B, inv(CB), CA
1227 ///   check for CB flags
1228 ///
1229 /// In general we can create code for arbitrary "... (and (and A B) C)"
1230 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1231 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1232 /// negation operations:
1233 /// We can negate the results of a single comparison by inverting the flags
1234 /// used when the predicate fails and inverting the flags tested in the next
1235 /// instruction; We can also negate the results of the whole previous
1236 /// conditional compare sequence by inverting the flags tested in the next
1237 /// instruction. However there is no way to negate the result of a partial
1238 /// sequence.
1239 ///
1240 /// Therefore on encountering an "or" expression we can negate the subtree on
1241 /// one side and have to be able to push the negate to the leafs of the subtree
1242 /// on the other side (see also the comments in code). As complete example:
1243 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1244 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1245 /// is transformed to
1246 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1247 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1248 /// and implemented as:
1249 ///   cmp C
1250 ///   ccmp D, inv(CD), CC
1251 ///   ccmp A, CA, inv(CD)
1252 ///   ccmp B, CB, inv(CA)
1253 ///   check for CB flags
1254 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1255 /// by conditional compare sequences.
1256 /// @{
1257
1258 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1259 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1260                                          ISD::CondCode CC, SDValue CCOp,
1261                                          SDValue Condition, unsigned NZCV,
1262                                          SDLoc DL, SelectionDAG &DAG) {
1263   unsigned Opcode = 0;
1264   if (LHS.getValueType().isFloatingPoint())
1265     Opcode = AArch64ISD::FCCMP;
1266   else if (RHS.getOpcode() == ISD::SUB) {
1267     SDValue SubOp0 = RHS.getOperand(0);
1268     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1269       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1270         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1271         Opcode = AArch64ISD::CCMN;
1272         RHS = RHS.getOperand(1);
1273       }
1274   }
1275   if (Opcode == 0)
1276     Opcode = AArch64ISD::CCMP;
1277
1278   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1279   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1280 }
1281
1282 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1283 /// CanPushNegate is set to true if we can push a negate operation through
1284 /// the tree in a was that we are left with AND operations and negate operations
1285 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1286 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1287 /// brought into such a form.
1288 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1289                                          unsigned Depth = 0) {
1290   if (!Val.hasOneUse())
1291     return false;
1292   unsigned Opcode = Val->getOpcode();
1293   if (Opcode == ISD::SETCC) {
1294     CanPushNegate = true;
1295     return true;
1296   }
1297   // Protect against stack overflow.
1298   if (Depth > 15)
1299     return false;
1300   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1301     SDValue O0 = Val->getOperand(0);
1302     SDValue O1 = Val->getOperand(1);
1303     bool CanPushNegateL;
1304     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1305       return false;
1306     bool CanPushNegateR;
1307     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1308       return false;
1309     // We cannot push a negate through an AND operation (it would become an OR),
1310     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1311     // push the negate through the x/y subtrees.
1312     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1313     return true;
1314   }
1315   return false;
1316 }
1317
1318 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1319 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1320 /// Tries to transform the given i1 producing node @p Val to a series compare
1321 /// and conditional compare operations. @returns an NZCV flags producing node
1322 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1323 /// transformation was not possible.
1324 /// On recursive invocations @p PushNegate may be set to true to have negation
1325 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1326 /// for the comparisons in the current subtree; @p Depth limits the search
1327 /// depth to avoid stack overflow.
1328 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1329     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1330     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1331     unsigned Depth = 0) {
1332   // We're at a tree leaf, produce a conditional comparison operation.
1333   unsigned Opcode = Val->getOpcode();
1334   if (Opcode == ISD::SETCC) {
1335     SDValue LHS = Val->getOperand(0);
1336     SDValue RHS = Val->getOperand(1);
1337     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1338     bool isInteger = LHS.getValueType().isInteger();
1339     if (PushNegate)
1340       CC = getSetCCInverse(CC, isInteger);
1341     SDLoc DL(Val);
1342     // Determine OutCC and handle FP special case.
1343     if (isInteger) {
1344       OutCC = changeIntCCToAArch64CC(CC);
1345     } else {
1346       assert(LHS.getValueType().isFloatingPoint());
1347       AArch64CC::CondCode ExtraCC;
1348       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1349       // Surpisingly some floating point conditions can't be tested with a
1350       // single condition code. Construct an additional comparison in this case.
1351       // See comment below on how we deal with OR conditions.
1352       if (ExtraCC != AArch64CC::AL) {
1353         SDValue ExtraCmp;
1354         if (!CCOp.getNode())
1355           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1356         else {
1357           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1358           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1359           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1360           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1361                                                NZCV, DL, DAG);
1362         }
1363         CCOp = ExtraCmp;
1364         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1365         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1366       }
1367     }
1368
1369     // Produce a normal comparison if we are first in the chain
1370     if (!CCOp.getNode())
1371       return emitComparison(LHS, RHS, CC, DL, DAG);
1372     // Otherwise produce a ccmp.
1373     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1374     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1375     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1376     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1377                                      DAG);
1378   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1379     return SDValue();
1380
1381   assert((Opcode == ISD::OR || !PushNegate)
1382          && "Can only push negate through OR operation");
1383
1384   // Check if both sides can be transformed.
1385   SDValue LHS = Val->getOperand(0);
1386   SDValue RHS = Val->getOperand(1);
1387   bool CanPushNegateL;
1388   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1389     return SDValue();
1390   bool CanPushNegateR;
1391   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1392     return SDValue();
1393
1394   // Do we need to negate our operands?
1395   bool NegateOperands = Opcode == ISD::OR;
1396   // We can negate the results of all previous operations by inverting the
1397   // predicate flags giving us a free negation for one side. For the other side
1398   // we need to be able to push the negation to the leafs of the tree.
1399   if (NegateOperands) {
1400     if (!CanPushNegateL && !CanPushNegateR)
1401       return SDValue();
1402     // Order the side where we can push the negate through to LHS.
1403     if (!CanPushNegateL && CanPushNegateR)
1404       std::swap(LHS, RHS);
1405   } else {
1406     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1407     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1408     if (NeedsNegOutL && NeedsNegOutR)
1409       return SDValue();
1410     // Order the side where we need to negate the output flags to RHS so it
1411     // gets emitted first.
1412     if (NeedsNegOutL)
1413       std::swap(LHS, RHS);
1414   }
1415
1416   // Emit RHS. If we want to negate the tree we only need to push a negate
1417   // through if we are already in a PushNegate case, otherwise we can negate
1418   // the "flags to test" afterwards.
1419   AArch64CC::CondCode RHSCC;
1420   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1421                                                 CCOp, Predicate, Depth+1);
1422   if (NegateOperands && !PushNegate)
1423     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1424   // Emit LHS. We must push the negate through if we need to negate it.
1425   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1426                                                 CmpR, RHSCC, Depth+1);
1427   // If we transformed an OR to and AND then we have to negate the result
1428   // (or absorb a PushNegate resulting in a double negation).
1429   if (Opcode == ISD::OR && !PushNegate)
1430     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1431   return CmpL;
1432 }
1433
1434 /// @}
1435
1436 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1437                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1438   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1439     EVT VT = RHS.getValueType();
1440     uint64_t C = RHSC->getZExtValue();
1441     if (!isLegalArithImmed(C)) {
1442       // Constant does not fit, try adjusting it by one?
1443       switch (CC) {
1444       default:
1445         break;
1446       case ISD::SETLT:
1447       case ISD::SETGE:
1448         if ((VT == MVT::i32 && C != 0x80000000 &&
1449              isLegalArithImmed((uint32_t)(C - 1))) ||
1450             (VT == MVT::i64 && C != 0x80000000ULL &&
1451              isLegalArithImmed(C - 1ULL))) {
1452           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1453           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1454           RHS = DAG.getConstant(C, dl, VT);
1455         }
1456         break;
1457       case ISD::SETULT:
1458       case ISD::SETUGE:
1459         if ((VT == MVT::i32 && C != 0 &&
1460              isLegalArithImmed((uint32_t)(C - 1))) ||
1461             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1462           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1463           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1464           RHS = DAG.getConstant(C, dl, VT);
1465         }
1466         break;
1467       case ISD::SETLE:
1468       case ISD::SETGT:
1469         if ((VT == MVT::i32 && C != INT32_MAX &&
1470              isLegalArithImmed((uint32_t)(C + 1))) ||
1471             (VT == MVT::i64 && C != INT64_MAX &&
1472              isLegalArithImmed(C + 1ULL))) {
1473           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1474           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1475           RHS = DAG.getConstant(C, dl, VT);
1476         }
1477         break;
1478       case ISD::SETULE:
1479       case ISD::SETUGT:
1480         if ((VT == MVT::i32 && C != UINT32_MAX &&
1481              isLegalArithImmed((uint32_t)(C + 1))) ||
1482             (VT == MVT::i64 && C != UINT64_MAX &&
1483              isLegalArithImmed(C + 1ULL))) {
1484           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1485           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1486           RHS = DAG.getConstant(C, dl, VT);
1487         }
1488         break;
1489       }
1490     }
1491   }
1492   SDValue Cmp;
1493   AArch64CC::CondCode AArch64CC;
1494   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1495     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1496
1497     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1498     // For the i8 operand, the largest immediate is 255, so this can be easily
1499     // encoded in the compare instruction. For the i16 operand, however, the
1500     // largest immediate cannot be encoded in the compare.
1501     // Therefore, use a sign extending load and cmn to avoid materializing the
1502     // -1 constant. For example,
1503     // movz w1, #65535
1504     // ldrh w0, [x0, #0]
1505     // cmp w0, w1
1506     // >
1507     // ldrsh w0, [x0, #0]
1508     // cmn w0, #1
1509     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1510     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1511     // ensure both the LHS and RHS are truly zero extended and to make sure the
1512     // transformation is profitable.
1513     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1514         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1515         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1516         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1517       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1518       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1519         SDValue SExt =
1520             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1521                         DAG.getValueType(MVT::i16));
1522         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1523                                                    RHS.getValueType()),
1524                              CC, dl, DAG);
1525         AArch64CC = changeIntCCToAArch64CC(CC);
1526       }
1527     }
1528
1529     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1530       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1531         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1532           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1533       }
1534     }
1535   }
1536
1537   if (!Cmp) {
1538     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1539     AArch64CC = changeIntCCToAArch64CC(CC);
1540   }
1541   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1542   return Cmp;
1543 }
1544
1545 static std::pair<SDValue, SDValue>
1546 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1547   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1548          "Unsupported value type");
1549   SDValue Value, Overflow;
1550   SDLoc DL(Op);
1551   SDValue LHS = Op.getOperand(0);
1552   SDValue RHS = Op.getOperand(1);
1553   unsigned Opc = 0;
1554   switch (Op.getOpcode()) {
1555   default:
1556     llvm_unreachable("Unknown overflow instruction!");
1557   case ISD::SADDO:
1558     Opc = AArch64ISD::ADDS;
1559     CC = AArch64CC::VS;
1560     break;
1561   case ISD::UADDO:
1562     Opc = AArch64ISD::ADDS;
1563     CC = AArch64CC::HS;
1564     break;
1565   case ISD::SSUBO:
1566     Opc = AArch64ISD::SUBS;
1567     CC = AArch64CC::VS;
1568     break;
1569   case ISD::USUBO:
1570     Opc = AArch64ISD::SUBS;
1571     CC = AArch64CC::LO;
1572     break;
1573   // Multiply needs a little bit extra work.
1574   case ISD::SMULO:
1575   case ISD::UMULO: {
1576     CC = AArch64CC::NE;
1577     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1578     if (Op.getValueType() == MVT::i32) {
1579       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1580       // For a 32 bit multiply with overflow check we want the instruction
1581       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1582       // need to generate the following pattern:
1583       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1584       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1585       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1586       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1587       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1588                                 DAG.getConstant(0, DL, MVT::i64));
1589       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1590       // operation. We need to clear out the upper 32 bits, because we used a
1591       // widening multiply that wrote all 64 bits. In the end this should be a
1592       // noop.
1593       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1594       if (IsSigned) {
1595         // The signed overflow check requires more than just a simple check for
1596         // any bit set in the upper 32 bits of the result. These bits could be
1597         // just the sign bits of a negative number. To perform the overflow
1598         // check we have to arithmetic shift right the 32nd bit of the result by
1599         // 31 bits. Then we compare the result to the upper 32 bits.
1600         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1601                                         DAG.getConstant(32, DL, MVT::i64));
1602         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1603         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1604                                         DAG.getConstant(31, DL, MVT::i64));
1605         // It is important that LowerBits is last, otherwise the arithmetic
1606         // shift will not be folded into the compare (SUBS).
1607         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1608         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1609                        .getValue(1);
1610       } else {
1611         // The overflow check for unsigned multiply is easy. We only need to
1612         // check if any of the upper 32 bits are set. This can be done with a
1613         // CMP (shifted register). For that we need to generate the following
1614         // pattern:
1615         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1616         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1617                                         DAG.getConstant(32, DL, MVT::i64));
1618         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1619         Overflow =
1620             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1621                         DAG.getConstant(0, DL, MVT::i64),
1622                         UpperBits).getValue(1);
1623       }
1624       break;
1625     }
1626     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1627     // For the 64 bit multiply
1628     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1629     if (IsSigned) {
1630       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1631       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1632                                       DAG.getConstant(63, DL, MVT::i64));
1633       // It is important that LowerBits is last, otherwise the arithmetic
1634       // shift will not be folded into the compare (SUBS).
1635       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1636       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1637                      .getValue(1);
1638     } else {
1639       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1640       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1641       Overflow =
1642           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1643                       DAG.getConstant(0, DL, MVT::i64),
1644                       UpperBits).getValue(1);
1645     }
1646     break;
1647   }
1648   } // switch (...)
1649
1650   if (Opc) {
1651     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1652
1653     // Emit the AArch64 operation with overflow check.
1654     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1655     Overflow = Value.getValue(1);
1656   }
1657   return std::make_pair(Value, Overflow);
1658 }
1659
1660 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1661                                              RTLIB::Libcall Call) const {
1662   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1663   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1664 }
1665
1666 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1667   SDValue Sel = Op.getOperand(0);
1668   SDValue Other = Op.getOperand(1);
1669
1670   // If neither operand is a SELECT_CC, give up.
1671   if (Sel.getOpcode() != ISD::SELECT_CC)
1672     std::swap(Sel, Other);
1673   if (Sel.getOpcode() != ISD::SELECT_CC)
1674     return Op;
1675
1676   // The folding we want to perform is:
1677   // (xor x, (select_cc a, b, cc, 0, -1) )
1678   //   -->
1679   // (csel x, (xor x, -1), cc ...)
1680   //
1681   // The latter will get matched to a CSINV instruction.
1682
1683   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1684   SDValue LHS = Sel.getOperand(0);
1685   SDValue RHS = Sel.getOperand(1);
1686   SDValue TVal = Sel.getOperand(2);
1687   SDValue FVal = Sel.getOperand(3);
1688   SDLoc dl(Sel);
1689
1690   // FIXME: This could be generalized to non-integer comparisons.
1691   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1692     return Op;
1693
1694   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1695   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1696
1697   // The values aren't constants, this isn't the pattern we're looking for.
1698   if (!CFVal || !CTVal)
1699     return Op;
1700
1701   // We can commute the SELECT_CC by inverting the condition.  This
1702   // might be needed to make this fit into a CSINV pattern.
1703   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1704     std::swap(TVal, FVal);
1705     std::swap(CTVal, CFVal);
1706     CC = ISD::getSetCCInverse(CC, true);
1707   }
1708
1709   // If the constants line up, perform the transform!
1710   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1711     SDValue CCVal;
1712     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1713
1714     FVal = Other;
1715     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1716                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1717
1718     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1719                        CCVal, Cmp);
1720   }
1721
1722   return Op;
1723 }
1724
1725 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1726   EVT VT = Op.getValueType();
1727
1728   // Let legalize expand this if it isn't a legal type yet.
1729   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1730     return SDValue();
1731
1732   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1733
1734   unsigned Opc;
1735   bool ExtraOp = false;
1736   switch (Op.getOpcode()) {
1737   default:
1738     llvm_unreachable("Invalid code");
1739   case ISD::ADDC:
1740     Opc = AArch64ISD::ADDS;
1741     break;
1742   case ISD::SUBC:
1743     Opc = AArch64ISD::SUBS;
1744     break;
1745   case ISD::ADDE:
1746     Opc = AArch64ISD::ADCS;
1747     ExtraOp = true;
1748     break;
1749   case ISD::SUBE:
1750     Opc = AArch64ISD::SBCS;
1751     ExtraOp = true;
1752     break;
1753   }
1754
1755   if (!ExtraOp)
1756     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1757   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1758                      Op.getOperand(2));
1759 }
1760
1761 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1762   // Let legalize expand this if it isn't a legal type yet.
1763   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1764     return SDValue();
1765
1766   SDLoc dl(Op);
1767   AArch64CC::CondCode CC;
1768   // The actual operation that sets the overflow or carry flag.
1769   SDValue Value, Overflow;
1770   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1771
1772   // We use 0 and 1 as false and true values.
1773   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1774   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1775
1776   // We use an inverted condition, because the conditional select is inverted
1777   // too. This will allow it to be selected to a single instruction:
1778   // CSINC Wd, WZR, WZR, invert(cond).
1779   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1780   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1781                          CCVal, Overflow);
1782
1783   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1784   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1785 }
1786
1787 // Prefetch operands are:
1788 // 1: Address to prefetch
1789 // 2: bool isWrite
1790 // 3: int locality (0 = no locality ... 3 = extreme locality)
1791 // 4: bool isDataCache
1792 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1793   SDLoc DL(Op);
1794   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1795   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1796   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1797
1798   bool IsStream = !Locality;
1799   // When the locality number is set
1800   if (Locality) {
1801     // The front-end should have filtered out the out-of-range values
1802     assert(Locality <= 3 && "Prefetch locality out-of-range");
1803     // The locality degree is the opposite of the cache speed.
1804     // Put the number the other way around.
1805     // The encoding starts at 0 for level 1
1806     Locality = 3 - Locality;
1807   }
1808
1809   // built the mask value encoding the expected behavior.
1810   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1811                    (!IsData << 3) |     // IsDataCache bit
1812                    (Locality << 1) |    // Cache level bits
1813                    (unsigned)IsStream;  // Stream bit
1814   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1815                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1816 }
1817
1818 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1819                                               SelectionDAG &DAG) const {
1820   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1821
1822   RTLIB::Libcall LC;
1823   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1824
1825   return LowerF128Call(Op, DAG, LC);
1826 }
1827
1828 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1829                                              SelectionDAG &DAG) const {
1830   if (Op.getOperand(0).getValueType() != MVT::f128) {
1831     // It's legal except when f128 is involved
1832     return Op;
1833   }
1834
1835   RTLIB::Libcall LC;
1836   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1837
1838   // FP_ROUND node has a second operand indicating whether it is known to be
1839   // precise. That doesn't take part in the LibCall so we can't directly use
1840   // LowerF128Call.
1841   SDValue SrcVal = Op.getOperand(0);
1842   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1843                      SDLoc(Op)).first;
1844 }
1845
1846 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1847   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1848   // Any additional optimization in this function should be recorded
1849   // in the cost tables.
1850   EVT InVT = Op.getOperand(0).getValueType();
1851   EVT VT = Op.getValueType();
1852
1853   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1854     SDLoc dl(Op);
1855     SDValue Cv =
1856         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1857                     Op.getOperand(0));
1858     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1859   }
1860
1861   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1862     SDLoc dl(Op);
1863     MVT ExtVT =
1864         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1865                          VT.getVectorNumElements());
1866     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1867     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1868   }
1869
1870   // Type changing conversions are illegal.
1871   return Op;
1872 }
1873
1874 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1875                                               SelectionDAG &DAG) const {
1876   if (Op.getOperand(0).getValueType().isVector())
1877     return LowerVectorFP_TO_INT(Op, DAG);
1878
1879   // f16 conversions are promoted to f32.
1880   if (Op.getOperand(0).getValueType() == MVT::f16) {
1881     SDLoc dl(Op);
1882     return DAG.getNode(
1883         Op.getOpcode(), dl, Op.getValueType(),
1884         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1885   }
1886
1887   if (Op.getOperand(0).getValueType() != MVT::f128) {
1888     // It's legal except when f128 is involved
1889     return Op;
1890   }
1891
1892   RTLIB::Libcall LC;
1893   if (Op.getOpcode() == ISD::FP_TO_SINT)
1894     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1895   else
1896     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1897
1898   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1899   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1900 }
1901
1902 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1903   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1904   // Any additional optimization in this function should be recorded
1905   // in the cost tables.
1906   EVT VT = Op.getValueType();
1907   SDLoc dl(Op);
1908   SDValue In = Op.getOperand(0);
1909   EVT InVT = In.getValueType();
1910
1911   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1912     MVT CastVT =
1913         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1914                          InVT.getVectorNumElements());
1915     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1916     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1917   }
1918
1919   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1920     unsigned CastOpc =
1921         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1922     EVT CastVT = VT.changeVectorElementTypeToInteger();
1923     In = DAG.getNode(CastOpc, dl, CastVT, In);
1924     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1925   }
1926
1927   return Op;
1928 }
1929
1930 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1931                                             SelectionDAG &DAG) const {
1932   if (Op.getValueType().isVector())
1933     return LowerVectorINT_TO_FP(Op, DAG);
1934
1935   // f16 conversions are promoted to f32.
1936   if (Op.getValueType() == MVT::f16) {
1937     SDLoc dl(Op);
1938     return DAG.getNode(
1939         ISD::FP_ROUND, dl, MVT::f16,
1940         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1941         DAG.getIntPtrConstant(0, dl));
1942   }
1943
1944   // i128 conversions are libcalls.
1945   if (Op.getOperand(0).getValueType() == MVT::i128)
1946     return SDValue();
1947
1948   // Other conversions are legal, unless it's to the completely software-based
1949   // fp128.
1950   if (Op.getValueType() != MVT::f128)
1951     return Op;
1952
1953   RTLIB::Libcall LC;
1954   if (Op.getOpcode() == ISD::SINT_TO_FP)
1955     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1956   else
1957     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1958
1959   return LowerF128Call(Op, DAG, LC);
1960 }
1961
1962 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1963                                             SelectionDAG &DAG) const {
1964   // For iOS, we want to call an alternative entry point: __sincos_stret,
1965   // which returns the values in two S / D registers.
1966   SDLoc dl(Op);
1967   SDValue Arg = Op.getOperand(0);
1968   EVT ArgVT = Arg.getValueType();
1969   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1970
1971   ArgListTy Args;
1972   ArgListEntry Entry;
1973
1974   Entry.Node = Arg;
1975   Entry.Ty = ArgTy;
1976   Entry.isSExt = false;
1977   Entry.isZExt = false;
1978   Args.push_back(Entry);
1979
1980   const char *LibcallName =
1981       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1982   SDValue Callee =
1983       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1984
1985   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1986   TargetLowering::CallLoweringInfo CLI(DAG);
1987   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1988     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1989
1990   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1991   return CallResult.first;
1992 }
1993
1994 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1995   if (Op.getValueType() != MVT::f16)
1996     return SDValue();
1997
1998   assert(Op.getOperand(0).getValueType() == MVT::i16);
1999   SDLoc DL(Op);
2000
2001   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2002   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2003   return SDValue(
2004       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2005                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2006       0);
2007 }
2008
2009 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2010   if (OrigVT.getSizeInBits() >= 64)
2011     return OrigVT;
2012
2013   assert(OrigVT.isSimple() && "Expecting a simple value type");
2014
2015   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2016   switch (OrigSimpleTy) {
2017   default: llvm_unreachable("Unexpected Vector Type");
2018   case MVT::v2i8:
2019   case MVT::v2i16:
2020      return MVT::v2i32;
2021   case MVT::v4i8:
2022     return  MVT::v4i16;
2023   }
2024 }
2025
2026 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2027                                                  const EVT &OrigTy,
2028                                                  const EVT &ExtTy,
2029                                                  unsigned ExtOpcode) {
2030   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2031   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2032   // 64-bits we need to insert a new extension so that it will be 64-bits.
2033   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2034   if (OrigTy.getSizeInBits() >= 64)
2035     return N;
2036
2037   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2038   EVT NewVT = getExtensionTo64Bits(OrigTy);
2039
2040   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2041 }
2042
2043 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2044                                    bool isSigned) {
2045   EVT VT = N->getValueType(0);
2046
2047   if (N->getOpcode() != ISD::BUILD_VECTOR)
2048     return false;
2049
2050   for (const SDValue &Elt : N->op_values()) {
2051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2052       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2053       unsigned HalfSize = EltSize / 2;
2054       if (isSigned) {
2055         if (!isIntN(HalfSize, C->getSExtValue()))
2056           return false;
2057       } else {
2058         if (!isUIntN(HalfSize, C->getZExtValue()))
2059           return false;
2060       }
2061       continue;
2062     }
2063     return false;
2064   }
2065
2066   return true;
2067 }
2068
2069 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2070   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2071     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2072                                              N->getOperand(0)->getValueType(0),
2073                                              N->getValueType(0),
2074                                              N->getOpcode());
2075
2076   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2077   EVT VT = N->getValueType(0);
2078   SDLoc dl(N);
2079   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2080   unsigned NumElts = VT.getVectorNumElements();
2081   MVT TruncVT = MVT::getIntegerVT(EltSize);
2082   SmallVector<SDValue, 8> Ops;
2083   for (unsigned i = 0; i != NumElts; ++i) {
2084     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2085     const APInt &CInt = C->getAPIntValue();
2086     // Element types smaller than 32 bits are not legal, so use i32 elements.
2087     // The values are implicitly truncated so sext vs. zext doesn't matter.
2088     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2089   }
2090   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2091                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2092 }
2093
2094 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2095   if (N->getOpcode() == ISD::SIGN_EXTEND)
2096     return true;
2097   if (isExtendedBUILD_VECTOR(N, DAG, true))
2098     return true;
2099   return false;
2100 }
2101
2102 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2103   if (N->getOpcode() == ISD::ZERO_EXTEND)
2104     return true;
2105   if (isExtendedBUILD_VECTOR(N, DAG, false))
2106     return true;
2107   return false;
2108 }
2109
2110 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2111   unsigned Opcode = N->getOpcode();
2112   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2113     SDNode *N0 = N->getOperand(0).getNode();
2114     SDNode *N1 = N->getOperand(1).getNode();
2115     return N0->hasOneUse() && N1->hasOneUse() &&
2116       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2117   }
2118   return false;
2119 }
2120
2121 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2122   unsigned Opcode = N->getOpcode();
2123   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2124     SDNode *N0 = N->getOperand(0).getNode();
2125     SDNode *N1 = N->getOperand(1).getNode();
2126     return N0->hasOneUse() && N1->hasOneUse() &&
2127       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2128   }
2129   return false;
2130 }
2131
2132 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2133   // Multiplications are only custom-lowered for 128-bit vectors so that
2134   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2135   EVT VT = Op.getValueType();
2136   assert(VT.is128BitVector() && VT.isInteger() &&
2137          "unexpected type for custom-lowering ISD::MUL");
2138   SDNode *N0 = Op.getOperand(0).getNode();
2139   SDNode *N1 = Op.getOperand(1).getNode();
2140   unsigned NewOpc = 0;
2141   bool isMLA = false;
2142   bool isN0SExt = isSignExtended(N0, DAG);
2143   bool isN1SExt = isSignExtended(N1, DAG);
2144   if (isN0SExt && isN1SExt)
2145     NewOpc = AArch64ISD::SMULL;
2146   else {
2147     bool isN0ZExt = isZeroExtended(N0, DAG);
2148     bool isN1ZExt = isZeroExtended(N1, DAG);
2149     if (isN0ZExt && isN1ZExt)
2150       NewOpc = AArch64ISD::UMULL;
2151     else if (isN1SExt || isN1ZExt) {
2152       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2153       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2154       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2155         NewOpc = AArch64ISD::SMULL;
2156         isMLA = true;
2157       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2158         NewOpc =  AArch64ISD::UMULL;
2159         isMLA = true;
2160       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2161         std::swap(N0, N1);
2162         NewOpc =  AArch64ISD::UMULL;
2163         isMLA = true;
2164       }
2165     }
2166
2167     if (!NewOpc) {
2168       if (VT == MVT::v2i64)
2169         // Fall through to expand this.  It is not legal.
2170         return SDValue();
2171       else
2172         // Other vector multiplications are legal.
2173         return Op;
2174     }
2175   }
2176
2177   // Legalize to a S/UMULL instruction
2178   SDLoc DL(Op);
2179   SDValue Op0;
2180   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2181   if (!isMLA) {
2182     Op0 = skipExtensionForVectorMULL(N0, DAG);
2183     assert(Op0.getValueType().is64BitVector() &&
2184            Op1.getValueType().is64BitVector() &&
2185            "unexpected types for extended operands to VMULL");
2186     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2187   }
2188   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2189   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2190   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2191   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2192   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2193   EVT Op1VT = Op1.getValueType();
2194   return DAG.getNode(N0->getOpcode(), DL, VT,
2195                      DAG.getNode(NewOpc, DL, VT,
2196                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2197                      DAG.getNode(NewOpc, DL, VT,
2198                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2199 }
2200
2201 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2202                                                      SelectionDAG &DAG) const {
2203   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2204   SDLoc dl(Op);
2205   switch (IntNo) {
2206   default: return SDValue();    // Don't custom lower most intrinsics.
2207   case Intrinsic::aarch64_thread_pointer: {
2208     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2209     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2210   }
2211   case Intrinsic::aarch64_neon_smax:
2212     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2213                        Op.getOperand(1), Op.getOperand(2));
2214   case Intrinsic::aarch64_neon_umax:
2215     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2216                        Op.getOperand(1), Op.getOperand(2));
2217   case Intrinsic::aarch64_neon_smin:
2218     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2219                        Op.getOperand(1), Op.getOperand(2));
2220   case Intrinsic::aarch64_neon_umin:
2221     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2222                        Op.getOperand(1), Op.getOperand(2));
2223   }
2224 }
2225
2226 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2227                                               SelectionDAG &DAG) const {
2228   switch (Op.getOpcode()) {
2229   default:
2230     llvm_unreachable("unimplemented operand");
2231     return SDValue();
2232   case ISD::BITCAST:
2233     return LowerBITCAST(Op, DAG);
2234   case ISD::GlobalAddress:
2235     return LowerGlobalAddress(Op, DAG);
2236   case ISD::GlobalTLSAddress:
2237     return LowerGlobalTLSAddress(Op, DAG);
2238   case ISD::SETCC:
2239     return LowerSETCC(Op, DAG);
2240   case ISD::BR_CC:
2241     return LowerBR_CC(Op, DAG);
2242   case ISD::SELECT:
2243     return LowerSELECT(Op, DAG);
2244   case ISD::SELECT_CC:
2245     return LowerSELECT_CC(Op, DAG);
2246   case ISD::JumpTable:
2247     return LowerJumpTable(Op, DAG);
2248   case ISD::ConstantPool:
2249     return LowerConstantPool(Op, DAG);
2250   case ISD::BlockAddress:
2251     return LowerBlockAddress(Op, DAG);
2252   case ISD::VASTART:
2253     return LowerVASTART(Op, DAG);
2254   case ISD::VACOPY:
2255     return LowerVACOPY(Op, DAG);
2256   case ISD::VAARG:
2257     return LowerVAARG(Op, DAG);
2258   case ISD::ADDC:
2259   case ISD::ADDE:
2260   case ISD::SUBC:
2261   case ISD::SUBE:
2262     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2263   case ISD::SADDO:
2264   case ISD::UADDO:
2265   case ISD::SSUBO:
2266   case ISD::USUBO:
2267   case ISD::SMULO:
2268   case ISD::UMULO:
2269     return LowerXALUO(Op, DAG);
2270   case ISD::FADD:
2271     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2272   case ISD::FSUB:
2273     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2274   case ISD::FMUL:
2275     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2276   case ISD::FDIV:
2277     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2278   case ISD::FP_ROUND:
2279     return LowerFP_ROUND(Op, DAG);
2280   case ISD::FP_EXTEND:
2281     return LowerFP_EXTEND(Op, DAG);
2282   case ISD::FRAMEADDR:
2283     return LowerFRAMEADDR(Op, DAG);
2284   case ISD::RETURNADDR:
2285     return LowerRETURNADDR(Op, DAG);
2286   case ISD::INSERT_VECTOR_ELT:
2287     return LowerINSERT_VECTOR_ELT(Op, DAG);
2288   case ISD::EXTRACT_VECTOR_ELT:
2289     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2290   case ISD::BUILD_VECTOR:
2291     return LowerBUILD_VECTOR(Op, DAG);
2292   case ISD::VECTOR_SHUFFLE:
2293     return LowerVECTOR_SHUFFLE(Op, DAG);
2294   case ISD::EXTRACT_SUBVECTOR:
2295     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2296   case ISD::SRA:
2297   case ISD::SRL:
2298   case ISD::SHL:
2299     return LowerVectorSRA_SRL_SHL(Op, DAG);
2300   case ISD::SHL_PARTS:
2301     return LowerShiftLeftParts(Op, DAG);
2302   case ISD::SRL_PARTS:
2303   case ISD::SRA_PARTS:
2304     return LowerShiftRightParts(Op, DAG);
2305   case ISD::CTPOP:
2306     return LowerCTPOP(Op, DAG);
2307   case ISD::FCOPYSIGN:
2308     return LowerFCOPYSIGN(Op, DAG);
2309   case ISD::AND:
2310     return LowerVectorAND(Op, DAG);
2311   case ISD::OR:
2312     return LowerVectorOR(Op, DAG);
2313   case ISD::XOR:
2314     return LowerXOR(Op, DAG);
2315   case ISD::PREFETCH:
2316     return LowerPREFETCH(Op, DAG);
2317   case ISD::SINT_TO_FP:
2318   case ISD::UINT_TO_FP:
2319     return LowerINT_TO_FP(Op, DAG);
2320   case ISD::FP_TO_SINT:
2321   case ISD::FP_TO_UINT:
2322     return LowerFP_TO_INT(Op, DAG);
2323   case ISD::FSINCOS:
2324     return LowerFSINCOS(Op, DAG);
2325   case ISD::MUL:
2326     return LowerMUL(Op, DAG);
2327   case ISD::INTRINSIC_WO_CHAIN:
2328     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2329   }
2330 }
2331
2332 /// getFunctionAlignment - Return the Log2 alignment of this function.
2333 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2334   return 2;
2335 }
2336
2337 //===----------------------------------------------------------------------===//
2338 //                      Calling Convention Implementation
2339 //===----------------------------------------------------------------------===//
2340
2341 #include "AArch64GenCallingConv.inc"
2342
2343 /// Selects the correct CCAssignFn for a given CallingConvention value.
2344 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2345                                                      bool IsVarArg) const {
2346   switch (CC) {
2347   default:
2348     llvm_unreachable("Unsupported calling convention.");
2349   case CallingConv::WebKit_JS:
2350     return CC_AArch64_WebKit_JS;
2351   case CallingConv::GHC:
2352     return CC_AArch64_GHC;
2353   case CallingConv::C:
2354   case CallingConv::Fast:
2355     if (!Subtarget->isTargetDarwin())
2356       return CC_AArch64_AAPCS;
2357     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2358   }
2359 }
2360
2361 SDValue AArch64TargetLowering::LowerFormalArguments(
2362     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2363     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2364     SmallVectorImpl<SDValue> &InVals) const {
2365   MachineFunction &MF = DAG.getMachineFunction();
2366   MachineFrameInfo *MFI = MF.getFrameInfo();
2367
2368   // Assign locations to all of the incoming arguments.
2369   SmallVector<CCValAssign, 16> ArgLocs;
2370   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2371                  *DAG.getContext());
2372
2373   // At this point, Ins[].VT may already be promoted to i32. To correctly
2374   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2375   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2376   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2377   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2378   // LocVT.
2379   unsigned NumArgs = Ins.size();
2380   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2381   unsigned CurArgIdx = 0;
2382   for (unsigned i = 0; i != NumArgs; ++i) {
2383     MVT ValVT = Ins[i].VT;
2384     if (Ins[i].isOrigArg()) {
2385       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2386       CurArgIdx = Ins[i].getOrigArgIndex();
2387
2388       // Get type of the original argument.
2389       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2390                                   /*AllowUnknown*/ true);
2391       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2392       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2393       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2394         ValVT = MVT::i8;
2395       else if (ActualMVT == MVT::i16)
2396         ValVT = MVT::i16;
2397     }
2398     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2399     bool Res =
2400         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2401     assert(!Res && "Call operand has unhandled type");
2402     (void)Res;
2403   }
2404   assert(ArgLocs.size() == Ins.size());
2405   SmallVector<SDValue, 16> ArgValues;
2406   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2407     CCValAssign &VA = ArgLocs[i];
2408
2409     if (Ins[i].Flags.isByVal()) {
2410       // Byval is used for HFAs in the PCS, but the system should work in a
2411       // non-compliant manner for larger structs.
2412       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2413       int Size = Ins[i].Flags.getByValSize();
2414       unsigned NumRegs = (Size + 7) / 8;
2415
2416       // FIXME: This works on big-endian for composite byvals, which are the common
2417       // case. It should also work for fundamental types too.
2418       unsigned FrameIdx =
2419         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2420       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2421       InVals.push_back(FrameIdxN);
2422
2423       continue;
2424     }
2425     
2426     if (VA.isRegLoc()) {
2427       // Arguments stored in registers.
2428       EVT RegVT = VA.getLocVT();
2429
2430       SDValue ArgValue;
2431       const TargetRegisterClass *RC;
2432
2433       if (RegVT == MVT::i32)
2434         RC = &AArch64::GPR32RegClass;
2435       else if (RegVT == MVT::i64)
2436         RC = &AArch64::GPR64RegClass;
2437       else if (RegVT == MVT::f16)
2438         RC = &AArch64::FPR16RegClass;
2439       else if (RegVT == MVT::f32)
2440         RC = &AArch64::FPR32RegClass;
2441       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2442         RC = &AArch64::FPR64RegClass;
2443       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2444         RC = &AArch64::FPR128RegClass;
2445       else
2446         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2447
2448       // Transform the arguments in physical registers into virtual ones.
2449       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2450       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2451
2452       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2453       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2454       // truncate to the right size.
2455       switch (VA.getLocInfo()) {
2456       default:
2457         llvm_unreachable("Unknown loc info!");
2458       case CCValAssign::Full:
2459         break;
2460       case CCValAssign::BCvt:
2461         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2462         break;
2463       case CCValAssign::AExt:
2464       case CCValAssign::SExt:
2465       case CCValAssign::ZExt:
2466         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2467         // nodes after our lowering.
2468         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2469         break;
2470       }
2471
2472       InVals.push_back(ArgValue);
2473
2474     } else { // VA.isRegLoc()
2475       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2476       unsigned ArgOffset = VA.getLocMemOffset();
2477       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2478
2479       uint32_t BEAlign = 0;
2480       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2481           !Ins[i].Flags.isInConsecutiveRegs())
2482         BEAlign = 8 - ArgSize;
2483
2484       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2485
2486       // Create load nodes to retrieve arguments from the stack.
2487       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2488       SDValue ArgValue;
2489
2490       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2491       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2492       MVT MemVT = VA.getValVT();
2493
2494       switch (VA.getLocInfo()) {
2495       default:
2496         break;
2497       case CCValAssign::BCvt:
2498         MemVT = VA.getLocVT();
2499         break;
2500       case CCValAssign::SExt:
2501         ExtType = ISD::SEXTLOAD;
2502         break;
2503       case CCValAssign::ZExt:
2504         ExtType = ISD::ZEXTLOAD;
2505         break;
2506       case CCValAssign::AExt:
2507         ExtType = ISD::EXTLOAD;
2508         break;
2509       }
2510
2511       ArgValue = DAG.getExtLoad(
2512           ExtType, DL, VA.getLocVT(), Chain, FIN,
2513           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2514           MemVT, false, false, false, 0);
2515
2516       InVals.push_back(ArgValue);
2517     }
2518   }
2519
2520   // varargs
2521   if (isVarArg) {
2522     if (!Subtarget->isTargetDarwin()) {
2523       // The AAPCS variadic function ABI is identical to the non-variadic
2524       // one. As a result there may be more arguments in registers and we should
2525       // save them for future reference.
2526       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2527     }
2528
2529     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2530     // This will point to the next argument passed via stack.
2531     unsigned StackOffset = CCInfo.getNextStackOffset();
2532     // We currently pass all varargs at 8-byte alignment.
2533     StackOffset = ((StackOffset + 7) & ~7);
2534     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2535   }
2536
2537   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2538   unsigned StackArgSize = CCInfo.getNextStackOffset();
2539   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2540   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2541     // This is a non-standard ABI so by fiat I say we're allowed to make full
2542     // use of the stack area to be popped, which must be aligned to 16 bytes in
2543     // any case:
2544     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2545
2546     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2547     // a multiple of 16.
2548     FuncInfo->setArgumentStackToRestore(StackArgSize);
2549
2550     // This realignment carries over to the available bytes below. Our own
2551     // callers will guarantee the space is free by giving an aligned value to
2552     // CALLSEQ_START.
2553   }
2554   // Even if we're not expected to free up the space, it's useful to know how
2555   // much is there while considering tail calls (because we can reuse it).
2556   FuncInfo->setBytesInStackArgArea(StackArgSize);
2557
2558   return Chain;
2559 }
2560
2561 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2562                                                 SelectionDAG &DAG, SDLoc DL,
2563                                                 SDValue &Chain) const {
2564   MachineFunction &MF = DAG.getMachineFunction();
2565   MachineFrameInfo *MFI = MF.getFrameInfo();
2566   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2567   auto PtrVT = getPointerTy(DAG.getDataLayout());
2568
2569   SmallVector<SDValue, 8> MemOps;
2570
2571   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2572                                           AArch64::X3, AArch64::X4, AArch64::X5,
2573                                           AArch64::X6, AArch64::X7 };
2574   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2575   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2576
2577   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2578   int GPRIdx = 0;
2579   if (GPRSaveSize != 0) {
2580     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2581
2582     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2583
2584     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2585       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2586       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2587       SDValue Store = DAG.getStore(
2588           Val.getValue(1), DL, Val, FIN,
2589           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2590           false, 0);
2591       MemOps.push_back(Store);
2592       FIN =
2593           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2594     }
2595   }
2596   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2597   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2598
2599   if (Subtarget->hasFPARMv8()) {
2600     static const MCPhysReg FPRArgRegs[] = {
2601         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2602         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2603     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2604     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2605
2606     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2607     int FPRIdx = 0;
2608     if (FPRSaveSize != 0) {
2609       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2610
2611       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2612
2613       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2614         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2615         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2616
2617         SDValue Store = DAG.getStore(
2618             Val.getValue(1), DL, Val, FIN,
2619             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2620             false, false, 0);
2621         MemOps.push_back(Store);
2622         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2623                           DAG.getConstant(16, DL, PtrVT));
2624       }
2625     }
2626     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2627     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2628   }
2629
2630   if (!MemOps.empty()) {
2631     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2632   }
2633 }
2634
2635 /// LowerCallResult - Lower the result values of a call into the
2636 /// appropriate copies out of appropriate physical registers.
2637 SDValue AArch64TargetLowering::LowerCallResult(
2638     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2639     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2640     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2641     SDValue ThisVal) const {
2642   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2643                           ? RetCC_AArch64_WebKit_JS
2644                           : RetCC_AArch64_AAPCS;
2645   // Assign locations to each value returned by this call.
2646   SmallVector<CCValAssign, 16> RVLocs;
2647   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2648                  *DAG.getContext());
2649   CCInfo.AnalyzeCallResult(Ins, RetCC);
2650
2651   // Copy all of the result registers out of their specified physreg.
2652   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2653     CCValAssign VA = RVLocs[i];
2654
2655     // Pass 'this' value directly from the argument to return value, to avoid
2656     // reg unit interference
2657     if (i == 0 && isThisReturn) {
2658       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2659              "unexpected return calling convention register assignment");
2660       InVals.push_back(ThisVal);
2661       continue;
2662     }
2663
2664     SDValue Val =
2665         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2666     Chain = Val.getValue(1);
2667     InFlag = Val.getValue(2);
2668
2669     switch (VA.getLocInfo()) {
2670     default:
2671       llvm_unreachable("Unknown loc info!");
2672     case CCValAssign::Full:
2673       break;
2674     case CCValAssign::BCvt:
2675       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2676       break;
2677     }
2678
2679     InVals.push_back(Val);
2680   }
2681
2682   return Chain;
2683 }
2684
2685 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2686     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2687     bool isCalleeStructRet, bool isCallerStructRet,
2688     const SmallVectorImpl<ISD::OutputArg> &Outs,
2689     const SmallVectorImpl<SDValue> &OutVals,
2690     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2691   // For CallingConv::C this function knows whether the ABI needs
2692   // changing. That's not true for other conventions so they will have to opt in
2693   // manually.
2694   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2695     return false;
2696
2697   const MachineFunction &MF = DAG.getMachineFunction();
2698   const Function *CallerF = MF.getFunction();
2699   CallingConv::ID CallerCC = CallerF->getCallingConv();
2700   bool CCMatch = CallerCC == CalleeCC;
2701
2702   // Byval parameters hand the function a pointer directly into the stack area
2703   // we want to reuse during a tail call. Working around this *is* possible (see
2704   // X86) but less efficient and uglier in LowerCall.
2705   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2706                                     e = CallerF->arg_end();
2707        i != e; ++i)
2708     if (i->hasByValAttr())
2709       return false;
2710
2711   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2712     if (IsTailCallConvention(CalleeCC) && CCMatch)
2713       return true;
2714     return false;
2715   }
2716
2717   // Externally-defined functions with weak linkage should not be
2718   // tail-called on AArch64 when the OS does not support dynamic
2719   // pre-emption of symbols, as the AAELF spec requires normal calls
2720   // to undefined weak functions to be replaced with a NOP or jump to the
2721   // next instruction. The behaviour of branch instructions in this
2722   // situation (as used for tail calls) is implementation-defined, so we
2723   // cannot rely on the linker replacing the tail call with a return.
2724   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2725     const GlobalValue *GV = G->getGlobal();
2726     const Triple &TT = getTargetMachine().getTargetTriple();
2727     if (GV->hasExternalWeakLinkage() &&
2728         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2729       return false;
2730   }
2731
2732   // Now we search for cases where we can use a tail call without changing the
2733   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2734   // concept.
2735
2736   // I want anyone implementing a new calling convention to think long and hard
2737   // about this assert.
2738   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2739          "Unexpected variadic calling convention");
2740
2741   if (isVarArg && !Outs.empty()) {
2742     // At least two cases here: if caller is fastcc then we can't have any
2743     // memory arguments (we'd be expected to clean up the stack afterwards). If
2744     // caller is C then we could potentially use its argument area.
2745
2746     // FIXME: for now we take the most conservative of these in both cases:
2747     // disallow all variadic memory operands.
2748     SmallVector<CCValAssign, 16> ArgLocs;
2749     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2750                    *DAG.getContext());
2751
2752     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2753     for (const CCValAssign &ArgLoc : ArgLocs)
2754       if (!ArgLoc.isRegLoc())
2755         return false;
2756   }
2757
2758   // If the calling conventions do not match, then we'd better make sure the
2759   // results are returned in the same way as what the caller expects.
2760   if (!CCMatch) {
2761     SmallVector<CCValAssign, 16> RVLocs1;
2762     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2763                     *DAG.getContext());
2764     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2765
2766     SmallVector<CCValAssign, 16> RVLocs2;
2767     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2768                     *DAG.getContext());
2769     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2770
2771     if (RVLocs1.size() != RVLocs2.size())
2772       return false;
2773     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2774       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2775         return false;
2776       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2777         return false;
2778       if (RVLocs1[i].isRegLoc()) {
2779         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2780           return false;
2781       } else {
2782         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2783           return false;
2784       }
2785     }
2786   }
2787
2788   // Nothing more to check if the callee is taking no arguments
2789   if (Outs.empty())
2790     return true;
2791
2792   SmallVector<CCValAssign, 16> ArgLocs;
2793   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2794                  *DAG.getContext());
2795
2796   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2797
2798   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2799
2800   // If the stack arguments for this call would fit into our own save area then
2801   // the call can be made tail.
2802   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2803 }
2804
2805 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2806                                                    SelectionDAG &DAG,
2807                                                    MachineFrameInfo *MFI,
2808                                                    int ClobberedFI) const {
2809   SmallVector<SDValue, 8> ArgChains;
2810   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2811   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2812
2813   // Include the original chain at the beginning of the list. When this is
2814   // used by target LowerCall hooks, this helps legalize find the
2815   // CALLSEQ_BEGIN node.
2816   ArgChains.push_back(Chain);
2817
2818   // Add a chain value for each stack argument corresponding
2819   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2820                             UE = DAG.getEntryNode().getNode()->use_end();
2821        U != UE; ++U)
2822     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2823       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2824         if (FI->getIndex() < 0) {
2825           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2826           int64_t InLastByte = InFirstByte;
2827           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2828
2829           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2830               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2831             ArgChains.push_back(SDValue(L, 1));
2832         }
2833
2834   // Build a tokenfactor for all the chains.
2835   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2836 }
2837
2838 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2839                                                    bool TailCallOpt) const {
2840   return CallCC == CallingConv::Fast && TailCallOpt;
2841 }
2842
2843 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2844   return CallCC == CallingConv::Fast;
2845 }
2846
2847 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2848 /// and add input and output parameter nodes.
2849 SDValue
2850 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2851                                  SmallVectorImpl<SDValue> &InVals) const {
2852   SelectionDAG &DAG = CLI.DAG;
2853   SDLoc &DL = CLI.DL;
2854   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2855   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2856   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2857   SDValue Chain = CLI.Chain;
2858   SDValue Callee = CLI.Callee;
2859   bool &IsTailCall = CLI.IsTailCall;
2860   CallingConv::ID CallConv = CLI.CallConv;
2861   bool IsVarArg = CLI.IsVarArg;
2862
2863   MachineFunction &MF = DAG.getMachineFunction();
2864   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2865   bool IsThisReturn = false;
2866
2867   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2868   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2869   bool IsSibCall = false;
2870
2871   if (IsTailCall) {
2872     // Check if it's really possible to do a tail call.
2873     IsTailCall = isEligibleForTailCallOptimization(
2874         Callee, CallConv, IsVarArg, IsStructRet,
2875         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2876     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2877       report_fatal_error("failed to perform tail call elimination on a call "
2878                          "site marked musttail");
2879
2880     // A sibling call is one where we're under the usual C ABI and not planning
2881     // to change that but can still do a tail call:
2882     if (!TailCallOpt && IsTailCall)
2883       IsSibCall = true;
2884
2885     if (IsTailCall)
2886       ++NumTailCalls;
2887   }
2888
2889   // Analyze operands of the call, assigning locations to each operand.
2890   SmallVector<CCValAssign, 16> ArgLocs;
2891   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2892                  *DAG.getContext());
2893
2894   if (IsVarArg) {
2895     // Handle fixed and variable vector arguments differently.
2896     // Variable vector arguments always go into memory.
2897     unsigned NumArgs = Outs.size();
2898
2899     for (unsigned i = 0; i != NumArgs; ++i) {
2900       MVT ArgVT = Outs[i].VT;
2901       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2902       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2903                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2904       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2905       assert(!Res && "Call operand has unhandled type");
2906       (void)Res;
2907     }
2908   } else {
2909     // At this point, Outs[].VT may already be promoted to i32. To correctly
2910     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2911     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2912     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2913     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2914     // LocVT.
2915     unsigned NumArgs = Outs.size();
2916     for (unsigned i = 0; i != NumArgs; ++i) {
2917       MVT ValVT = Outs[i].VT;
2918       // Get type of the original argument.
2919       EVT ActualVT = getValueType(DAG.getDataLayout(),
2920                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2921                                   /*AllowUnknown*/ true);
2922       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2923       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2924       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2925       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2926         ValVT = MVT::i8;
2927       else if (ActualMVT == MVT::i16)
2928         ValVT = MVT::i16;
2929
2930       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2931       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2932       assert(!Res && "Call operand has unhandled type");
2933       (void)Res;
2934     }
2935   }
2936
2937   // Get a count of how many bytes are to be pushed on the stack.
2938   unsigned NumBytes = CCInfo.getNextStackOffset();
2939
2940   if (IsSibCall) {
2941     // Since we're not changing the ABI to make this a tail call, the memory
2942     // operands are already available in the caller's incoming argument space.
2943     NumBytes = 0;
2944   }
2945
2946   // FPDiff is the byte offset of the call's argument area from the callee's.
2947   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2948   // by this amount for a tail call. In a sibling call it must be 0 because the
2949   // caller will deallocate the entire stack and the callee still expects its
2950   // arguments to begin at SP+0. Completely unused for non-tail calls.
2951   int FPDiff = 0;
2952
2953   if (IsTailCall && !IsSibCall) {
2954     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2955
2956     // Since callee will pop argument stack as a tail call, we must keep the
2957     // popped size 16-byte aligned.
2958     NumBytes = RoundUpToAlignment(NumBytes, 16);
2959
2960     // FPDiff will be negative if this tail call requires more space than we
2961     // would automatically have in our incoming argument space. Positive if we
2962     // can actually shrink the stack.
2963     FPDiff = NumReusableBytes - NumBytes;
2964
2965     // The stack pointer must be 16-byte aligned at all times it's used for a
2966     // memory operation, which in practice means at *all* times and in
2967     // particular across call boundaries. Therefore our own arguments started at
2968     // a 16-byte aligned SP and the delta applied for the tail call should
2969     // satisfy the same constraint.
2970     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2971   }
2972
2973   // Adjust the stack pointer for the new arguments...
2974   // These operations are automatically eliminated by the prolog/epilog pass
2975   if (!IsSibCall)
2976     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2977                                                               true),
2978                                  DL);
2979
2980   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2981                                         getPointerTy(DAG.getDataLayout()));
2982
2983   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2984   SmallVector<SDValue, 8> MemOpChains;
2985   auto PtrVT = getPointerTy(DAG.getDataLayout());
2986
2987   // Walk the register/memloc assignments, inserting copies/loads.
2988   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2989        ++i, ++realArgIdx) {
2990     CCValAssign &VA = ArgLocs[i];
2991     SDValue Arg = OutVals[realArgIdx];
2992     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2993
2994     // Promote the value if needed.
2995     switch (VA.getLocInfo()) {
2996     default:
2997       llvm_unreachable("Unknown loc info!");
2998     case CCValAssign::Full:
2999       break;
3000     case CCValAssign::SExt:
3001       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3002       break;
3003     case CCValAssign::ZExt:
3004       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3005       break;
3006     case CCValAssign::AExt:
3007       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3008         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3009         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3010         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3011       }
3012       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3013       break;
3014     case CCValAssign::BCvt:
3015       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3016       break;
3017     case CCValAssign::FPExt:
3018       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3019       break;
3020     }
3021
3022     if (VA.isRegLoc()) {
3023       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3024         assert(VA.getLocVT() == MVT::i64 &&
3025                "unexpected calling convention register assignment");
3026         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3027                "unexpected use of 'returned'");
3028         IsThisReturn = true;
3029       }
3030       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3031     } else {
3032       assert(VA.isMemLoc());
3033
3034       SDValue DstAddr;
3035       MachinePointerInfo DstInfo;
3036
3037       // FIXME: This works on big-endian for composite byvals, which are the
3038       // common case. It should also work for fundamental types too.
3039       uint32_t BEAlign = 0;
3040       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3041                                         : VA.getValVT().getSizeInBits();
3042       OpSize = (OpSize + 7) / 8;
3043       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3044           !Flags.isInConsecutiveRegs()) {
3045         if (OpSize < 8)
3046           BEAlign = 8 - OpSize;
3047       }
3048       unsigned LocMemOffset = VA.getLocMemOffset();
3049       int32_t Offset = LocMemOffset + BEAlign;
3050       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3051       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3052
3053       if (IsTailCall) {
3054         Offset = Offset + FPDiff;
3055         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3056
3057         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3058         DstInfo =
3059             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3060
3061         // Make sure any stack arguments overlapping with where we're storing
3062         // are loaded before this eventual operation. Otherwise they'll be
3063         // clobbered.
3064         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3065       } else {
3066         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3067
3068         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3069         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3070                                                LocMemOffset);
3071       }
3072
3073       if (Outs[i].Flags.isByVal()) {
3074         SDValue SizeNode =
3075             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3076         SDValue Cpy = DAG.getMemcpy(
3077             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3078             /*isVol = */ false, /*AlwaysInline = */ false,
3079             /*isTailCall = */ false,
3080             DstInfo, MachinePointerInfo());
3081
3082         MemOpChains.push_back(Cpy);
3083       } else {
3084         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3085         // promoted to a legal register type i32, we should truncate Arg back to
3086         // i1/i8/i16.
3087         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3088             VA.getValVT() == MVT::i16)
3089           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3090
3091         SDValue Store =
3092             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3093         MemOpChains.push_back(Store);
3094       }
3095     }
3096   }
3097
3098   if (!MemOpChains.empty())
3099     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3100
3101   // Build a sequence of copy-to-reg nodes chained together with token chain
3102   // and flag operands which copy the outgoing args into the appropriate regs.
3103   SDValue InFlag;
3104   for (auto &RegToPass : RegsToPass) {
3105     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3106                              RegToPass.second, InFlag);
3107     InFlag = Chain.getValue(1);
3108   }
3109
3110   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3111   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3112   // node so that legalize doesn't hack it.
3113   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3114       Subtarget->isTargetMachO()) {
3115     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3116       const GlobalValue *GV = G->getGlobal();
3117       bool InternalLinkage = GV->hasInternalLinkage();
3118       if (InternalLinkage)
3119         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3120       else {
3121         Callee =
3122             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3123         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3124       }
3125     } else if (ExternalSymbolSDNode *S =
3126                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3127       const char *Sym = S->getSymbol();
3128       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3129       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3130     }
3131   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3132     const GlobalValue *GV = G->getGlobal();
3133     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3134   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3135     const char *Sym = S->getSymbol();
3136     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3137   }
3138
3139   // We don't usually want to end the call-sequence here because we would tidy
3140   // the frame up *after* the call, however in the ABI-changing tail-call case
3141   // we've carefully laid out the parameters so that when sp is reset they'll be
3142   // in the correct location.
3143   if (IsTailCall && !IsSibCall) {
3144     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3145                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3146     InFlag = Chain.getValue(1);
3147   }
3148
3149   std::vector<SDValue> Ops;
3150   Ops.push_back(Chain);
3151   Ops.push_back(Callee);
3152
3153   if (IsTailCall) {
3154     // Each tail call may have to adjust the stack by a different amount, so
3155     // this information must travel along with the operation for eventual
3156     // consumption by emitEpilogue.
3157     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3158   }
3159
3160   // Add argument registers to the end of the list so that they are known live
3161   // into the call.
3162   for (auto &RegToPass : RegsToPass)
3163     Ops.push_back(DAG.getRegister(RegToPass.first,
3164                                   RegToPass.second.getValueType()));
3165
3166   // Add a register mask operand representing the call-preserved registers.
3167   const uint32_t *Mask;
3168   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3169   if (IsThisReturn) {
3170     // For 'this' returns, use the X0-preserving mask if applicable
3171     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3172     if (!Mask) {
3173       IsThisReturn = false;
3174       Mask = TRI->getCallPreservedMask(MF, CallConv);
3175     }
3176   } else
3177     Mask = TRI->getCallPreservedMask(MF, CallConv);
3178
3179   assert(Mask && "Missing call preserved mask for calling convention");
3180   Ops.push_back(DAG.getRegisterMask(Mask));
3181
3182   if (InFlag.getNode())
3183     Ops.push_back(InFlag);
3184
3185   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3186
3187   // If we're doing a tall call, use a TC_RETURN here rather than an
3188   // actual call instruction.
3189   if (IsTailCall) {
3190     MF.getFrameInfo()->setHasTailCall();
3191     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3192   }
3193
3194   // Returns a chain and a flag for retval copy to use.
3195   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3196   InFlag = Chain.getValue(1);
3197
3198   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3199                                 ? RoundUpToAlignment(NumBytes, 16)
3200                                 : 0;
3201
3202   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3203                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3204                              InFlag, DL);
3205   if (!Ins.empty())
3206     InFlag = Chain.getValue(1);
3207
3208   // Handle result values, copying them out of physregs into vregs that we
3209   // return.
3210   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3211                          InVals, IsThisReturn,
3212                          IsThisReturn ? OutVals[0] : SDValue());
3213 }
3214
3215 bool AArch64TargetLowering::CanLowerReturn(
3216     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3217     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3218   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3219                           ? RetCC_AArch64_WebKit_JS
3220                           : RetCC_AArch64_AAPCS;
3221   SmallVector<CCValAssign, 16> RVLocs;
3222   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3223   return CCInfo.CheckReturn(Outs, RetCC);
3224 }
3225
3226 SDValue
3227 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3228                                    bool isVarArg,
3229                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3230                                    const SmallVectorImpl<SDValue> &OutVals,
3231                                    SDLoc DL, SelectionDAG &DAG) const {
3232   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3233                           ? RetCC_AArch64_WebKit_JS
3234                           : RetCC_AArch64_AAPCS;
3235   SmallVector<CCValAssign, 16> RVLocs;
3236   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3237                  *DAG.getContext());
3238   CCInfo.AnalyzeReturn(Outs, RetCC);
3239
3240   // Copy the result values into the output registers.
3241   SDValue Flag;
3242   SmallVector<SDValue, 4> RetOps(1, Chain);
3243   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3244        ++i, ++realRVLocIdx) {
3245     CCValAssign &VA = RVLocs[i];
3246     assert(VA.isRegLoc() && "Can only return in registers!");
3247     SDValue Arg = OutVals[realRVLocIdx];
3248
3249     switch (VA.getLocInfo()) {
3250     default:
3251       llvm_unreachable("Unknown loc info!");
3252     case CCValAssign::Full:
3253       if (Outs[i].ArgVT == MVT::i1) {
3254         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3255         // value. This is strictly redundant on Darwin (which uses "zeroext
3256         // i1"), but will be optimised out before ISel.
3257         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3258         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3259       }
3260       break;
3261     case CCValAssign::BCvt:
3262       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3263       break;
3264     }
3265
3266     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3267     Flag = Chain.getValue(1);
3268     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3269   }
3270
3271   RetOps[0] = Chain; // Update chain.
3272
3273   // Add the flag if we have it.
3274   if (Flag.getNode())
3275     RetOps.push_back(Flag);
3276
3277   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3278 }
3279
3280 //===----------------------------------------------------------------------===//
3281 //  Other Lowering Code
3282 //===----------------------------------------------------------------------===//
3283
3284 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3285                                                   SelectionDAG &DAG) const {
3286   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3287   SDLoc DL(Op);
3288   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3289   const GlobalValue *GV = GN->getGlobal();
3290   unsigned char OpFlags =
3291       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3292
3293   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3294          "unexpected offset in global node");
3295
3296   // This also catched the large code model case for Darwin.
3297   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3298     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3299     // FIXME: Once remat is capable of dealing with instructions with register
3300     // operands, expand this into two nodes instead of using a wrapper node.
3301     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3302   }
3303
3304   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3305     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3306            "use of MO_CONSTPOOL only supported on small model");
3307     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3308     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3309     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3310     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3311     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3312     SDValue GlobalAddr = DAG.getLoad(
3313         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3314         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3315         /*isVolatile=*/false,
3316         /*isNonTemporal=*/true,
3317         /*isInvariant=*/true, 8);
3318     if (GN->getOffset() != 0)
3319       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3320                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3321     return GlobalAddr;
3322   }
3323
3324   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3325     const unsigned char MO_NC = AArch64II::MO_NC;
3326     return DAG.getNode(
3327         AArch64ISD::WrapperLarge, DL, PtrVT,
3328         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3329         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3330         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3331         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3332   } else {
3333     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3334     // the only correct model on Darwin.
3335     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3336                                             OpFlags | AArch64II::MO_PAGE);
3337     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3338     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3339
3340     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3341     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3342   }
3343 }
3344
3345 /// \brief Convert a TLS address reference into the correct sequence of loads
3346 /// and calls to compute the variable's address (for Darwin, currently) and
3347 /// return an SDValue containing the final node.
3348
3349 /// Darwin only has one TLS scheme which must be capable of dealing with the
3350 /// fully general situation, in the worst case. This means:
3351 ///     + "extern __thread" declaration.
3352 ///     + Defined in a possibly unknown dynamic library.
3353 ///
3354 /// The general system is that each __thread variable has a [3 x i64] descriptor
3355 /// which contains information used by the runtime to calculate the address. The
3356 /// only part of this the compiler needs to know about is the first xword, which
3357 /// contains a function pointer that must be called with the address of the
3358 /// entire descriptor in "x0".
3359 ///
3360 /// Since this descriptor may be in a different unit, in general even the
3361 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3362 /// is:
3363 ///     adrp x0, _var@TLVPPAGE
3364 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3365 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3366 ///                                      ; the function pointer
3367 ///     blr x1                           ; Uses descriptor address in x0
3368 ///     ; Address of _var is now in x0.
3369 ///
3370 /// If the address of _var's descriptor *is* known to the linker, then it can
3371 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3372 /// a slight efficiency gain.
3373 SDValue
3374 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3375                                                    SelectionDAG &DAG) const {
3376   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3377
3378   SDLoc DL(Op);
3379   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3380   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3381
3382   SDValue TLVPAddr =
3383       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3384   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3385
3386   // The first entry in the descriptor is a function pointer that we must call
3387   // to obtain the address of the variable.
3388   SDValue Chain = DAG.getEntryNode();
3389   SDValue FuncTLVGet =
3390       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3391                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3392                   true, true, 8);
3393   Chain = FuncTLVGet.getValue(1);
3394
3395   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3396   MFI->setAdjustsStack(true);
3397
3398   // TLS calls preserve all registers except those that absolutely must be
3399   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3400   // silly).
3401   const uint32_t *Mask =
3402       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3403
3404   // Finally, we can make the call. This is just a degenerate version of a
3405   // normal AArch64 call node: x0 takes the address of the descriptor, and
3406   // returns the address of the variable in this thread.
3407   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3408   Chain =
3409       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3410                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3411                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3412   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3413 }
3414
3415 /// When accessing thread-local variables under either the general-dynamic or
3416 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3417 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3418 /// is a function pointer to carry out the resolution.
3419 ///
3420 /// The sequence is:
3421 ///    adrp  x0, :tlsdesc:var
3422 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3423 ///    add   x0, x0, #:tlsdesc_lo12:var
3424 ///    .tlsdesccall var
3425 ///    blr   x1
3426 ///    (TPIDR_EL0 offset now in x0)
3427 ///
3428 ///  The above sequence must be produced unscheduled, to enable the linker to
3429 ///  optimize/relax this sequence.
3430 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3431 ///  above sequence, and expanded really late in the compilation flow, to ensure
3432 ///  the sequence is produced as per above.
3433 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3434                                                       SelectionDAG &DAG) const {
3435   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3436
3437   SDValue Chain = DAG.getEntryNode();
3438   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3439
3440   SmallVector<SDValue, 2> Ops;
3441   Ops.push_back(Chain);
3442   Ops.push_back(SymAddr);
3443
3444   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3445   SDValue Glue = Chain.getValue(1);
3446
3447   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3448 }
3449
3450 SDValue
3451 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3452                                                 SelectionDAG &DAG) const {
3453   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3454   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3455          "ELF TLS only supported in small memory model");
3456   // Different choices can be made for the maximum size of the TLS area for a
3457   // module. For the small address model, the default TLS size is 16MiB and the
3458   // maximum TLS size is 4GiB.
3459   // FIXME: add -mtls-size command line option and make it control the 16MiB
3460   // vs. 4GiB code sequence generation.
3461   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3462
3463   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3464
3465   if (DAG.getTarget().Options.EmulatedTLS)
3466     return LowerToTLSEmulatedModel(GA, DAG);
3467
3468   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3469     if (Model == TLSModel::LocalDynamic)
3470       Model = TLSModel::GeneralDynamic;
3471   }
3472
3473   SDValue TPOff;
3474   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3475   SDLoc DL(Op);
3476   const GlobalValue *GV = GA->getGlobal();
3477
3478   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3479
3480   if (Model == TLSModel::LocalExec) {
3481     SDValue HiVar = DAG.getTargetGlobalAddress(
3482         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3483     SDValue LoVar = DAG.getTargetGlobalAddress(
3484         GV, DL, PtrVT, 0,
3485         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3486
3487     SDValue TPWithOff_lo =
3488         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3489                                    HiVar,
3490                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3491                 0);
3492     SDValue TPWithOff =
3493         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3494                                    LoVar,
3495                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3496                 0);
3497     return TPWithOff;
3498   } else if (Model == TLSModel::InitialExec) {
3499     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3500     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3501   } else if (Model == TLSModel::LocalDynamic) {
3502     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3503     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3504     // the beginning of the module's TLS region, followed by a DTPREL offset
3505     // calculation.
3506
3507     // These accesses will need deduplicating if there's more than one.
3508     AArch64FunctionInfo *MFI =
3509         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3510     MFI->incNumLocalDynamicTLSAccesses();
3511
3512     // The call needs a relocation too for linker relaxation. It doesn't make
3513     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3514     // the address.
3515     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3516                                                   AArch64II::MO_TLS);
3517
3518     // Now we can calculate the offset from TPIDR_EL0 to this module's
3519     // thread-local area.
3520     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3521
3522     // Now use :dtprel_whatever: operations to calculate this variable's offset
3523     // in its thread-storage area.
3524     SDValue HiVar = DAG.getTargetGlobalAddress(
3525         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3526     SDValue LoVar = DAG.getTargetGlobalAddress(
3527         GV, DL, MVT::i64, 0,
3528         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3529
3530     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3531                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3532                     0);
3533     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3534                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3535                     0);
3536   } else if (Model == TLSModel::GeneralDynamic) {
3537     // The call needs a relocation too for linker relaxation. It doesn't make
3538     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3539     // the address.
3540     SDValue SymAddr =
3541         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3542
3543     // Finally we can make a call to calculate the offset from tpidr_el0.
3544     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3545   } else
3546     llvm_unreachable("Unsupported ELF TLS access model");
3547
3548   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3549 }
3550
3551 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3552                                                      SelectionDAG &DAG) const {
3553   if (Subtarget->isTargetDarwin())
3554     return LowerDarwinGlobalTLSAddress(Op, DAG);
3555   else if (Subtarget->isTargetELF())
3556     return LowerELFGlobalTLSAddress(Op, DAG);
3557
3558   llvm_unreachable("Unexpected platform trying to use TLS");
3559 }
3560 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3561   SDValue Chain = Op.getOperand(0);
3562   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3563   SDValue LHS = Op.getOperand(2);
3564   SDValue RHS = Op.getOperand(3);
3565   SDValue Dest = Op.getOperand(4);
3566   SDLoc dl(Op);
3567
3568   // Handle f128 first, since lowering it will result in comparing the return
3569   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3570   // is expecting to deal with.
3571   if (LHS.getValueType() == MVT::f128) {
3572     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3573
3574     // If softenSetCCOperands returned a scalar, we need to compare the result
3575     // against zero to select between true and false values.
3576     if (!RHS.getNode()) {
3577       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3578       CC = ISD::SETNE;
3579     }
3580   }
3581
3582   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3583   // instruction.
3584   unsigned Opc = LHS.getOpcode();
3585   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3586       cast<ConstantSDNode>(RHS)->isOne() &&
3587       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3588        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3589     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3590            "Unexpected condition code.");
3591     // Only lower legal XALUO ops.
3592     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3593       return SDValue();
3594
3595     // The actual operation with overflow check.
3596     AArch64CC::CondCode OFCC;
3597     SDValue Value, Overflow;
3598     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3599
3600     if (CC == ISD::SETNE)
3601       OFCC = getInvertedCondCode(OFCC);
3602     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3603
3604     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3605                        Overflow);
3606   }
3607
3608   if (LHS.getValueType().isInteger()) {
3609     assert((LHS.getValueType() == RHS.getValueType()) &&
3610            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3611
3612     // If the RHS of the comparison is zero, we can potentially fold this
3613     // to a specialized branch.
3614     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3615     if (RHSC && RHSC->getZExtValue() == 0) {
3616       if (CC == ISD::SETEQ) {
3617         // See if we can use a TBZ to fold in an AND as well.
3618         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3619         // out of bounds, a late MI-layer pass rewrites branches.
3620         // 403.gcc is an example that hits this case.
3621         if (LHS.getOpcode() == ISD::AND &&
3622             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3623             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3624           SDValue Test = LHS.getOperand(0);
3625           uint64_t Mask = LHS.getConstantOperandVal(1);
3626           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3627                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3628                              Dest);
3629         }
3630
3631         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3632       } else if (CC == ISD::SETNE) {
3633         // See if we can use a TBZ to fold in an AND as well.
3634         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3635         // out of bounds, a late MI-layer pass rewrites branches.
3636         // 403.gcc is an example that hits this case.
3637         if (LHS.getOpcode() == ISD::AND &&
3638             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3639             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3640           SDValue Test = LHS.getOperand(0);
3641           uint64_t Mask = LHS.getConstantOperandVal(1);
3642           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3643                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3644                              Dest);
3645         }
3646
3647         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3648       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3649         // Don't combine AND since emitComparison converts the AND to an ANDS
3650         // (a.k.a. TST) and the test in the test bit and branch instruction
3651         // becomes redundant.  This would also increase register pressure.
3652         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3653         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3654                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3655       }
3656     }
3657     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3658         LHS.getOpcode() != ISD::AND) {
3659       // Don't combine AND since emitComparison converts the AND to an ANDS
3660       // (a.k.a. TST) and the test in the test bit and branch instruction
3661       // becomes redundant.  This would also increase register pressure.
3662       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3663       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3664                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3665     }
3666
3667     SDValue CCVal;
3668     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3669     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3670                        Cmp);
3671   }
3672
3673   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3674
3675   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3676   // clean.  Some of them require two branches to implement.
3677   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3678   AArch64CC::CondCode CC1, CC2;
3679   changeFPCCToAArch64CC(CC, CC1, CC2);
3680   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3681   SDValue BR1 =
3682       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3683   if (CC2 != AArch64CC::AL) {
3684     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3685     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3686                        Cmp);
3687   }
3688
3689   return BR1;
3690 }
3691
3692 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3693                                               SelectionDAG &DAG) const {
3694   EVT VT = Op.getValueType();
3695   SDLoc DL(Op);
3696
3697   SDValue In1 = Op.getOperand(0);
3698   SDValue In2 = Op.getOperand(1);
3699   EVT SrcVT = In2.getValueType();
3700
3701   if (SrcVT.bitsLT(VT))
3702     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3703   else if (SrcVT.bitsGT(VT))
3704     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3705
3706   EVT VecVT;
3707   EVT EltVT;
3708   uint64_t EltMask;
3709   SDValue VecVal1, VecVal2;
3710   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3711     EltVT = MVT::i32;
3712     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3713     EltMask = 0x80000000ULL;
3714
3715     if (!VT.isVector()) {
3716       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3717                                           DAG.getUNDEF(VecVT), In1);
3718       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3719                                           DAG.getUNDEF(VecVT), In2);
3720     } else {
3721       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3722       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3723     }
3724   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3725     EltVT = MVT::i64;
3726     VecVT = MVT::v2i64;
3727
3728     // We want to materialize a mask with the high bit set, but the AdvSIMD
3729     // immediate moves cannot materialize that in a single instruction for
3730     // 64-bit elements. Instead, materialize zero and then negate it.
3731     EltMask = 0;
3732
3733     if (!VT.isVector()) {
3734       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3735                                           DAG.getUNDEF(VecVT), In1);
3736       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3737                                           DAG.getUNDEF(VecVT), In2);
3738     } else {
3739       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3740       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3741     }
3742   } else {
3743     llvm_unreachable("Invalid type for copysign!");
3744   }
3745
3746   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3747
3748   // If we couldn't materialize the mask above, then the mask vector will be
3749   // the zero vector, and we need to negate it here.
3750   if (VT == MVT::f64 || VT == MVT::v2f64) {
3751     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3752     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3753     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3754   }
3755
3756   SDValue Sel =
3757       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3758
3759   if (VT == MVT::f32)
3760     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3761   else if (VT == MVT::f64)
3762     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3763   else
3764     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3765 }
3766
3767 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3768   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3769           Attribute::NoImplicitFloat))
3770     return SDValue();
3771
3772   if (!Subtarget->hasNEON())
3773     return SDValue();
3774
3775   // While there is no integer popcount instruction, it can
3776   // be more efficiently lowered to the following sequence that uses
3777   // AdvSIMD registers/instructions as long as the copies to/from
3778   // the AdvSIMD registers are cheap.
3779   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3780   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3781   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3782   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3783   SDValue Val = Op.getOperand(0);
3784   SDLoc DL(Op);
3785   EVT VT = Op.getValueType();
3786
3787   if (VT == MVT::i32)
3788     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3789   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3790
3791   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3792   SDValue UaddLV = DAG.getNode(
3793       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3794       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3795
3796   if (VT == MVT::i64)
3797     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3798   return UaddLV;
3799 }
3800
3801 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3802
3803   if (Op.getValueType().isVector())
3804     return LowerVSETCC(Op, DAG);
3805
3806   SDValue LHS = Op.getOperand(0);
3807   SDValue RHS = Op.getOperand(1);
3808   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3809   SDLoc dl(Op);
3810
3811   // We chose ZeroOrOneBooleanContents, so use zero and one.
3812   EVT VT = Op.getValueType();
3813   SDValue TVal = DAG.getConstant(1, dl, VT);
3814   SDValue FVal = DAG.getConstant(0, dl, VT);
3815
3816   // Handle f128 first, since one possible outcome is a normal integer
3817   // comparison which gets picked up by the next if statement.
3818   if (LHS.getValueType() == MVT::f128) {
3819     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3820
3821     // If softenSetCCOperands returned a scalar, use it.
3822     if (!RHS.getNode()) {
3823       assert(LHS.getValueType() == Op.getValueType() &&
3824              "Unexpected setcc expansion!");
3825       return LHS;
3826     }
3827   }
3828
3829   if (LHS.getValueType().isInteger()) {
3830     SDValue CCVal;
3831     SDValue Cmp =
3832         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3833
3834     // Note that we inverted the condition above, so we reverse the order of
3835     // the true and false operands here.  This will allow the setcc to be
3836     // matched to a single CSINC instruction.
3837     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3838   }
3839
3840   // Now we know we're dealing with FP values.
3841   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3842
3843   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3844   // and do the comparison.
3845   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3846
3847   AArch64CC::CondCode CC1, CC2;
3848   changeFPCCToAArch64CC(CC, CC1, CC2);
3849   if (CC2 == AArch64CC::AL) {
3850     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3851     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3852
3853     // Note that we inverted the condition above, so we reverse the order of
3854     // the true and false operands here.  This will allow the setcc to be
3855     // matched to a single CSINC instruction.
3856     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3857   } else {
3858     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3859     // totally clean.  Some of them require two CSELs to implement.  As is in
3860     // this case, we emit the first CSEL and then emit a second using the output
3861     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3862
3863     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3864     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3865     SDValue CS1 =
3866         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3867
3868     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3869     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3870   }
3871 }
3872
3873 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3874                                               SDValue RHS, SDValue TVal,
3875                                               SDValue FVal, SDLoc dl,
3876                                               SelectionDAG &DAG) const {
3877   // Handle f128 first, because it will result in a comparison of some RTLIB
3878   // call result against zero.
3879   if (LHS.getValueType() == MVT::f128) {
3880     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3881
3882     // If softenSetCCOperands returned a scalar, we need to compare the result
3883     // against zero to select between true and false values.
3884     if (!RHS.getNode()) {
3885       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3886       CC = ISD::SETNE;
3887     }
3888   }
3889
3890   // Handle integers first.
3891   if (LHS.getValueType().isInteger()) {
3892     assert((LHS.getValueType() == RHS.getValueType()) &&
3893            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3894
3895     unsigned Opcode = AArch64ISD::CSEL;
3896
3897     // If both the TVal and the FVal are constants, see if we can swap them in
3898     // order to for a CSINV or CSINC out of them.
3899     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3900     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3901
3902     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3903       std::swap(TVal, FVal);
3904       std::swap(CTVal, CFVal);
3905       CC = ISD::getSetCCInverse(CC, true);
3906     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3907       std::swap(TVal, FVal);
3908       std::swap(CTVal, CFVal);
3909       CC = ISD::getSetCCInverse(CC, true);
3910     } else if (TVal.getOpcode() == ISD::XOR) {
3911       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3912       // with a CSINV rather than a CSEL.
3913       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3914
3915       if (CVal && CVal->isAllOnesValue()) {
3916         std::swap(TVal, FVal);
3917         std::swap(CTVal, CFVal);
3918         CC = ISD::getSetCCInverse(CC, true);
3919       }
3920     } else if (TVal.getOpcode() == ISD::SUB) {
3921       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3922       // that we can match with a CSNEG rather than a CSEL.
3923       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3924
3925       if (CVal && CVal->isNullValue()) {
3926         std::swap(TVal, FVal);
3927         std::swap(CTVal, CFVal);
3928         CC = ISD::getSetCCInverse(CC, true);
3929       }
3930     } else if (CTVal && CFVal) {
3931       const int64_t TrueVal = CTVal->getSExtValue();
3932       const int64_t FalseVal = CFVal->getSExtValue();
3933       bool Swap = false;
3934
3935       // If both TVal and FVal are constants, see if FVal is the
3936       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3937       // instead of a CSEL in that case.
3938       if (TrueVal == ~FalseVal) {
3939         Opcode = AArch64ISD::CSINV;
3940       } else if (TrueVal == -FalseVal) {
3941         Opcode = AArch64ISD::CSNEG;
3942       } else if (TVal.getValueType() == MVT::i32) {
3943         // If our operands are only 32-bit wide, make sure we use 32-bit
3944         // arithmetic for the check whether we can use CSINC. This ensures that
3945         // the addition in the check will wrap around properly in case there is
3946         // an overflow (which would not be the case if we do the check with
3947         // 64-bit arithmetic).
3948         const uint32_t TrueVal32 = CTVal->getZExtValue();
3949         const uint32_t FalseVal32 = CFVal->getZExtValue();
3950
3951         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3952           Opcode = AArch64ISD::CSINC;
3953
3954           if (TrueVal32 > FalseVal32) {
3955             Swap = true;
3956           }
3957         }
3958         // 64-bit check whether we can use CSINC.
3959       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3960         Opcode = AArch64ISD::CSINC;
3961
3962         if (TrueVal > FalseVal) {
3963           Swap = true;
3964         }
3965       }
3966
3967       // Swap TVal and FVal if necessary.
3968       if (Swap) {
3969         std::swap(TVal, FVal);
3970         std::swap(CTVal, CFVal);
3971         CC = ISD::getSetCCInverse(CC, true);
3972       }
3973
3974       if (Opcode != AArch64ISD::CSEL) {
3975         // Drop FVal since we can get its value by simply inverting/negating
3976         // TVal.
3977         FVal = TVal;
3978       }
3979     }
3980
3981     SDValue CCVal;
3982     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3983
3984     EVT VT = TVal.getValueType();
3985     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3986   }
3987
3988   // Now we know we're dealing with FP values.
3989   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3990   assert(LHS.getValueType() == RHS.getValueType());
3991   EVT VT = TVal.getValueType();
3992   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3993
3994   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3995   // clean.  Some of them require two CSELs to implement.
3996   AArch64CC::CondCode CC1, CC2;
3997   changeFPCCToAArch64CC(CC, CC1, CC2);
3998   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3999   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4000
4001   // If we need a second CSEL, emit it, using the output of the first as the
4002   // RHS.  We're effectively OR'ing the two CC's together.
4003   if (CC2 != AArch64CC::AL) {
4004     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4005     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4006   }
4007
4008   // Otherwise, return the output of the first CSEL.
4009   return CS1;
4010 }
4011
4012 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4013                                               SelectionDAG &DAG) const {
4014   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4015   SDValue LHS = Op.getOperand(0);
4016   SDValue RHS = Op.getOperand(1);
4017   SDValue TVal = Op.getOperand(2);
4018   SDValue FVal = Op.getOperand(3);
4019   SDLoc DL(Op);
4020   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4021 }
4022
4023 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4024                                            SelectionDAG &DAG) const {
4025   SDValue CCVal = Op->getOperand(0);
4026   SDValue TVal = Op->getOperand(1);
4027   SDValue FVal = Op->getOperand(2);
4028   SDLoc DL(Op);
4029
4030   unsigned Opc = CCVal.getOpcode();
4031   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4032   // instruction.
4033   if (CCVal.getResNo() == 1 &&
4034       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4035        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4036     // Only lower legal XALUO ops.
4037     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4038       return SDValue();
4039
4040     AArch64CC::CondCode OFCC;
4041     SDValue Value, Overflow;
4042     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4043     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4044
4045     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4046                        CCVal, Overflow);
4047   }
4048
4049   // Lower it the same way as we would lower a SELECT_CC node.
4050   ISD::CondCode CC;
4051   SDValue LHS, RHS;
4052   if (CCVal.getOpcode() == ISD::SETCC) {
4053     LHS = CCVal.getOperand(0);
4054     RHS = CCVal.getOperand(1);
4055     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4056   } else {
4057     LHS = CCVal;
4058     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4059     CC = ISD::SETNE;
4060   }
4061   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4062 }
4063
4064 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4065                                               SelectionDAG &DAG) const {
4066   // Jump table entries as PC relative offsets. No additional tweaking
4067   // is necessary here. Just get the address of the jump table.
4068   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4069   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4070   SDLoc DL(Op);
4071
4072   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4073       !Subtarget->isTargetMachO()) {
4074     const unsigned char MO_NC = AArch64II::MO_NC;
4075     return DAG.getNode(
4076         AArch64ISD::WrapperLarge, DL, PtrVT,
4077         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4078         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4079         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4080         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4081                                AArch64II::MO_G0 | MO_NC));
4082   }
4083
4084   SDValue Hi =
4085       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4086   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4087                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4088   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4089   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4090 }
4091
4092 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4093                                                  SelectionDAG &DAG) const {
4094   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4095   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4096   SDLoc DL(Op);
4097
4098   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4099     // Use the GOT for the large code model on iOS.
4100     if (Subtarget->isTargetMachO()) {
4101       SDValue GotAddr = DAG.getTargetConstantPool(
4102           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4103           AArch64II::MO_GOT);
4104       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4105     }
4106
4107     const unsigned char MO_NC = AArch64II::MO_NC;
4108     return DAG.getNode(
4109         AArch64ISD::WrapperLarge, DL, PtrVT,
4110         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4111                                   CP->getOffset(), AArch64II::MO_G3),
4112         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4113                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4114         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4115                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4116         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4117                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4118   } else {
4119     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4120     // ELF, the only valid one on Darwin.
4121     SDValue Hi =
4122         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4123                                   CP->getOffset(), AArch64II::MO_PAGE);
4124     SDValue Lo = DAG.getTargetConstantPool(
4125         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4126         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4127
4128     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4129     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4130   }
4131 }
4132
4133 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4134                                                SelectionDAG &DAG) const {
4135   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4136   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4137   SDLoc DL(Op);
4138   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4139       !Subtarget->isTargetMachO()) {
4140     const unsigned char MO_NC = AArch64II::MO_NC;
4141     return DAG.getNode(
4142         AArch64ISD::WrapperLarge, DL, PtrVT,
4143         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4144         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4145         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4146         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4147   } else {
4148     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4149     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4150                                                              AArch64II::MO_NC);
4151     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4152     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4153   }
4154 }
4155
4156 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4157                                                  SelectionDAG &DAG) const {
4158   AArch64FunctionInfo *FuncInfo =
4159       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4160
4161   SDLoc DL(Op);
4162   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4163                                  getPointerTy(DAG.getDataLayout()));
4164   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4165   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4166                       MachinePointerInfo(SV), false, false, 0);
4167 }
4168
4169 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4170                                                 SelectionDAG &DAG) const {
4171   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4172   // Standard, section B.3.
4173   MachineFunction &MF = DAG.getMachineFunction();
4174   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4175   auto PtrVT = getPointerTy(DAG.getDataLayout());
4176   SDLoc DL(Op);
4177
4178   SDValue Chain = Op.getOperand(0);
4179   SDValue VAList = Op.getOperand(1);
4180   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4181   SmallVector<SDValue, 4> MemOps;
4182
4183   // void *__stack at offset 0
4184   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4185   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4186                                 MachinePointerInfo(SV), false, false, 8));
4187
4188   // void *__gr_top at offset 8
4189   int GPRSize = FuncInfo->getVarArgsGPRSize();
4190   if (GPRSize > 0) {
4191     SDValue GRTop, GRTopAddr;
4192
4193     GRTopAddr =
4194         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4195
4196     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4197     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4198                         DAG.getConstant(GPRSize, DL, PtrVT));
4199
4200     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4201                                   MachinePointerInfo(SV, 8), false, false, 8));
4202   }
4203
4204   // void *__vr_top at offset 16
4205   int FPRSize = FuncInfo->getVarArgsFPRSize();
4206   if (FPRSize > 0) {
4207     SDValue VRTop, VRTopAddr;
4208     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4209                             DAG.getConstant(16, DL, PtrVT));
4210
4211     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4212     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4213                         DAG.getConstant(FPRSize, DL, PtrVT));
4214
4215     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4216                                   MachinePointerInfo(SV, 16), false, false, 8));
4217   }
4218
4219   // int __gr_offs at offset 24
4220   SDValue GROffsAddr =
4221       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4222   MemOps.push_back(DAG.getStore(Chain, DL,
4223                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4224                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4225                                 false, 4));
4226
4227   // int __vr_offs at offset 28
4228   SDValue VROffsAddr =
4229       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4230   MemOps.push_back(DAG.getStore(Chain, DL,
4231                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4232                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4233                                 false, 4));
4234
4235   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4236 }
4237
4238 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4239                                             SelectionDAG &DAG) const {
4240   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4241                                      : LowerAAPCS_VASTART(Op, DAG);
4242 }
4243
4244 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4245                                            SelectionDAG &DAG) const {
4246   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4247   // pointer.
4248   SDLoc DL(Op);
4249   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4250   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4251   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4252
4253   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4254                        Op.getOperand(2),
4255                        DAG.getConstant(VaListSize, DL, MVT::i32),
4256                        8, false, false, false, MachinePointerInfo(DestSV),
4257                        MachinePointerInfo(SrcSV));
4258 }
4259
4260 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4261   assert(Subtarget->isTargetDarwin() &&
4262          "automatic va_arg instruction only works on Darwin");
4263
4264   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4265   EVT VT = Op.getValueType();
4266   SDLoc DL(Op);
4267   SDValue Chain = Op.getOperand(0);
4268   SDValue Addr = Op.getOperand(1);
4269   unsigned Align = Op.getConstantOperandVal(3);
4270   auto PtrVT = getPointerTy(DAG.getDataLayout());
4271
4272   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4273                                false, false, false, 0);
4274   Chain = VAList.getValue(1);
4275
4276   if (Align > 8) {
4277     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4278     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4279                          DAG.getConstant(Align - 1, DL, PtrVT));
4280     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4281                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4282   }
4283
4284   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4285   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4286
4287   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4288   // up to 64 bits.  At the very least, we have to increase the striding of the
4289   // vaargs list to match this, and for FP values we need to introduce
4290   // FP_ROUND nodes as well.
4291   if (VT.isInteger() && !VT.isVector())
4292     ArgSize = 8;
4293   bool NeedFPTrunc = false;
4294   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4295     ArgSize = 8;
4296     NeedFPTrunc = true;
4297   }
4298
4299   // Increment the pointer, VAList, to the next vaarg
4300   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4301                                DAG.getConstant(ArgSize, DL, PtrVT));
4302   // Store the incremented VAList to the legalized pointer
4303   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4304                                  false, false, 0);
4305
4306   // Load the actual argument out of the pointer VAList
4307   if (NeedFPTrunc) {
4308     // Load the value as an f64.
4309     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4310                                  MachinePointerInfo(), false, false, false, 0);
4311     // Round the value down to an f32.
4312     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4313                                    DAG.getIntPtrConstant(1, DL));
4314     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4315     // Merge the rounded value with the chain output of the load.
4316     return DAG.getMergeValues(Ops, DL);
4317   }
4318
4319   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4320                      false, false, 0);
4321 }
4322
4323 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4324                                               SelectionDAG &DAG) const {
4325   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4326   MFI->setFrameAddressIsTaken(true);
4327
4328   EVT VT = Op.getValueType();
4329   SDLoc DL(Op);
4330   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4331   SDValue FrameAddr =
4332       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4333   while (Depth--)
4334     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4335                             MachinePointerInfo(), false, false, false, 0);
4336   return FrameAddr;
4337 }
4338
4339 // FIXME? Maybe this could be a TableGen attribute on some registers and
4340 // this table could be generated automatically from RegInfo.
4341 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4342                                                   SelectionDAG &DAG) const {
4343   unsigned Reg = StringSwitch<unsigned>(RegName)
4344                        .Case("sp", AArch64::SP)
4345                        .Default(0);
4346   if (Reg)
4347     return Reg;
4348   report_fatal_error(Twine("Invalid register name \""
4349                               + StringRef(RegName)  + "\"."));
4350 }
4351
4352 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4353                                                SelectionDAG &DAG) const {
4354   MachineFunction &MF = DAG.getMachineFunction();
4355   MachineFrameInfo *MFI = MF.getFrameInfo();
4356   MFI->setReturnAddressIsTaken(true);
4357
4358   EVT VT = Op.getValueType();
4359   SDLoc DL(Op);
4360   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4361   if (Depth) {
4362     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4363     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4364     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4365                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4366                        MachinePointerInfo(), false, false, false, 0);
4367   }
4368
4369   // Return LR, which contains the return address. Mark it an implicit live-in.
4370   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4371   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4372 }
4373
4374 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4375 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4376 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4377                                                     SelectionDAG &DAG) const {
4378   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4379   EVT VT = Op.getValueType();
4380   unsigned VTBits = VT.getSizeInBits();
4381   SDLoc dl(Op);
4382   SDValue ShOpLo = Op.getOperand(0);
4383   SDValue ShOpHi = Op.getOperand(1);
4384   SDValue ShAmt = Op.getOperand(2);
4385   SDValue ARMcc;
4386   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4387
4388   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4389
4390   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4391                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4392   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4393   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4394                                    DAG.getConstant(VTBits, dl, MVT::i64));
4395   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4396
4397   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4398                                ISD::SETGE, dl, DAG);
4399   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4400
4401   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4402   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4403   SDValue Lo =
4404       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4405
4406   // AArch64 shifts larger than the register width are wrapped rather than
4407   // clamped, so we can't just emit "hi >> x".
4408   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4409   SDValue TrueValHi = Opc == ISD::SRA
4410                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4411                                         DAG.getConstant(VTBits - 1, dl,
4412                                                         MVT::i64))
4413                           : DAG.getConstant(0, dl, VT);
4414   SDValue Hi =
4415       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4416
4417   SDValue Ops[2] = { Lo, Hi };
4418   return DAG.getMergeValues(Ops, dl);
4419 }
4420
4421 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4422 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4423 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4424                                                  SelectionDAG &DAG) const {
4425   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4426   EVT VT = Op.getValueType();
4427   unsigned VTBits = VT.getSizeInBits();
4428   SDLoc dl(Op);
4429   SDValue ShOpLo = Op.getOperand(0);
4430   SDValue ShOpHi = Op.getOperand(1);
4431   SDValue ShAmt = Op.getOperand(2);
4432   SDValue ARMcc;
4433
4434   assert(Op.getOpcode() == ISD::SHL_PARTS);
4435   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4436                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4437   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4438   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4439                                    DAG.getConstant(VTBits, dl, MVT::i64));
4440   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4441   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4442
4443   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4444
4445   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4446                                ISD::SETGE, dl, DAG);
4447   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4448   SDValue Hi =
4449       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4450
4451   // AArch64 shifts of larger than register sizes are wrapped rather than
4452   // clamped, so we can't just emit "lo << a" if a is too big.
4453   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4454   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4455   SDValue Lo =
4456       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4457
4458   SDValue Ops[2] = { Lo, Hi };
4459   return DAG.getMergeValues(Ops, dl);
4460 }
4461
4462 bool AArch64TargetLowering::isOffsetFoldingLegal(
4463     const GlobalAddressSDNode *GA) const {
4464   // The AArch64 target doesn't support folding offsets into global addresses.
4465   return false;
4466 }
4467
4468 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4469   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4470   // FIXME: We should be able to handle f128 as well with a clever lowering.
4471   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4472     return true;
4473
4474   if (VT == MVT::f64)
4475     return AArch64_AM::getFP64Imm(Imm) != -1;
4476   else if (VT == MVT::f32)
4477     return AArch64_AM::getFP32Imm(Imm) != -1;
4478   return false;
4479 }
4480
4481 //===----------------------------------------------------------------------===//
4482 //                          AArch64 Optimization Hooks
4483 //===----------------------------------------------------------------------===//
4484
4485 //===----------------------------------------------------------------------===//
4486 //                          AArch64 Inline Assembly Support
4487 //===----------------------------------------------------------------------===//
4488
4489 // Table of Constraints
4490 // TODO: This is the current set of constraints supported by ARM for the
4491 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4492 //
4493 // r - A general register
4494 // w - An FP/SIMD register of some size in the range v0-v31
4495 // x - An FP/SIMD register of some size in the range v0-v15
4496 // I - Constant that can be used with an ADD instruction
4497 // J - Constant that can be used with a SUB instruction
4498 // K - Constant that can be used with a 32-bit logical instruction
4499 // L - Constant that can be used with a 64-bit logical instruction
4500 // M - Constant that can be used as a 32-bit MOV immediate
4501 // N - Constant that can be used as a 64-bit MOV immediate
4502 // Q - A memory reference with base register and no offset
4503 // S - A symbolic address
4504 // Y - Floating point constant zero
4505 // Z - Integer constant zero
4506 //
4507 //   Note that general register operands will be output using their 64-bit x
4508 // register name, whatever the size of the variable, unless the asm operand
4509 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4510 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4511 // %q modifier.
4512
4513 /// getConstraintType - Given a constraint letter, return the type of
4514 /// constraint it is for this target.
4515 AArch64TargetLowering::ConstraintType
4516 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4517   if (Constraint.size() == 1) {
4518     switch (Constraint[0]) {
4519     default:
4520       break;
4521     case 'z':
4522       return C_Other;
4523     case 'x':
4524     case 'w':
4525       return C_RegisterClass;
4526     // An address with a single base register. Due to the way we
4527     // currently handle addresses it is the same as 'r'.
4528     case 'Q':
4529       return C_Memory;
4530     }
4531   }
4532   return TargetLowering::getConstraintType(Constraint);
4533 }
4534
4535 /// Examine constraint type and operand type and determine a weight value.
4536 /// This object must already have been set up with the operand type
4537 /// and the current alternative constraint selected.
4538 TargetLowering::ConstraintWeight
4539 AArch64TargetLowering::getSingleConstraintMatchWeight(
4540     AsmOperandInfo &info, const char *constraint) const {
4541   ConstraintWeight weight = CW_Invalid;
4542   Value *CallOperandVal = info.CallOperandVal;
4543   // If we don't have a value, we can't do a match,
4544   // but allow it at the lowest weight.
4545   if (!CallOperandVal)
4546     return CW_Default;
4547   Type *type = CallOperandVal->getType();
4548   // Look at the constraint type.
4549   switch (*constraint) {
4550   default:
4551     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4552     break;
4553   case 'x':
4554   case 'w':
4555     if (type->isFloatingPointTy() || type->isVectorTy())
4556       weight = CW_Register;
4557     break;
4558   case 'z':
4559     weight = CW_Constant;
4560     break;
4561   }
4562   return weight;
4563 }
4564
4565 std::pair<unsigned, const TargetRegisterClass *>
4566 AArch64TargetLowering::getRegForInlineAsmConstraint(
4567     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4568   if (Constraint.size() == 1) {
4569     switch (Constraint[0]) {
4570     case 'r':
4571       if (VT.getSizeInBits() == 64)
4572         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4573       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4574     case 'w':
4575       if (VT == MVT::f32)
4576         return std::make_pair(0U, &AArch64::FPR32RegClass);
4577       if (VT.getSizeInBits() == 64)
4578         return std::make_pair(0U, &AArch64::FPR64RegClass);
4579       if (VT.getSizeInBits() == 128)
4580         return std::make_pair(0U, &AArch64::FPR128RegClass);
4581       break;
4582     // The instructions that this constraint is designed for can
4583     // only take 128-bit registers so just use that regclass.
4584     case 'x':
4585       if (VT.getSizeInBits() == 128)
4586         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4587       break;
4588     }
4589   }
4590   if (StringRef("{cc}").equals_lower(Constraint))
4591     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4592
4593   // Use the default implementation in TargetLowering to convert the register
4594   // constraint into a member of a register class.
4595   std::pair<unsigned, const TargetRegisterClass *> Res;
4596   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4597
4598   // Not found as a standard register?
4599   if (!Res.second) {
4600     unsigned Size = Constraint.size();
4601     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4602         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4603       int RegNo;
4604       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4605       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4606         // v0 - v31 are aliases of q0 - q31.
4607         // By default we'll emit v0-v31 for this unless there's a modifier where
4608         // we'll emit the correct register as well.
4609         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4610         Res.second = &AArch64::FPR128RegClass;
4611       }
4612     }
4613   }
4614
4615   return Res;
4616 }
4617
4618 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4619 /// vector.  If it is invalid, don't add anything to Ops.
4620 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4621     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4622     SelectionDAG &DAG) const {
4623   SDValue Result;
4624
4625   // Currently only support length 1 constraints.
4626   if (Constraint.length() != 1)
4627     return;
4628
4629   char ConstraintLetter = Constraint[0];
4630   switch (ConstraintLetter) {
4631   default:
4632     break;
4633
4634   // This set of constraints deal with valid constants for various instructions.
4635   // Validate and return a target constant for them if we can.
4636   case 'z': {
4637     // 'z' maps to xzr or wzr so it needs an input of 0.
4638     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4639     if (!C || C->getZExtValue() != 0)
4640       return;
4641
4642     if (Op.getValueType() == MVT::i64)
4643       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4644     else
4645       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4646     break;
4647   }
4648
4649   case 'I':
4650   case 'J':
4651   case 'K':
4652   case 'L':
4653   case 'M':
4654   case 'N':
4655     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4656     if (!C)
4657       return;
4658
4659     // Grab the value and do some validation.
4660     uint64_t CVal = C->getZExtValue();
4661     switch (ConstraintLetter) {
4662     // The I constraint applies only to simple ADD or SUB immediate operands:
4663     // i.e. 0 to 4095 with optional shift by 12
4664     // The J constraint applies only to ADD or SUB immediates that would be
4665     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4666     // instruction [or vice versa], in other words -1 to -4095 with optional
4667     // left shift by 12.
4668     case 'I':
4669       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4670         break;
4671       return;
4672     case 'J': {
4673       uint64_t NVal = -C->getSExtValue();
4674       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4675         CVal = C->getSExtValue();
4676         break;
4677       }
4678       return;
4679     }
4680     // The K and L constraints apply *only* to logical immediates, including
4681     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4682     // been removed and MOV should be used). So these constraints have to
4683     // distinguish between bit patterns that are valid 32-bit or 64-bit
4684     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4685     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4686     // versa.
4687     case 'K':
4688       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4689         break;
4690       return;
4691     case 'L':
4692       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4693         break;
4694       return;
4695     // The M and N constraints are a superset of K and L respectively, for use
4696     // with the MOV (immediate) alias. As well as the logical immediates they
4697     // also match 32 or 64-bit immediates that can be loaded either using a
4698     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4699     // (M) or 64-bit 0x1234000000000000 (N) etc.
4700     // As a note some of this code is liberally stolen from the asm parser.
4701     case 'M': {
4702       if (!isUInt<32>(CVal))
4703         return;
4704       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4705         break;
4706       if ((CVal & 0xFFFF) == CVal)
4707         break;
4708       if ((CVal & 0xFFFF0000ULL) == CVal)
4709         break;
4710       uint64_t NCVal = ~(uint32_t)CVal;
4711       if ((NCVal & 0xFFFFULL) == NCVal)
4712         break;
4713       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4714         break;
4715       return;
4716     }
4717     case 'N': {
4718       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4719         break;
4720       if ((CVal & 0xFFFFULL) == CVal)
4721         break;
4722       if ((CVal & 0xFFFF0000ULL) == CVal)
4723         break;
4724       if ((CVal & 0xFFFF00000000ULL) == CVal)
4725         break;
4726       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4727         break;
4728       uint64_t NCVal = ~CVal;
4729       if ((NCVal & 0xFFFFULL) == NCVal)
4730         break;
4731       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4732         break;
4733       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4734         break;
4735       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4736         break;
4737       return;
4738     }
4739     default:
4740       return;
4741     }
4742
4743     // All assembler immediates are 64-bit integers.
4744     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4745     break;
4746   }
4747
4748   if (Result.getNode()) {
4749     Ops.push_back(Result);
4750     return;
4751   }
4752
4753   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4754 }
4755
4756 //===----------------------------------------------------------------------===//
4757 //                     AArch64 Advanced SIMD Support
4758 //===----------------------------------------------------------------------===//
4759
4760 /// WidenVector - Given a value in the V64 register class, produce the
4761 /// equivalent value in the V128 register class.
4762 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4763   EVT VT = V64Reg.getValueType();
4764   unsigned NarrowSize = VT.getVectorNumElements();
4765   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4766   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4767   SDLoc DL(V64Reg);
4768
4769   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4770                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4771 }
4772
4773 /// getExtFactor - Determine the adjustment factor for the position when
4774 /// generating an "extract from vector registers" instruction.
4775 static unsigned getExtFactor(SDValue &V) {
4776   EVT EltType = V.getValueType().getVectorElementType();
4777   return EltType.getSizeInBits() / 8;
4778 }
4779
4780 /// NarrowVector - Given a value in the V128 register class, produce the
4781 /// equivalent value in the V64 register class.
4782 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4783   EVT VT = V128Reg.getValueType();
4784   unsigned WideSize = VT.getVectorNumElements();
4785   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4786   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4787   SDLoc DL(V128Reg);
4788
4789   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4790 }
4791
4792 // Gather data to see if the operation can be modelled as a
4793 // shuffle in combination with VEXTs.
4794 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4795                                                   SelectionDAG &DAG) const {
4796   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4797   SDLoc dl(Op);
4798   EVT VT = Op.getValueType();
4799   unsigned NumElts = VT.getVectorNumElements();
4800
4801   struct ShuffleSourceInfo {
4802     SDValue Vec;
4803     unsigned MinElt;
4804     unsigned MaxElt;
4805
4806     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4807     // be compatible with the shuffle we intend to construct. As a result
4808     // ShuffleVec will be some sliding window into the original Vec.
4809     SDValue ShuffleVec;
4810
4811     // Code should guarantee that element i in Vec starts at element "WindowBase
4812     // + i * WindowScale in ShuffleVec".
4813     int WindowBase;
4814     int WindowScale;
4815
4816     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4817     ShuffleSourceInfo(SDValue Vec)
4818         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4819           WindowScale(1) {}
4820   };
4821
4822   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4823   // node.
4824   SmallVector<ShuffleSourceInfo, 2> Sources;
4825   for (unsigned i = 0; i < NumElts; ++i) {
4826     SDValue V = Op.getOperand(i);
4827     if (V.getOpcode() == ISD::UNDEF)
4828       continue;
4829     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4830       // A shuffle can only come from building a vector from various
4831       // elements of other vectors.
4832       return SDValue();
4833     }
4834
4835     // Add this element source to the list if it's not already there.
4836     SDValue SourceVec = V.getOperand(0);
4837     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4838     if (Source == Sources.end())
4839       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4840
4841     // Update the minimum and maximum lane number seen.
4842     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4843     Source->MinElt = std::min(Source->MinElt, EltNo);
4844     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4845   }
4846
4847   // Currently only do something sane when at most two source vectors
4848   // are involved.
4849   if (Sources.size() > 2)
4850     return SDValue();
4851
4852   // Find out the smallest element size among result and two sources, and use
4853   // it as element size to build the shuffle_vector.
4854   EVT SmallestEltTy = VT.getVectorElementType();
4855   for (auto &Source : Sources) {
4856     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4857     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4858       SmallestEltTy = SrcEltTy;
4859     }
4860   }
4861   unsigned ResMultiplier =
4862       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4863   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4864   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4865
4866   // If the source vector is too wide or too narrow, we may nevertheless be able
4867   // to construct a compatible shuffle either by concatenating it with UNDEF or
4868   // extracting a suitable range of elements.
4869   for (auto &Src : Sources) {
4870     EVT SrcVT = Src.ShuffleVec.getValueType();
4871
4872     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4873       continue;
4874
4875     // This stage of the search produces a source with the same element type as
4876     // the original, but with a total width matching the BUILD_VECTOR output.
4877     EVT EltVT = SrcVT.getVectorElementType();
4878     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4879     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4880
4881     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4882       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4883       // We can pad out the smaller vector for free, so if it's part of a
4884       // shuffle...
4885       Src.ShuffleVec =
4886           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4887                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4888       continue;
4889     }
4890
4891     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4892
4893     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4894       // Span too large for a VEXT to cope
4895       return SDValue();
4896     }
4897
4898     if (Src.MinElt >= NumSrcElts) {
4899       // The extraction can just take the second half
4900       Src.ShuffleVec =
4901           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4902                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4903       Src.WindowBase = -NumSrcElts;
4904     } else if (Src.MaxElt < NumSrcElts) {
4905       // The extraction can just take the first half
4906       Src.ShuffleVec =
4907           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4908                       DAG.getConstant(0, dl, MVT::i64));
4909     } else {
4910       // An actual VEXT is needed
4911       SDValue VEXTSrc1 =
4912           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4913                       DAG.getConstant(0, dl, MVT::i64));
4914       SDValue VEXTSrc2 =
4915           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4916                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4917       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4918
4919       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4920                                    VEXTSrc2,
4921                                    DAG.getConstant(Imm, dl, MVT::i32));
4922       Src.WindowBase = -Src.MinElt;
4923     }
4924   }
4925
4926   // Another possible incompatibility occurs from the vector element types. We
4927   // can fix this by bitcasting the source vectors to the same type we intend
4928   // for the shuffle.
4929   for (auto &Src : Sources) {
4930     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4931     if (SrcEltTy == SmallestEltTy)
4932       continue;
4933     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4934     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4935     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4936     Src.WindowBase *= Src.WindowScale;
4937   }
4938
4939   // Final sanity check before we try to actually produce a shuffle.
4940   DEBUG(
4941     for (auto Src : Sources)
4942       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4943   );
4944
4945   // The stars all align, our next step is to produce the mask for the shuffle.
4946   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4947   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4948   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4949     SDValue Entry = Op.getOperand(i);
4950     if (Entry.getOpcode() == ISD::UNDEF)
4951       continue;
4952
4953     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4954     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4955
4956     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4957     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4958     // segment.
4959     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4960     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4961                                VT.getVectorElementType().getSizeInBits());
4962     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4963
4964     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4965     // starting at the appropriate offset.
4966     int *LaneMask = &Mask[i * ResMultiplier];
4967
4968     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4969     ExtractBase += NumElts * (Src - Sources.begin());
4970     for (int j = 0; j < LanesDefined; ++j)
4971       LaneMask[j] = ExtractBase + j;
4972   }
4973
4974   // Final check before we try to produce nonsense...
4975   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4976     return SDValue();
4977
4978   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4979   for (unsigned i = 0; i < Sources.size(); ++i)
4980     ShuffleOps[i] = Sources[i].ShuffleVec;
4981
4982   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4983                                          ShuffleOps[1], &Mask[0]);
4984   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4985 }
4986
4987 // check if an EXT instruction can handle the shuffle mask when the
4988 // vector sources of the shuffle are the same.
4989 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4990   unsigned NumElts = VT.getVectorNumElements();
4991
4992   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4993   if (M[0] < 0)
4994     return false;
4995
4996   Imm = M[0];
4997
4998   // If this is a VEXT shuffle, the immediate value is the index of the first
4999   // element.  The other shuffle indices must be the successive elements after
5000   // the first one.
5001   unsigned ExpectedElt = Imm;
5002   for (unsigned i = 1; i < NumElts; ++i) {
5003     // Increment the expected index.  If it wraps around, just follow it
5004     // back to index zero and keep going.
5005     ++ExpectedElt;
5006     if (ExpectedElt == NumElts)
5007       ExpectedElt = 0;
5008
5009     if (M[i] < 0)
5010       continue; // ignore UNDEF indices
5011     if (ExpectedElt != static_cast<unsigned>(M[i]))
5012       return false;
5013   }
5014
5015   return true;
5016 }
5017
5018 // check if an EXT instruction can handle the shuffle mask when the
5019 // vector sources of the shuffle are different.
5020 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5021                       unsigned &Imm) {
5022   // Look for the first non-undef element.
5023   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5024       [](int Elt) {return Elt >= 0;});
5025
5026   // Benefit form APInt to handle overflow when calculating expected element.
5027   unsigned NumElts = VT.getVectorNumElements();
5028   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5029   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5030   // The following shuffle indices must be the successive elements after the
5031   // first real element.
5032   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5033       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5034   if (FirstWrongElt != M.end())
5035     return false;
5036
5037   // The index of an EXT is the first element if it is not UNDEF.
5038   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5039   // value of the first element.  E.g. 
5040   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5041   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5042   // ExpectedElt is the last mask index plus 1.
5043   Imm = ExpectedElt.getZExtValue();
5044
5045   // There are two difference cases requiring to reverse input vectors.
5046   // For example, for vector <4 x i32> we have the following cases,
5047   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5048   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5049   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5050   // to reverse two input vectors.
5051   if (Imm < NumElts)
5052     ReverseEXT = true;
5053   else
5054     Imm -= NumElts;
5055
5056   return true;
5057 }
5058
5059 /// isREVMask - Check if a vector shuffle corresponds to a REV
5060 /// instruction with the specified blocksize.  (The order of the elements
5061 /// within each block of the vector is reversed.)
5062 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5063   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5064          "Only possible block sizes for REV are: 16, 32, 64");
5065
5066   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5067   if (EltSz == 64)
5068     return false;
5069
5070   unsigned NumElts = VT.getVectorNumElements();
5071   unsigned BlockElts = M[0] + 1;
5072   // If the first shuffle index is UNDEF, be optimistic.
5073   if (M[0] < 0)
5074     BlockElts = BlockSize / EltSz;
5075
5076   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5077     return false;
5078
5079   for (unsigned i = 0; i < NumElts; ++i) {
5080     if (M[i] < 0)
5081       continue; // ignore UNDEF indices
5082     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5083       return false;
5084   }
5085
5086   return true;
5087 }
5088
5089 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5090   unsigned NumElts = VT.getVectorNumElements();
5091   WhichResult = (M[0] == 0 ? 0 : 1);
5092   unsigned Idx = WhichResult * NumElts / 2;
5093   for (unsigned i = 0; i != NumElts; i += 2) {
5094     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5095         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5096       return false;
5097     Idx += 1;
5098   }
5099
5100   return true;
5101 }
5102
5103 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5104   unsigned NumElts = VT.getVectorNumElements();
5105   WhichResult = (M[0] == 0 ? 0 : 1);
5106   for (unsigned i = 0; i != NumElts; ++i) {
5107     if (M[i] < 0)
5108       continue; // ignore UNDEF indices
5109     if ((unsigned)M[i] != 2 * i + WhichResult)
5110       return false;
5111   }
5112
5113   return true;
5114 }
5115
5116 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5117   unsigned NumElts = VT.getVectorNumElements();
5118   WhichResult = (M[0] == 0 ? 0 : 1);
5119   for (unsigned i = 0; i < NumElts; i += 2) {
5120     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5121         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5122       return false;
5123   }
5124   return true;
5125 }
5126
5127 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5128 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5129 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5130 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5131   unsigned NumElts = VT.getVectorNumElements();
5132   WhichResult = (M[0] == 0 ? 0 : 1);
5133   unsigned Idx = WhichResult * NumElts / 2;
5134   for (unsigned i = 0; i != NumElts; i += 2) {
5135     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5136         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5137       return false;
5138     Idx += 1;
5139   }
5140
5141   return true;
5142 }
5143
5144 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5145 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5146 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5147 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5148   unsigned Half = VT.getVectorNumElements() / 2;
5149   WhichResult = (M[0] == 0 ? 0 : 1);
5150   for (unsigned j = 0; j != 2; ++j) {
5151     unsigned Idx = WhichResult;
5152     for (unsigned i = 0; i != Half; ++i) {
5153       int MIdx = M[i + j * Half];
5154       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5155         return false;
5156       Idx += 2;
5157     }
5158   }
5159
5160   return true;
5161 }
5162
5163 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5164 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5165 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5166 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5167   unsigned NumElts = VT.getVectorNumElements();
5168   WhichResult = (M[0] == 0 ? 0 : 1);
5169   for (unsigned i = 0; i < NumElts; i += 2) {
5170     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5171         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5172       return false;
5173   }
5174   return true;
5175 }
5176
5177 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5178                       bool &DstIsLeft, int &Anomaly) {
5179   if (M.size() != static_cast<size_t>(NumInputElements))
5180     return false;
5181
5182   int NumLHSMatch = 0, NumRHSMatch = 0;
5183   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5184
5185   for (int i = 0; i < NumInputElements; ++i) {
5186     if (M[i] == -1) {
5187       ++NumLHSMatch;
5188       ++NumRHSMatch;
5189       continue;
5190     }
5191
5192     if (M[i] == i)
5193       ++NumLHSMatch;
5194     else
5195       LastLHSMismatch = i;
5196
5197     if (M[i] == i + NumInputElements)
5198       ++NumRHSMatch;
5199     else
5200       LastRHSMismatch = i;
5201   }
5202
5203   if (NumLHSMatch == NumInputElements - 1) {
5204     DstIsLeft = true;
5205     Anomaly = LastLHSMismatch;
5206     return true;
5207   } else if (NumRHSMatch == NumInputElements - 1) {
5208     DstIsLeft = false;
5209     Anomaly = LastRHSMismatch;
5210     return true;
5211   }
5212
5213   return false;
5214 }
5215
5216 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5217   if (VT.getSizeInBits() != 128)
5218     return false;
5219
5220   unsigned NumElts = VT.getVectorNumElements();
5221
5222   for (int I = 0, E = NumElts / 2; I != E; I++) {
5223     if (Mask[I] != I)
5224       return false;
5225   }
5226
5227   int Offset = NumElts / 2;
5228   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5229     if (Mask[I] != I + SplitLHS * Offset)
5230       return false;
5231   }
5232
5233   return true;
5234 }
5235
5236 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5237   SDLoc DL(Op);
5238   EVT VT = Op.getValueType();
5239   SDValue V0 = Op.getOperand(0);
5240   SDValue V1 = Op.getOperand(1);
5241   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5242
5243   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5244       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5245     return SDValue();
5246
5247   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5248
5249   if (!isConcatMask(Mask, VT, SplitV0))
5250     return SDValue();
5251
5252   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5253                                 VT.getVectorNumElements() / 2);
5254   if (SplitV0) {
5255     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5256                      DAG.getConstant(0, DL, MVT::i64));
5257   }
5258   if (V1.getValueType().getSizeInBits() == 128) {
5259     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5260                      DAG.getConstant(0, DL, MVT::i64));
5261   }
5262   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5263 }
5264
5265 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5266 /// the specified operations to build the shuffle.
5267 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5268                                       SDValue RHS, SelectionDAG &DAG,
5269                                       SDLoc dl) {
5270   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5271   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5272   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5273
5274   enum {
5275     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5276     OP_VREV,
5277     OP_VDUP0,
5278     OP_VDUP1,
5279     OP_VDUP2,
5280     OP_VDUP3,
5281     OP_VEXT1,
5282     OP_VEXT2,
5283     OP_VEXT3,
5284     OP_VUZPL, // VUZP, left result
5285     OP_VUZPR, // VUZP, right result
5286     OP_VZIPL, // VZIP, left result
5287     OP_VZIPR, // VZIP, right result
5288     OP_VTRNL, // VTRN, left result
5289     OP_VTRNR  // VTRN, right result
5290   };
5291
5292   if (OpNum == OP_COPY) {
5293     if (LHSID == (1 * 9 + 2) * 9 + 3)
5294       return LHS;
5295     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5296     return RHS;
5297   }
5298
5299   SDValue OpLHS, OpRHS;
5300   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5301   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5302   EVT VT = OpLHS.getValueType();
5303
5304   switch (OpNum) {
5305   default:
5306     llvm_unreachable("Unknown shuffle opcode!");
5307   case OP_VREV:
5308     // VREV divides the vector in half and swaps within the half.
5309     if (VT.getVectorElementType() == MVT::i32 ||
5310         VT.getVectorElementType() == MVT::f32)
5311       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5312     // vrev <4 x i16> -> REV32
5313     if (VT.getVectorElementType() == MVT::i16 ||
5314         VT.getVectorElementType() == MVT::f16)
5315       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5316     // vrev <4 x i8> -> REV16
5317     assert(VT.getVectorElementType() == MVT::i8);
5318     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5319   case OP_VDUP0:
5320   case OP_VDUP1:
5321   case OP_VDUP2:
5322   case OP_VDUP3: {
5323     EVT EltTy = VT.getVectorElementType();
5324     unsigned Opcode;
5325     if (EltTy == MVT::i8)
5326       Opcode = AArch64ISD::DUPLANE8;
5327     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5328       Opcode = AArch64ISD::DUPLANE16;
5329     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5330       Opcode = AArch64ISD::DUPLANE32;
5331     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5332       Opcode = AArch64ISD::DUPLANE64;
5333     else
5334       llvm_unreachable("Invalid vector element type?");
5335
5336     if (VT.getSizeInBits() == 64)
5337       OpLHS = WidenVector(OpLHS, DAG);
5338     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5339     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5340   }
5341   case OP_VEXT1:
5342   case OP_VEXT2:
5343   case OP_VEXT3: {
5344     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5345     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5346                        DAG.getConstant(Imm, dl, MVT::i32));
5347   }
5348   case OP_VUZPL:
5349     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5350                        OpRHS);
5351   case OP_VUZPR:
5352     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5353                        OpRHS);
5354   case OP_VZIPL:
5355     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5356                        OpRHS);
5357   case OP_VZIPR:
5358     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5359                        OpRHS);
5360   case OP_VTRNL:
5361     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5362                        OpRHS);
5363   case OP_VTRNR:
5364     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5365                        OpRHS);
5366   }
5367 }
5368
5369 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5370                            SelectionDAG &DAG) {
5371   // Check to see if we can use the TBL instruction.
5372   SDValue V1 = Op.getOperand(0);
5373   SDValue V2 = Op.getOperand(1);
5374   SDLoc DL(Op);
5375
5376   EVT EltVT = Op.getValueType().getVectorElementType();
5377   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5378
5379   SmallVector<SDValue, 8> TBLMask;
5380   for (int Val : ShuffleMask) {
5381     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5382       unsigned Offset = Byte + Val * BytesPerElt;
5383       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5384     }
5385   }
5386
5387   MVT IndexVT = MVT::v8i8;
5388   unsigned IndexLen = 8;
5389   if (Op.getValueType().getSizeInBits() == 128) {
5390     IndexVT = MVT::v16i8;
5391     IndexLen = 16;
5392   }
5393
5394   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5395   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5396
5397   SDValue Shuffle;
5398   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5399     if (IndexLen == 8)
5400       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5401     Shuffle = DAG.getNode(
5402         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5403         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5404         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5405                     makeArrayRef(TBLMask.data(), IndexLen)));
5406   } else {
5407     if (IndexLen == 8) {
5408       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5409       Shuffle = DAG.getNode(
5410           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5411           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5412           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5413                       makeArrayRef(TBLMask.data(), IndexLen)));
5414     } else {
5415       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5416       // cannot currently represent the register constraints on the input
5417       // table registers.
5418       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5419       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5420       //                               &TBLMask[0], IndexLen));
5421       Shuffle = DAG.getNode(
5422           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5423           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5424           V1Cst, V2Cst,
5425           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5426                       makeArrayRef(TBLMask.data(), IndexLen)));
5427     }
5428   }
5429   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5430 }
5431
5432 static unsigned getDUPLANEOp(EVT EltType) {
5433   if (EltType == MVT::i8)
5434     return AArch64ISD::DUPLANE8;
5435   if (EltType == MVT::i16 || EltType == MVT::f16)
5436     return AArch64ISD::DUPLANE16;
5437   if (EltType == MVT::i32 || EltType == MVT::f32)
5438     return AArch64ISD::DUPLANE32;
5439   if (EltType == MVT::i64 || EltType == MVT::f64)
5440     return AArch64ISD::DUPLANE64;
5441
5442   llvm_unreachable("Invalid vector element type?");
5443 }
5444
5445 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5446                                                    SelectionDAG &DAG) const {
5447   SDLoc dl(Op);
5448   EVT VT = Op.getValueType();
5449
5450   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5451
5452   // Convert shuffles that are directly supported on NEON to target-specific
5453   // DAG nodes, instead of keeping them as shuffles and matching them again
5454   // during code selection.  This is more efficient and avoids the possibility
5455   // of inconsistencies between legalization and selection.
5456   ArrayRef<int> ShuffleMask = SVN->getMask();
5457
5458   SDValue V1 = Op.getOperand(0);
5459   SDValue V2 = Op.getOperand(1);
5460
5461   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5462                                        V1.getValueType().getSimpleVT())) {
5463     int Lane = SVN->getSplatIndex();
5464     // If this is undef splat, generate it via "just" vdup, if possible.
5465     if (Lane == -1)
5466       Lane = 0;
5467
5468     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5469       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5470                          V1.getOperand(0));
5471     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5472     // constant. If so, we can just reference the lane's definition directly.
5473     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5474         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5475       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5476
5477     // Otherwise, duplicate from the lane of the input vector.
5478     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5479
5480     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5481     // to make a vector of the same size as this SHUFFLE. We can ignore the
5482     // extract entirely, and canonicalise the concat using WidenVector.
5483     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5484       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5485       V1 = V1.getOperand(0);
5486     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5487       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5488       Lane -= Idx * VT.getVectorNumElements() / 2;
5489       V1 = WidenVector(V1.getOperand(Idx), DAG);
5490     } else if (VT.getSizeInBits() == 64)
5491       V1 = WidenVector(V1, DAG);
5492
5493     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5494   }
5495
5496   if (isREVMask(ShuffleMask, VT, 64))
5497     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5498   if (isREVMask(ShuffleMask, VT, 32))
5499     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5500   if (isREVMask(ShuffleMask, VT, 16))
5501     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5502
5503   bool ReverseEXT = false;
5504   unsigned Imm;
5505   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5506     if (ReverseEXT)
5507       std::swap(V1, V2);
5508     Imm *= getExtFactor(V1);
5509     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5510                        DAG.getConstant(Imm, dl, MVT::i32));
5511   } else if (V2->getOpcode() == ISD::UNDEF &&
5512              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5513     Imm *= getExtFactor(V1);
5514     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5515                        DAG.getConstant(Imm, dl, MVT::i32));
5516   }
5517
5518   unsigned WhichResult;
5519   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5520     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5521     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5522   }
5523   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5524     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5525     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5526   }
5527   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5528     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5529     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5530   }
5531
5532   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5533     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5534     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5535   }
5536   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5537     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5538     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5539   }
5540   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5541     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5542     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5543   }
5544
5545   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5546   if (Concat.getNode())
5547     return Concat;
5548
5549   bool DstIsLeft;
5550   int Anomaly;
5551   int NumInputElements = V1.getValueType().getVectorNumElements();
5552   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5553     SDValue DstVec = DstIsLeft ? V1 : V2;
5554     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5555
5556     SDValue SrcVec = V1;
5557     int SrcLane = ShuffleMask[Anomaly];
5558     if (SrcLane >= NumInputElements) {
5559       SrcVec = V2;
5560       SrcLane -= VT.getVectorNumElements();
5561     }
5562     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5563
5564     EVT ScalarVT = VT.getVectorElementType();
5565
5566     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5567       ScalarVT = MVT::i32;
5568
5569     return DAG.getNode(
5570         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5571         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5572         DstLaneV);
5573   }
5574
5575   // If the shuffle is not directly supported and it has 4 elements, use
5576   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5577   unsigned NumElts = VT.getVectorNumElements();
5578   if (NumElts == 4) {
5579     unsigned PFIndexes[4];
5580     for (unsigned i = 0; i != 4; ++i) {
5581       if (ShuffleMask[i] < 0)
5582         PFIndexes[i] = 8;
5583       else
5584         PFIndexes[i] = ShuffleMask[i];
5585     }
5586
5587     // Compute the index in the perfect shuffle table.
5588     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5589                             PFIndexes[2] * 9 + PFIndexes[3];
5590     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5591     unsigned Cost = (PFEntry >> 30);
5592
5593     if (Cost <= 4)
5594       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5595   }
5596
5597   return GenerateTBL(Op, ShuffleMask, DAG);
5598 }
5599
5600 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5601                                APInt &UndefBits) {
5602   EVT VT = BVN->getValueType(0);
5603   APInt SplatBits, SplatUndef;
5604   unsigned SplatBitSize;
5605   bool HasAnyUndefs;
5606   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5607     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5608
5609     for (unsigned i = 0; i < NumSplats; ++i) {
5610       CnstBits <<= SplatBitSize;
5611       UndefBits <<= SplatBitSize;
5612       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5613       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5614     }
5615
5616     return true;
5617   }
5618
5619   return false;
5620 }
5621
5622 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5623                                               SelectionDAG &DAG) const {
5624   BuildVectorSDNode *BVN =
5625       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5626   SDValue LHS = Op.getOperand(0);
5627   SDLoc dl(Op);
5628   EVT VT = Op.getValueType();
5629
5630   if (!BVN)
5631     return Op;
5632
5633   APInt CnstBits(VT.getSizeInBits(), 0);
5634   APInt UndefBits(VT.getSizeInBits(), 0);
5635   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5636     // We only have BIC vector immediate instruction, which is and-not.
5637     CnstBits = ~CnstBits;
5638
5639     // We make use of a little bit of goto ickiness in order to avoid having to
5640     // duplicate the immediate matching logic for the undef toggled case.
5641     bool SecondTry = false;
5642   AttemptModImm:
5643
5644     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5645       CnstBits = CnstBits.zextOrTrunc(64);
5646       uint64_t CnstVal = CnstBits.getZExtValue();
5647
5648       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5649         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5650         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5651         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5652                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5653                                   DAG.getConstant(0, dl, MVT::i32));
5654         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5655       }
5656
5657       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5658         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5659         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5660         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5661                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5662                                   DAG.getConstant(8, dl, MVT::i32));
5663         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5664       }
5665
5666       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5667         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5668         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5669         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5670                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5671                                   DAG.getConstant(16, dl, MVT::i32));
5672         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5673       }
5674
5675       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5676         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5677         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5678         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5679                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5680                                   DAG.getConstant(24, dl, MVT::i32));
5681         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5682       }
5683
5684       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5685         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5686         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5687         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5688                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5689                                   DAG.getConstant(0, dl, MVT::i32));
5690         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5691       }
5692
5693       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5694         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5695         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5696         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5697                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5698                                   DAG.getConstant(8, dl, MVT::i32));
5699         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5700       }
5701     }
5702
5703     if (SecondTry)
5704       goto FailedModImm;
5705     SecondTry = true;
5706     CnstBits = ~UndefBits;
5707     goto AttemptModImm;
5708   }
5709
5710 // We can always fall back to a non-immediate AND.
5711 FailedModImm:
5712   return Op;
5713 }
5714
5715 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5716 // consists of only the same constant int value, returned in reference arg
5717 // ConstVal
5718 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5719                                      uint64_t &ConstVal) {
5720   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5721   if (!Bvec)
5722     return false;
5723   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5724   if (!FirstElt)
5725     return false;
5726   EVT VT = Bvec->getValueType(0);
5727   unsigned NumElts = VT.getVectorNumElements();
5728   for (unsigned i = 1; i < NumElts; ++i)
5729     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5730       return false;
5731   ConstVal = FirstElt->getZExtValue();
5732   return true;
5733 }
5734
5735 static unsigned getIntrinsicID(const SDNode *N) {
5736   unsigned Opcode = N->getOpcode();
5737   switch (Opcode) {
5738   default:
5739     return Intrinsic::not_intrinsic;
5740   case ISD::INTRINSIC_WO_CHAIN: {
5741     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5742     if (IID < Intrinsic::num_intrinsics)
5743       return IID;
5744     return Intrinsic::not_intrinsic;
5745   }
5746   }
5747 }
5748
5749 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5750 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5751 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5752 // Also, logical shift right -> sri, with the same structure.
5753 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5754   EVT VT = N->getValueType(0);
5755
5756   if (!VT.isVector())
5757     return SDValue();
5758
5759   SDLoc DL(N);
5760
5761   // Is the first op an AND?
5762   const SDValue And = N->getOperand(0);
5763   if (And.getOpcode() != ISD::AND)
5764     return SDValue();
5765
5766   // Is the second op an shl or lshr?
5767   SDValue Shift = N->getOperand(1);
5768   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5769   // or AArch64ISD::VLSHR vector, #shift
5770   unsigned ShiftOpc = Shift.getOpcode();
5771   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5772     return SDValue();
5773   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5774
5775   // Is the shift amount constant?
5776   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5777   if (!C2node)
5778     return SDValue();
5779
5780   // Is the and mask vector all constant?
5781   uint64_t C1;
5782   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5783     return SDValue();
5784
5785   // Is C1 == ~C2, taking into account how much one can shift elements of a
5786   // particular size?
5787   uint64_t C2 = C2node->getZExtValue();
5788   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5789   if (C2 > ElemSizeInBits)
5790     return SDValue();
5791   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5792   if ((C1 & ElemMask) != (~C2 & ElemMask))
5793     return SDValue();
5794
5795   SDValue X = And.getOperand(0);
5796   SDValue Y = Shift.getOperand(0);
5797
5798   unsigned Intrin =
5799       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5800   SDValue ResultSLI =
5801       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5802                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5803                   Shift.getOperand(1));
5804
5805   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5806   DEBUG(N->dump(&DAG));
5807   DEBUG(dbgs() << "into: \n");
5808   DEBUG(ResultSLI->dump(&DAG));
5809
5810   ++NumShiftInserts;
5811   return ResultSLI;
5812 }
5813
5814 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5815                                              SelectionDAG &DAG) const {
5816   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5817   if (EnableAArch64SlrGeneration) {
5818     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5819     if (Res.getNode())
5820       return Res;
5821   }
5822
5823   BuildVectorSDNode *BVN =
5824       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5825   SDValue LHS = Op.getOperand(1);
5826   SDLoc dl(Op);
5827   EVT VT = Op.getValueType();
5828
5829   // OR commutes, so try swapping the operands.
5830   if (!BVN) {
5831     LHS = Op.getOperand(0);
5832     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5833   }
5834   if (!BVN)
5835     return Op;
5836
5837   APInt CnstBits(VT.getSizeInBits(), 0);
5838   APInt UndefBits(VT.getSizeInBits(), 0);
5839   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5840     // We make use of a little bit of goto ickiness in order to avoid having to
5841     // duplicate the immediate matching logic for the undef toggled case.
5842     bool SecondTry = false;
5843   AttemptModImm:
5844
5845     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5846       CnstBits = CnstBits.zextOrTrunc(64);
5847       uint64_t CnstVal = CnstBits.getZExtValue();
5848
5849       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5850         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5851         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5852         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5853                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5854                                   DAG.getConstant(0, dl, MVT::i32));
5855         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5856       }
5857
5858       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5859         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5860         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5861         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5862                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5863                                   DAG.getConstant(8, dl, MVT::i32));
5864         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5865       }
5866
5867       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5868         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5869         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5870         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5871                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5872                                   DAG.getConstant(16, dl, MVT::i32));
5873         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5874       }
5875
5876       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5877         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5878         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5879         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5880                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5881                                   DAG.getConstant(24, dl, MVT::i32));
5882         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5883       }
5884
5885       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5886         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5887         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5888         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5889                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5890                                   DAG.getConstant(0, dl, MVT::i32));
5891         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5892       }
5893
5894       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5895         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5896         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5897         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5898                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5899                                   DAG.getConstant(8, dl, MVT::i32));
5900         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5901       }
5902     }
5903
5904     if (SecondTry)
5905       goto FailedModImm;
5906     SecondTry = true;
5907     CnstBits = UndefBits;
5908     goto AttemptModImm;
5909   }
5910
5911 // We can always fall back to a non-immediate OR.
5912 FailedModImm:
5913   return Op;
5914 }
5915
5916 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5917 // be truncated to fit element width.
5918 static SDValue NormalizeBuildVector(SDValue Op,
5919                                     SelectionDAG &DAG) {
5920   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5921   SDLoc dl(Op);
5922   EVT VT = Op.getValueType();
5923   EVT EltTy= VT.getVectorElementType();
5924
5925   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5926     return Op;
5927
5928   SmallVector<SDValue, 16> Ops;
5929   for (SDValue Lane : Op->ops()) {
5930     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5931       APInt LowBits(EltTy.getSizeInBits(),
5932                     CstLane->getZExtValue());
5933       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5934     }
5935     Ops.push_back(Lane);
5936   }
5937   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5938 }
5939
5940 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5941                                                  SelectionDAG &DAG) const {
5942   SDLoc dl(Op);
5943   EVT VT = Op.getValueType();
5944   Op = NormalizeBuildVector(Op, DAG);
5945   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5946
5947   APInt CnstBits(VT.getSizeInBits(), 0);
5948   APInt UndefBits(VT.getSizeInBits(), 0);
5949   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5950     // We make use of a little bit of goto ickiness in order to avoid having to
5951     // duplicate the immediate matching logic for the undef toggled case.
5952     bool SecondTry = false;
5953   AttemptModImm:
5954
5955     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5956       CnstBits = CnstBits.zextOrTrunc(64);
5957       uint64_t CnstVal = CnstBits.getZExtValue();
5958
5959       // Certain magic vector constants (used to express things like NOT
5960       // and NEG) are passed through unmodified.  This allows codegen patterns
5961       // for these operations to match.  Special-purpose patterns will lower
5962       // these immediates to MOVIs if it proves necessary.
5963       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5964         return Op;
5965
5966       // The many faces of MOVI...
5967       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5968         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5969         if (VT.getSizeInBits() == 128) {
5970           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5971                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5972           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5973         }
5974
5975         // Support the V64 version via subregister insertion.
5976         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5977                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5978         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5979       }
5980
5981       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5982         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5983         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5984         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5985                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5986                                   DAG.getConstant(0, dl, MVT::i32));
5987         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5988       }
5989
5990       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5991         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5992         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5993         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5994                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5995                                   DAG.getConstant(8, dl, MVT::i32));
5996         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5997       }
5998
5999       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6000         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6001         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6002         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6003                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6004                                   DAG.getConstant(16, dl, MVT::i32));
6005         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6006       }
6007
6008       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6009         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6010         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6011         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6012                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6013                                   DAG.getConstant(24, dl, MVT::i32));
6014         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6015       }
6016
6017       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6018         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6019         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6020         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6021                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6022                                   DAG.getConstant(0, dl, MVT::i32));
6023         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6024       }
6025
6026       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6027         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6028         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6029         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6030                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6031                                   DAG.getConstant(8, dl, MVT::i32));
6032         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6033       }
6034
6035       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6036         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6037         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6038         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6039                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6040                                   DAG.getConstant(264, dl, MVT::i32));
6041         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6042       }
6043
6044       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6045         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6046         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6047         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6048                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6049                                   DAG.getConstant(272, dl, MVT::i32));
6050         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6051       }
6052
6053       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6054         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6055         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6056         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6057                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6058         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6059       }
6060
6061       // The few faces of FMOV...
6062       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6063         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6064         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6065         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6066                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6067         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6068       }
6069
6070       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6071           VT.getSizeInBits() == 128) {
6072         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6073         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6074                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6075         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6076       }
6077
6078       // The many faces of MVNI...
6079       CnstVal = ~CnstVal;
6080       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6081         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6082         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6083         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6084                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6085                                   DAG.getConstant(0, dl, MVT::i32));
6086         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6087       }
6088
6089       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6090         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6091         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6092         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6093                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6094                                   DAG.getConstant(8, dl, MVT::i32));
6095         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6096       }
6097
6098       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6099         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6100         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6101         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6102                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6103                                   DAG.getConstant(16, dl, MVT::i32));
6104         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6105       }
6106
6107       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6108         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6109         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6110         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6111                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6112                                   DAG.getConstant(24, dl, MVT::i32));
6113         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6114       }
6115
6116       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6117         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6118         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6119         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6120                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6121                                   DAG.getConstant(0, dl, MVT::i32));
6122         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6123       }
6124
6125       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6126         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6127         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6128         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6129                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6130                                   DAG.getConstant(8, dl, MVT::i32));
6131         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6132       }
6133
6134       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6135         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6136         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6137         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6138                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6139                                   DAG.getConstant(264, dl, MVT::i32));
6140         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6141       }
6142
6143       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6144         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6145         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6146         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6147                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6148                                   DAG.getConstant(272, dl, MVT::i32));
6149         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6150       }
6151     }
6152
6153     if (SecondTry)
6154       goto FailedModImm;
6155     SecondTry = true;
6156     CnstBits = UndefBits;
6157     goto AttemptModImm;
6158   }
6159 FailedModImm:
6160
6161   // Scan through the operands to find some interesting properties we can
6162   // exploit:
6163   //   1) If only one value is used, we can use a DUP, or
6164   //   2) if only the low element is not undef, we can just insert that, or
6165   //   3) if only one constant value is used (w/ some non-constant lanes),
6166   //      we can splat the constant value into the whole vector then fill
6167   //      in the non-constant lanes.
6168   //   4) FIXME: If different constant values are used, but we can intelligently
6169   //             select the values we'll be overwriting for the non-constant
6170   //             lanes such that we can directly materialize the vector
6171   //             some other way (MOVI, e.g.), we can be sneaky.
6172   unsigned NumElts = VT.getVectorNumElements();
6173   bool isOnlyLowElement = true;
6174   bool usesOnlyOneValue = true;
6175   bool usesOnlyOneConstantValue = true;
6176   bool isConstant = true;
6177   unsigned NumConstantLanes = 0;
6178   SDValue Value;
6179   SDValue ConstantValue;
6180   for (unsigned i = 0; i < NumElts; ++i) {
6181     SDValue V = Op.getOperand(i);
6182     if (V.getOpcode() == ISD::UNDEF)
6183       continue;
6184     if (i > 0)
6185       isOnlyLowElement = false;
6186     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6187       isConstant = false;
6188
6189     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6190       ++NumConstantLanes;
6191       if (!ConstantValue.getNode())
6192         ConstantValue = V;
6193       else if (ConstantValue != V)
6194         usesOnlyOneConstantValue = false;
6195     }
6196
6197     if (!Value.getNode())
6198       Value = V;
6199     else if (V != Value)
6200       usesOnlyOneValue = false;
6201   }
6202
6203   if (!Value.getNode())
6204     return DAG.getUNDEF(VT);
6205
6206   if (isOnlyLowElement)
6207     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6208
6209   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6210   // i32 and try again.
6211   if (usesOnlyOneValue) {
6212     if (!isConstant) {
6213       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6214           Value.getValueType() != VT)
6215         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6216
6217       // This is actually a DUPLANExx operation, which keeps everything vectory.
6218
6219       // DUPLANE works on 128-bit vectors, widen it if necessary.
6220       SDValue Lane = Value.getOperand(1);
6221       Value = Value.getOperand(0);
6222       if (Value.getValueType().getSizeInBits() == 64)
6223         Value = WidenVector(Value, DAG);
6224
6225       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6226       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6227     }
6228
6229     if (VT.getVectorElementType().isFloatingPoint()) {
6230       SmallVector<SDValue, 8> Ops;
6231       EVT EltTy = VT.getVectorElementType();
6232       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6233               "Unsupported floating-point vector type");
6234       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6235       for (unsigned i = 0; i < NumElts; ++i)
6236         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6237       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6238       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6239       Val = LowerBUILD_VECTOR(Val, DAG);
6240       if (Val.getNode())
6241         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6242     }
6243   }
6244
6245   // If there was only one constant value used and for more than one lane,
6246   // start by splatting that value, then replace the non-constant lanes. This
6247   // is better than the default, which will perform a separate initialization
6248   // for each lane.
6249   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6250     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6251     // Now insert the non-constant lanes.
6252     for (unsigned i = 0; i < NumElts; ++i) {
6253       SDValue V = Op.getOperand(i);
6254       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6255       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6256         // Note that type legalization likely mucked about with the VT of the
6257         // source operand, so we may have to convert it here before inserting.
6258         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6259       }
6260     }
6261     return Val;
6262   }
6263
6264   // If all elements are constants and the case above didn't get hit, fall back
6265   // to the default expansion, which will generate a load from the constant
6266   // pool.
6267   if (isConstant)
6268     return SDValue();
6269
6270   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6271   if (NumElts >= 4) {
6272     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6273       return shuffle;
6274   }
6275
6276   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6277   // know the default expansion would otherwise fall back on something even
6278   // worse. For a vector with one or two non-undef values, that's
6279   // scalar_to_vector for the elements followed by a shuffle (provided the
6280   // shuffle is valid for the target) and materialization element by element
6281   // on the stack followed by a load for everything else.
6282   if (!isConstant && !usesOnlyOneValue) {
6283     SDValue Vec = DAG.getUNDEF(VT);
6284     SDValue Op0 = Op.getOperand(0);
6285     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6286     unsigned i = 0;
6287     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6288     // a) Avoid a RMW dependency on the full vector register, and
6289     // b) Allow the register coalescer to fold away the copy if the
6290     //    value is already in an S or D register.
6291     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6292     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6293     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6294         (ElemSize == 32 || ElemSize == 64)) {
6295       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6296       MachineSDNode *N =
6297           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6298                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6299       Vec = SDValue(N, 0);
6300       ++i;
6301     }
6302     for (; i < NumElts; ++i) {
6303       SDValue V = Op.getOperand(i);
6304       if (V.getOpcode() == ISD::UNDEF)
6305         continue;
6306       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6307       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6308     }
6309     return Vec;
6310   }
6311
6312   // Just use the default expansion. We failed to find a better alternative.
6313   return SDValue();
6314 }
6315
6316 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6317                                                       SelectionDAG &DAG) const {
6318   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6319
6320   // Check for non-constant or out of range lane.
6321   EVT VT = Op.getOperand(0).getValueType();
6322   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6323   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6324     return SDValue();
6325
6326
6327   // Insertion/extraction are legal for V128 types.
6328   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6329       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6330       VT == MVT::v8f16)
6331     return Op;
6332
6333   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6334       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6335     return SDValue();
6336
6337   // For V64 types, we perform insertion by expanding the value
6338   // to a V128 type and perform the insertion on that.
6339   SDLoc DL(Op);
6340   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6341   EVT WideTy = WideVec.getValueType();
6342
6343   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6344                              Op.getOperand(1), Op.getOperand(2));
6345   // Re-narrow the resultant vector.
6346   return NarrowVector(Node, DAG);
6347 }
6348
6349 SDValue
6350 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6351                                                SelectionDAG &DAG) const {
6352   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6353
6354   // Check for non-constant or out of range lane.
6355   EVT VT = Op.getOperand(0).getValueType();
6356   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6357   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6358     return SDValue();
6359
6360
6361   // Insertion/extraction are legal for V128 types.
6362   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6363       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6364       VT == MVT::v8f16)
6365     return Op;
6366
6367   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6368       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6369     return SDValue();
6370
6371   // For V64 types, we perform extraction by expanding the value
6372   // to a V128 type and perform the extraction on that.
6373   SDLoc DL(Op);
6374   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6375   EVT WideTy = WideVec.getValueType();
6376
6377   EVT ExtrTy = WideTy.getVectorElementType();
6378   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6379     ExtrTy = MVT::i32;
6380
6381   // For extractions, we just return the result directly.
6382   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6383                      Op.getOperand(1));
6384 }
6385
6386 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6387                                                       SelectionDAG &DAG) const {
6388   EVT VT = Op.getOperand(0).getValueType();
6389   SDLoc dl(Op);
6390   // Just in case...
6391   if (!VT.isVector())
6392     return SDValue();
6393
6394   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6395   if (!Cst)
6396     return SDValue();
6397   unsigned Val = Cst->getZExtValue();
6398
6399   unsigned Size = Op.getValueType().getSizeInBits();
6400
6401   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6402   if (Val == 0)
6403     return Op;
6404
6405   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6406   // that directly.
6407   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6408     return Op;
6409
6410   return SDValue();
6411 }
6412
6413 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6414                                                EVT VT) const {
6415   if (VT.getVectorNumElements() == 4 &&
6416       (VT.is128BitVector() || VT.is64BitVector())) {
6417     unsigned PFIndexes[4];
6418     for (unsigned i = 0; i != 4; ++i) {
6419       if (M[i] < 0)
6420         PFIndexes[i] = 8;
6421       else
6422         PFIndexes[i] = M[i];
6423     }
6424
6425     // Compute the index in the perfect shuffle table.
6426     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6427                             PFIndexes[2] * 9 + PFIndexes[3];
6428     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6429     unsigned Cost = (PFEntry >> 30);
6430
6431     if (Cost <= 4)
6432       return true;
6433   }
6434
6435   bool DummyBool;
6436   int DummyInt;
6437   unsigned DummyUnsigned;
6438
6439   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6440           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6441           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6442           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6443           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6444           isZIPMask(M, VT, DummyUnsigned) ||
6445           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6446           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6447           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6448           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6449           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6450 }
6451
6452 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6453 /// operand of a vector shift operation, where all the elements of the
6454 /// build_vector must have the same constant integer value.
6455 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6456   // Ignore bit_converts.
6457   while (Op.getOpcode() == ISD::BITCAST)
6458     Op = Op.getOperand(0);
6459   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6460   APInt SplatBits, SplatUndef;
6461   unsigned SplatBitSize;
6462   bool HasAnyUndefs;
6463   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6464                                     HasAnyUndefs, ElementBits) ||
6465       SplatBitSize > ElementBits)
6466     return false;
6467   Cnt = SplatBits.getSExtValue();
6468   return true;
6469 }
6470
6471 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6472 /// operand of a vector shift left operation.  That value must be in the range:
6473 ///   0 <= Value < ElementBits for a left shift; or
6474 ///   0 <= Value <= ElementBits for a long left shift.
6475 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6476   assert(VT.isVector() && "vector shift count is not a vector type");
6477   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6478   if (!getVShiftImm(Op, ElementBits, Cnt))
6479     return false;
6480   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6481 }
6482
6483 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6484 /// operand of a vector shift right operation. The value must be in the range:
6485 ///   1 <= Value <= ElementBits for a right shift; or
6486 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6487   assert(VT.isVector() && "vector shift count is not a vector type");
6488   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6489   if (!getVShiftImm(Op, ElementBits, Cnt))
6490     return false;
6491   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6492 }
6493
6494 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6495                                                       SelectionDAG &DAG) const {
6496   EVT VT = Op.getValueType();
6497   SDLoc DL(Op);
6498   int64_t Cnt;
6499
6500   if (!Op.getOperand(1).getValueType().isVector())
6501     return Op;
6502   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6503
6504   switch (Op.getOpcode()) {
6505   default:
6506     llvm_unreachable("unexpected shift opcode");
6507
6508   case ISD::SHL:
6509     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6510       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6511                          DAG.getConstant(Cnt, DL, MVT::i32));
6512     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6513                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6514                                        MVT::i32),
6515                        Op.getOperand(0), Op.getOperand(1));
6516   case ISD::SRA:
6517   case ISD::SRL:
6518     // Right shift immediate
6519     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6520       unsigned Opc =
6521           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6522       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6523                          DAG.getConstant(Cnt, DL, MVT::i32));
6524     }
6525
6526     // Right shift register.  Note, there is not a shift right register
6527     // instruction, but the shift left register instruction takes a signed
6528     // value, where negative numbers specify a right shift.
6529     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6530                                                 : Intrinsic::aarch64_neon_ushl;
6531     // negate the shift amount
6532     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6533     SDValue NegShiftLeft =
6534         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6535                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6536                     NegShift);
6537     return NegShiftLeft;
6538   }
6539
6540   return SDValue();
6541 }
6542
6543 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6544                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6545                                     SDLoc dl, SelectionDAG &DAG) {
6546   EVT SrcVT = LHS.getValueType();
6547   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6548          "function only supposed to emit natural comparisons");
6549
6550   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6551   APInt CnstBits(VT.getSizeInBits(), 0);
6552   APInt UndefBits(VT.getSizeInBits(), 0);
6553   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6554   bool IsZero = IsCnst && (CnstBits == 0);
6555
6556   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6557     switch (CC) {
6558     default:
6559       return SDValue();
6560     case AArch64CC::NE: {
6561       SDValue Fcmeq;
6562       if (IsZero)
6563         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6564       else
6565         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6566       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6567     }
6568     case AArch64CC::EQ:
6569       if (IsZero)
6570         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6571       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6572     case AArch64CC::GE:
6573       if (IsZero)
6574         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6575       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6576     case AArch64CC::GT:
6577       if (IsZero)
6578         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6579       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6580     case AArch64CC::LS:
6581       if (IsZero)
6582         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6583       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6584     case AArch64CC::LT:
6585       if (!NoNans)
6586         return SDValue();
6587     // If we ignore NaNs then we can use to the MI implementation.
6588     // Fallthrough.
6589     case AArch64CC::MI:
6590       if (IsZero)
6591         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6592       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6593     }
6594   }
6595
6596   switch (CC) {
6597   default:
6598     return SDValue();
6599   case AArch64CC::NE: {
6600     SDValue Cmeq;
6601     if (IsZero)
6602       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6603     else
6604       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6605     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6606   }
6607   case AArch64CC::EQ:
6608     if (IsZero)
6609       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6610     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6611   case AArch64CC::GE:
6612     if (IsZero)
6613       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6614     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6615   case AArch64CC::GT:
6616     if (IsZero)
6617       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6618     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6619   case AArch64CC::LE:
6620     if (IsZero)
6621       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6622     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6623   case AArch64CC::LS:
6624     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6625   case AArch64CC::LO:
6626     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6627   case AArch64CC::LT:
6628     if (IsZero)
6629       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6630     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6631   case AArch64CC::HI:
6632     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6633   case AArch64CC::HS:
6634     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6635   }
6636 }
6637
6638 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6639                                            SelectionDAG &DAG) const {
6640   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6641   SDValue LHS = Op.getOperand(0);
6642   SDValue RHS = Op.getOperand(1);
6643   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6644   SDLoc dl(Op);
6645
6646   if (LHS.getValueType().getVectorElementType().isInteger()) {
6647     assert(LHS.getValueType() == RHS.getValueType());
6648     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6649     SDValue Cmp =
6650         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6651     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6652   }
6653
6654   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6655          LHS.getValueType().getVectorElementType() == MVT::f64);
6656
6657   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6658   // clean.  Some of them require two branches to implement.
6659   AArch64CC::CondCode CC1, CC2;
6660   bool ShouldInvert;
6661   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6662
6663   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6664   SDValue Cmp =
6665       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6666   if (!Cmp.getNode())
6667     return SDValue();
6668
6669   if (CC2 != AArch64CC::AL) {
6670     SDValue Cmp2 =
6671         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6672     if (!Cmp2.getNode())
6673       return SDValue();
6674
6675     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6676   }
6677
6678   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6679
6680   if (ShouldInvert)
6681     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6682
6683   return Cmp;
6684 }
6685
6686 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6687 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6688 /// specified in the intrinsic calls.
6689 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6690                                                const CallInst &I,
6691                                                unsigned Intrinsic) const {
6692   auto &DL = I.getModule()->getDataLayout();
6693   switch (Intrinsic) {
6694   case Intrinsic::aarch64_neon_ld2:
6695   case Intrinsic::aarch64_neon_ld3:
6696   case Intrinsic::aarch64_neon_ld4:
6697   case Intrinsic::aarch64_neon_ld1x2:
6698   case Intrinsic::aarch64_neon_ld1x3:
6699   case Intrinsic::aarch64_neon_ld1x4:
6700   case Intrinsic::aarch64_neon_ld2lane:
6701   case Intrinsic::aarch64_neon_ld3lane:
6702   case Intrinsic::aarch64_neon_ld4lane:
6703   case Intrinsic::aarch64_neon_ld2r:
6704   case Intrinsic::aarch64_neon_ld3r:
6705   case Intrinsic::aarch64_neon_ld4r: {
6706     Info.opc = ISD::INTRINSIC_W_CHAIN;
6707     // Conservatively set memVT to the entire set of vectors loaded.
6708     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6709     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6710     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6711     Info.offset = 0;
6712     Info.align = 0;
6713     Info.vol = false; // volatile loads with NEON intrinsics not supported
6714     Info.readMem = true;
6715     Info.writeMem = false;
6716     return true;
6717   }
6718   case Intrinsic::aarch64_neon_st2:
6719   case Intrinsic::aarch64_neon_st3:
6720   case Intrinsic::aarch64_neon_st4:
6721   case Intrinsic::aarch64_neon_st1x2:
6722   case Intrinsic::aarch64_neon_st1x3:
6723   case Intrinsic::aarch64_neon_st1x4:
6724   case Intrinsic::aarch64_neon_st2lane:
6725   case Intrinsic::aarch64_neon_st3lane:
6726   case Intrinsic::aarch64_neon_st4lane: {
6727     Info.opc = ISD::INTRINSIC_VOID;
6728     // Conservatively set memVT to the entire set of vectors stored.
6729     unsigned NumElts = 0;
6730     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6731       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6732       if (!ArgTy->isVectorTy())
6733         break;
6734       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6735     }
6736     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6737     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6738     Info.offset = 0;
6739     Info.align = 0;
6740     Info.vol = false; // volatile stores with NEON intrinsics not supported
6741     Info.readMem = false;
6742     Info.writeMem = true;
6743     return true;
6744   }
6745   case Intrinsic::aarch64_ldaxr:
6746   case Intrinsic::aarch64_ldxr: {
6747     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6748     Info.opc = ISD::INTRINSIC_W_CHAIN;
6749     Info.memVT = MVT::getVT(PtrTy->getElementType());
6750     Info.ptrVal = I.getArgOperand(0);
6751     Info.offset = 0;
6752     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6753     Info.vol = true;
6754     Info.readMem = true;
6755     Info.writeMem = false;
6756     return true;
6757   }
6758   case Intrinsic::aarch64_stlxr:
6759   case Intrinsic::aarch64_stxr: {
6760     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6761     Info.opc = ISD::INTRINSIC_W_CHAIN;
6762     Info.memVT = MVT::getVT(PtrTy->getElementType());
6763     Info.ptrVal = I.getArgOperand(1);
6764     Info.offset = 0;
6765     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6766     Info.vol = true;
6767     Info.readMem = false;
6768     Info.writeMem = true;
6769     return true;
6770   }
6771   case Intrinsic::aarch64_ldaxp:
6772   case Intrinsic::aarch64_ldxp: {
6773     Info.opc = ISD::INTRINSIC_W_CHAIN;
6774     Info.memVT = MVT::i128;
6775     Info.ptrVal = I.getArgOperand(0);
6776     Info.offset = 0;
6777     Info.align = 16;
6778     Info.vol = true;
6779     Info.readMem = true;
6780     Info.writeMem = false;
6781     return true;
6782   }
6783   case Intrinsic::aarch64_stlxp:
6784   case Intrinsic::aarch64_stxp: {
6785     Info.opc = ISD::INTRINSIC_W_CHAIN;
6786     Info.memVT = MVT::i128;
6787     Info.ptrVal = I.getArgOperand(2);
6788     Info.offset = 0;
6789     Info.align = 16;
6790     Info.vol = true;
6791     Info.readMem = false;
6792     Info.writeMem = true;
6793     return true;
6794   }
6795   default:
6796     break;
6797   }
6798
6799   return false;
6800 }
6801
6802 // Truncations from 64-bit GPR to 32-bit GPR is free.
6803 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6804   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6805     return false;
6806   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6807   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6808   return NumBits1 > NumBits2;
6809 }
6810 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6811   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6812     return false;
6813   unsigned NumBits1 = VT1.getSizeInBits();
6814   unsigned NumBits2 = VT2.getSizeInBits();
6815   return NumBits1 > NumBits2;
6816 }
6817
6818 /// Check if it is profitable to hoist instruction in then/else to if.
6819 /// Not profitable if I and it's user can form a FMA instruction
6820 /// because we prefer FMSUB/FMADD.
6821 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6822   if (I->getOpcode() != Instruction::FMul)
6823     return true;
6824
6825   if (I->getNumUses() != 1)
6826     return true;
6827
6828   Instruction *User = I->user_back();
6829
6830   if (User &&
6831       !(User->getOpcode() == Instruction::FSub ||
6832         User->getOpcode() == Instruction::FAdd))
6833     return true;
6834
6835   const TargetOptions &Options = getTargetMachine().Options;
6836   const DataLayout &DL = I->getModule()->getDataLayout();
6837   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6838
6839   if (isFMAFasterThanFMulAndFAdd(VT) &&
6840       isOperationLegalOrCustom(ISD::FMA, VT) &&
6841       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6842     return false;
6843
6844   return true;
6845 }
6846
6847 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6848 // 64-bit GPR.
6849 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6850   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6851     return false;
6852   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6853   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6854   return NumBits1 == 32 && NumBits2 == 64;
6855 }
6856 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6857   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6858     return false;
6859   unsigned NumBits1 = VT1.getSizeInBits();
6860   unsigned NumBits2 = VT2.getSizeInBits();
6861   return NumBits1 == 32 && NumBits2 == 64;
6862 }
6863
6864 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6865   EVT VT1 = Val.getValueType();
6866   if (isZExtFree(VT1, VT2)) {
6867     return true;
6868   }
6869
6870   if (Val.getOpcode() != ISD::LOAD)
6871     return false;
6872
6873   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6874   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6875           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6876           VT1.getSizeInBits() <= 32);
6877 }
6878
6879 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6880   if (isa<FPExtInst>(Ext))
6881     return false;
6882
6883   // Vector types are next free.
6884   if (Ext->getType()->isVectorTy())
6885     return false;
6886
6887   for (const Use &U : Ext->uses()) {
6888     // The extension is free if we can fold it with a left shift in an
6889     // addressing mode or an arithmetic operation: add, sub, and cmp.
6890
6891     // Is there a shift?
6892     const Instruction *Instr = cast<Instruction>(U.getUser());
6893
6894     // Is this a constant shift?
6895     switch (Instr->getOpcode()) {
6896     case Instruction::Shl:
6897       if (!isa<ConstantInt>(Instr->getOperand(1)))
6898         return false;
6899       break;
6900     case Instruction::GetElementPtr: {
6901       gep_type_iterator GTI = gep_type_begin(Instr);
6902       auto &DL = Ext->getModule()->getDataLayout();
6903       std::advance(GTI, U.getOperandNo());
6904       Type *IdxTy = *GTI;
6905       // This extension will end up with a shift because of the scaling factor.
6906       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6907       // Get the shift amount based on the scaling factor:
6908       // log2(sizeof(IdxTy)) - log2(8).
6909       uint64_t ShiftAmt =
6910           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6911       // Is the constant foldable in the shift of the addressing mode?
6912       // I.e., shift amount is between 1 and 4 inclusive.
6913       if (ShiftAmt == 0 || ShiftAmt > 4)
6914         return false;
6915       break;
6916     }
6917     case Instruction::Trunc:
6918       // Check if this is a noop.
6919       // trunc(sext ty1 to ty2) to ty1.
6920       if (Instr->getType() == Ext->getOperand(0)->getType())
6921         continue;
6922     // FALL THROUGH.
6923     default:
6924       return false;
6925     }
6926
6927     // At this point we can use the bfm family, so this extension is free
6928     // for that use.
6929   }
6930   return true;
6931 }
6932
6933 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6934                                           unsigned &RequiredAligment) const {
6935   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6936     return false;
6937   // Cyclone supports unaligned accesses.
6938   RequiredAligment = 0;
6939   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6940   return NumBits == 32 || NumBits == 64;
6941 }
6942
6943 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6944                                           unsigned &RequiredAligment) const {
6945   if (!LoadedType.isSimple() ||
6946       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6947     return false;
6948   // Cyclone supports unaligned accesses.
6949   RequiredAligment = 0;
6950   unsigned NumBits = LoadedType.getSizeInBits();
6951   return NumBits == 32 || NumBits == 64;
6952 }
6953
6954 /// \brief Lower an interleaved load into a ldN intrinsic.
6955 ///
6956 /// E.g. Lower an interleaved load (Factor = 2):
6957 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6958 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6959 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6960 ///
6961 ///      Into:
6962 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6963 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6964 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6965 bool AArch64TargetLowering::lowerInterleavedLoad(
6966     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6967     ArrayRef<unsigned> Indices, unsigned Factor) const {
6968   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6969          "Invalid interleave factor");
6970   assert(!Shuffles.empty() && "Empty shufflevector input");
6971   assert(Shuffles.size() == Indices.size() &&
6972          "Unmatched number of shufflevectors and indices");
6973
6974   const DataLayout &DL = LI->getModule()->getDataLayout();
6975
6976   VectorType *VecTy = Shuffles[0]->getType();
6977   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6978
6979   // Skip if we do not have NEON and skip illegal vector types.
6980   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
6981     return false;
6982
6983   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6984   // load integer vectors first and then convert to pointer vectors.
6985   Type *EltTy = VecTy->getVectorElementType();
6986   if (EltTy->isPointerTy())
6987     VecTy =
6988         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6989
6990   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6991   Type *Tys[2] = {VecTy, PtrTy};
6992   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6993                                             Intrinsic::aarch64_neon_ld3,
6994                                             Intrinsic::aarch64_neon_ld4};
6995   Function *LdNFunc =
6996       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6997
6998   IRBuilder<> Builder(LI);
6999   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7000
7001   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7002
7003   // Replace uses of each shufflevector with the corresponding vector loaded
7004   // by ldN.
7005   for (unsigned i = 0; i < Shuffles.size(); i++) {
7006     ShuffleVectorInst *SVI = Shuffles[i];
7007     unsigned Index = Indices[i];
7008
7009     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7010
7011     // Convert the integer vector to pointer vector if the element is pointer.
7012     if (EltTy->isPointerTy())
7013       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7014
7015     SVI->replaceAllUsesWith(SubVec);
7016   }
7017
7018   return true;
7019 }
7020
7021 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7022 ///
7023 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7024 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7025                                    unsigned NumElts) {
7026   SmallVector<Constant *, 16> Mask;
7027   for (unsigned i = 0; i < NumElts; i++)
7028     Mask.push_back(Builder.getInt32(Start + i));
7029
7030   return ConstantVector::get(Mask);
7031 }
7032
7033 /// \brief Lower an interleaved store into a stN intrinsic.
7034 ///
7035 /// E.g. Lower an interleaved store (Factor = 3):
7036 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7037 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7038 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7039 ///
7040 ///      Into:
7041 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7042 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7043 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7044 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7045 ///
7046 /// Note that the new shufflevectors will be removed and we'll only generate one
7047 /// st3 instruction in CodeGen.
7048 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7049                                                   ShuffleVectorInst *SVI,
7050                                                   unsigned Factor) const {
7051   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7052          "Invalid interleave factor");
7053
7054   VectorType *VecTy = SVI->getType();
7055   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7056          "Invalid interleaved store");
7057
7058   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7059   Type *EltTy = VecTy->getVectorElementType();
7060   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7061
7062   const DataLayout &DL = SI->getModule()->getDataLayout();
7063   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7064
7065   // Skip if we do not have NEON and skip illegal vector types.
7066   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7067     return false;
7068
7069   Value *Op0 = SVI->getOperand(0);
7070   Value *Op1 = SVI->getOperand(1);
7071   IRBuilder<> Builder(SI);
7072
7073   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7074   // vectors to integer vectors.
7075   if (EltTy->isPointerTy()) {
7076     Type *IntTy = DL.getIntPtrType(EltTy);
7077     unsigned NumOpElts =
7078         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7079
7080     // Convert to the corresponding integer vector.
7081     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7082     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7083     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7084
7085     SubVecTy = VectorType::get(IntTy, NumSubElts);
7086   }
7087
7088   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7089   Type *Tys[2] = {SubVecTy, PtrTy};
7090   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7091                                              Intrinsic::aarch64_neon_st3,
7092                                              Intrinsic::aarch64_neon_st4};
7093   Function *StNFunc =
7094       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7095
7096   SmallVector<Value *, 5> Ops;
7097
7098   // Split the shufflevector operands into sub vectors for the new stN call.
7099   for (unsigned i = 0; i < Factor; i++)
7100     Ops.push_back(Builder.CreateShuffleVector(
7101         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7102
7103   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7104   Builder.CreateCall(StNFunc, Ops);
7105   return true;
7106 }
7107
7108 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7109                        unsigned AlignCheck) {
7110   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7111           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7112 }
7113
7114 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7115                                                unsigned SrcAlign, bool IsMemset,
7116                                                bool ZeroMemset,
7117                                                bool MemcpyStrSrc,
7118                                                MachineFunction &MF) const {
7119   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7120   // instruction to materialize the v2i64 zero and one store (with restrictive
7121   // addressing mode). Just do two i64 store of zero-registers.
7122   bool Fast;
7123   const Function *F = MF.getFunction();
7124   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7125       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7126       (memOpAlign(SrcAlign, DstAlign, 16) ||
7127        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7128     return MVT::f128;
7129
7130   if (Size >= 8 &&
7131       (memOpAlign(SrcAlign, DstAlign, 8) ||
7132        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7133     return MVT::i64;
7134
7135   if (Size >= 4 &&
7136       (memOpAlign(SrcAlign, DstAlign, 4) ||
7137        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7138     return MVT::i32;
7139
7140   return MVT::Other;
7141 }
7142
7143 // 12-bit optionally shifted immediates are legal for adds.
7144 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7145   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7146     return true;
7147   return false;
7148 }
7149
7150 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7151 // immediates is the same as for an add or a sub.
7152 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7153   if (Immed < 0)
7154     Immed *= -1;
7155   return isLegalAddImmediate(Immed);
7156 }
7157
7158 /// isLegalAddressingMode - Return true if the addressing mode represented
7159 /// by AM is legal for this target, for a load/store of the specified type.
7160 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7161                                                   const AddrMode &AM, Type *Ty,
7162                                                   unsigned AS) const {
7163   // AArch64 has five basic addressing modes:
7164   //  reg
7165   //  reg + 9-bit signed offset
7166   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7167   //  reg1 + reg2
7168   //  reg + SIZE_IN_BYTES * reg
7169
7170   // No global is ever allowed as a base.
7171   if (AM.BaseGV)
7172     return false;
7173
7174   // No reg+reg+imm addressing.
7175   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7176     return false;
7177
7178   // check reg + imm case:
7179   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7180   uint64_t NumBytes = 0;
7181   if (Ty->isSized()) {
7182     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7183     NumBytes = NumBits / 8;
7184     if (!isPowerOf2_64(NumBits))
7185       NumBytes = 0;
7186   }
7187
7188   if (!AM.Scale) {
7189     int64_t Offset = AM.BaseOffs;
7190
7191     // 9-bit signed offset
7192     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7193       return true;
7194
7195     // 12-bit unsigned offset
7196     unsigned shift = Log2_64(NumBytes);
7197     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7198         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7199         (Offset >> shift) << shift == Offset)
7200       return true;
7201     return false;
7202   }
7203
7204   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7205
7206   if (!AM.Scale || AM.Scale == 1 ||
7207       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7208     return true;
7209   return false;
7210 }
7211
7212 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7213                                                 const AddrMode &AM, Type *Ty,
7214                                                 unsigned AS) const {
7215   // Scaling factors are not free at all.
7216   // Operands                     | Rt Latency
7217   // -------------------------------------------
7218   // Rt, [Xn, Xm]                 | 4
7219   // -------------------------------------------
7220   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7221   // Rt, [Xn, Wm, <extend> #imm]  |
7222   if (isLegalAddressingMode(DL, AM, Ty, AS))
7223     // Scale represents reg2 * scale, thus account for 1 if
7224     // it is not equal to 0 or 1.
7225     return AM.Scale != 0 && AM.Scale != 1;
7226   return -1;
7227 }
7228
7229 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7230   VT = VT.getScalarType();
7231
7232   if (!VT.isSimple())
7233     return false;
7234
7235   switch (VT.getSimpleVT().SimpleTy) {
7236   case MVT::f32:
7237   case MVT::f64:
7238     return true;
7239   default:
7240     break;
7241   }
7242
7243   return false;
7244 }
7245
7246 const MCPhysReg *
7247 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7248   // LR is a callee-save register, but we must treat it as clobbered by any call
7249   // site. Hence we include LR in the scratch registers, which are in turn added
7250   // as implicit-defs for stackmaps and patchpoints.
7251   static const MCPhysReg ScratchRegs[] = {
7252     AArch64::X16, AArch64::X17, AArch64::LR, 0
7253   };
7254   return ScratchRegs;
7255 }
7256
7257 bool
7258 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7259   EVT VT = N->getValueType(0);
7260     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7261     // it with shift to let it be lowered to UBFX.
7262   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7263       isa<ConstantSDNode>(N->getOperand(1))) {
7264     uint64_t TruncMask = N->getConstantOperandVal(1);
7265     if (isMask_64(TruncMask) &&
7266       N->getOperand(0).getOpcode() == ISD::SRL &&
7267       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7268       return false;
7269   }
7270   return true;
7271 }
7272
7273 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7274                                                               Type *Ty) const {
7275   assert(Ty->isIntegerTy());
7276
7277   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7278   if (BitSize == 0)
7279     return false;
7280
7281   int64_t Val = Imm.getSExtValue();
7282   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7283     return true;
7284
7285   if ((int64_t)Val < 0)
7286     Val = ~Val;
7287   if (BitSize == 32)
7288     Val &= (1LL << 32) - 1;
7289
7290   unsigned LZ = countLeadingZeros((uint64_t)Val);
7291   unsigned Shift = (63 - LZ) / 16;
7292   // MOVZ is free so return true for one or fewer MOVK.
7293   return Shift < 3;
7294 }
7295
7296 // Generate SUBS and CSEL for integer abs.
7297 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7298   EVT VT = N->getValueType(0);
7299
7300   SDValue N0 = N->getOperand(0);
7301   SDValue N1 = N->getOperand(1);
7302   SDLoc DL(N);
7303
7304   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7305   // and change it to SUB and CSEL.
7306   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7307       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7308       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7309     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7310       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7311         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7312                                   N0.getOperand(0));
7313         // Generate SUBS & CSEL.
7314         SDValue Cmp =
7315             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7316                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7317         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7318                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7319                            SDValue(Cmp.getNode(), 1));
7320       }
7321   return SDValue();
7322 }
7323
7324 // performXorCombine - Attempts to handle integer ABS.
7325 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7326                                  TargetLowering::DAGCombinerInfo &DCI,
7327                                  const AArch64Subtarget *Subtarget) {
7328   if (DCI.isBeforeLegalizeOps())
7329     return SDValue();
7330
7331   return performIntegerAbsCombine(N, DAG);
7332 }
7333
7334 SDValue
7335 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7336                                      SelectionDAG &DAG,
7337                                      std::vector<SDNode *> *Created) const {
7338   // fold (sdiv X, pow2)
7339   EVT VT = N->getValueType(0);
7340   if ((VT != MVT::i32 && VT != MVT::i64) ||
7341       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7342     return SDValue();
7343
7344   SDLoc DL(N);
7345   SDValue N0 = N->getOperand(0);
7346   unsigned Lg2 = Divisor.countTrailingZeros();
7347   SDValue Zero = DAG.getConstant(0, DL, VT);
7348   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7349
7350   // Add (N0 < 0) ? Pow2 - 1 : 0;
7351   SDValue CCVal;
7352   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7353   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7354   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7355
7356   if (Created) {
7357     Created->push_back(Cmp.getNode());
7358     Created->push_back(Add.getNode());
7359     Created->push_back(CSel.getNode());
7360   }
7361
7362   // Divide by pow2.
7363   SDValue SRA =
7364       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7365
7366   // If we're dividing by a positive value, we're done.  Otherwise, we must
7367   // negate the result.
7368   if (Divisor.isNonNegative())
7369     return SRA;
7370
7371   if (Created)
7372     Created->push_back(SRA.getNode());
7373   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7374 }
7375
7376 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7377                                  TargetLowering::DAGCombinerInfo &DCI,
7378                                  const AArch64Subtarget *Subtarget) {
7379   if (DCI.isBeforeLegalizeOps())
7380     return SDValue();
7381
7382   // Multiplication of a power of two plus/minus one can be done more
7383   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7384   // future CPUs have a cheaper MADD instruction, this may need to be
7385   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7386   // 64-bit is 5 cycles, so this is always a win.
7387   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7388     APInt Value = C->getAPIntValue();
7389     EVT VT = N->getValueType(0);
7390     SDLoc DL(N);
7391     if (Value.isNonNegative()) {
7392       // (mul x, 2^N + 1) => (add (shl x, N), x)
7393       APInt VM1 = Value - 1;
7394       if (VM1.isPowerOf2()) {
7395         SDValue ShiftedVal =
7396             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7397                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7398         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7399                            N->getOperand(0));
7400       }
7401       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7402       APInt VP1 = Value + 1;
7403       if (VP1.isPowerOf2()) {
7404         SDValue ShiftedVal =
7405             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7406                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7407         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7408                            N->getOperand(0));
7409       }
7410     } else {
7411       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7412       APInt VNP1 = -Value + 1;
7413       if (VNP1.isPowerOf2()) {
7414         SDValue ShiftedVal =
7415             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7416                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7417         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7418                            ShiftedVal);
7419       }
7420       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7421       APInt VNM1 = -Value - 1;
7422       if (VNM1.isPowerOf2()) {
7423         SDValue ShiftedVal =
7424             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7425                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7426         SDValue Add =
7427             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7428         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7429       }
7430     }
7431   }
7432   return SDValue();
7433 }
7434
7435 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7436                                                          SelectionDAG &DAG) {
7437   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7438   // optimize away operation when it's from a constant.
7439   //
7440   // The general transformation is:
7441   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7442   //       AND(VECTOR_CMP(x,y), constant2)
7443   //    constant2 = UNARYOP(constant)
7444
7445   // Early exit if this isn't a vector operation, the operand of the
7446   // unary operation isn't a bitwise AND, or if the sizes of the operations
7447   // aren't the same.
7448   EVT VT = N->getValueType(0);
7449   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7450       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7451       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7452     return SDValue();
7453
7454   // Now check that the other operand of the AND is a constant. We could
7455   // make the transformation for non-constant splats as well, but it's unclear
7456   // that would be a benefit as it would not eliminate any operations, just
7457   // perform one more step in scalar code before moving to the vector unit.
7458   if (BuildVectorSDNode *BV =
7459           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7460     // Bail out if the vector isn't a constant.
7461     if (!BV->isConstant())
7462       return SDValue();
7463
7464     // Everything checks out. Build up the new and improved node.
7465     SDLoc DL(N);
7466     EVT IntVT = BV->getValueType(0);
7467     // Create a new constant of the appropriate type for the transformed
7468     // DAG.
7469     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7470     // The AND node needs bitcasts to/from an integer vector type around it.
7471     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7472     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7473                                  N->getOperand(0)->getOperand(0), MaskConst);
7474     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7475     return Res;
7476   }
7477
7478   return SDValue();
7479 }
7480
7481 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7482                                      const AArch64Subtarget *Subtarget) {
7483   // First try to optimize away the conversion when it's conditionally from
7484   // a constant. Vectors only.
7485   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7486     return Res;
7487
7488   EVT VT = N->getValueType(0);
7489   if (VT != MVT::f32 && VT != MVT::f64)
7490     return SDValue();
7491
7492   // Only optimize when the source and destination types have the same width.
7493   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7494     return SDValue();
7495
7496   // If the result of an integer load is only used by an integer-to-float
7497   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7498   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7499   SDValue N0 = N->getOperand(0);
7500   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7501       // Do not change the width of a volatile load.
7502       !cast<LoadSDNode>(N0)->isVolatile()) {
7503     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7504     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7505                                LN0->getPointerInfo(), LN0->isVolatile(),
7506                                LN0->isNonTemporal(), LN0->isInvariant(),
7507                                LN0->getAlignment());
7508
7509     // Make sure successors of the original load stay after it by updating them
7510     // to use the new Chain.
7511     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7512
7513     unsigned Opcode =
7514         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7515     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7516   }
7517
7518   return SDValue();
7519 }
7520
7521 /// Fold a floating-point multiply by power of two into floating-point to
7522 /// fixed-point conversion.
7523 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7524                                      const AArch64Subtarget *Subtarget) {
7525   if (!Subtarget->hasNEON())
7526     return SDValue();
7527
7528   SDValue Op = N->getOperand(0);
7529   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7530     return SDValue();
7531
7532   SDValue ConstVec = Op->getOperand(1);
7533   if (!isa<BuildVectorSDNode>(ConstVec))
7534     return SDValue();
7535
7536   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7537   uint32_t FloatBits = FloatTy.getSizeInBits();
7538   if (FloatBits != 32 && FloatBits != 64)
7539     return SDValue();
7540
7541   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7542   uint32_t IntBits = IntTy.getSizeInBits();
7543   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7544     return SDValue();
7545
7546   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7547   if (IntBits > FloatBits)
7548     return SDValue();
7549
7550   BitVector UndefElements;
7551   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7552   int32_t Bits = IntBits == 64 ? 64 : 32;
7553   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7554   if (C == -1 || C == 0 || C > Bits)
7555     return SDValue();
7556
7557   MVT ResTy;
7558   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7559   switch (NumLanes) {
7560   default:
7561     return SDValue();
7562   case 2:
7563     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7564     break;
7565   case 4:
7566     ResTy = MVT::v4i32;
7567     break;
7568   }
7569
7570   SDLoc DL(N);
7571   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7572   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7573                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7574   SDValue FixConv =
7575       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7576                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7577                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7578   // We can handle smaller integers by generating an extra trunc.
7579   if (IntBits < FloatBits)
7580     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7581
7582   return FixConv;
7583 }
7584
7585 /// Fold a floating-point divide by power of two into fixed-point to
7586 /// floating-point conversion.
7587 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7588                                   const AArch64Subtarget *Subtarget) {
7589   if (!Subtarget->hasNEON())
7590     return SDValue();
7591
7592   SDValue Op = N->getOperand(0);
7593   unsigned Opc = Op->getOpcode();
7594   if (!Op.getValueType().isVector() ||
7595       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7596     return SDValue();
7597
7598   SDValue ConstVec = N->getOperand(1);
7599   if (!isa<BuildVectorSDNode>(ConstVec))
7600     return SDValue();
7601
7602   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7603   int32_t IntBits = IntTy.getSizeInBits();
7604   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7605     return SDValue();
7606
7607   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7608   int32_t FloatBits = FloatTy.getSizeInBits();
7609   if (FloatBits != 32 && FloatBits != 64)
7610     return SDValue();
7611
7612   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7613   if (IntBits > FloatBits)
7614     return SDValue();
7615
7616   BitVector UndefElements;
7617   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7618   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7619   if (C == -1 || C == 0 || C > FloatBits)
7620     return SDValue();
7621
7622   MVT ResTy;
7623   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7624   switch (NumLanes) {
7625   default:
7626     return SDValue();
7627   case 2:
7628     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7629     break;
7630   case 4:
7631     ResTy = MVT::v4i32;
7632     break;
7633   }
7634
7635   SDLoc DL(N);
7636   SDValue ConvInput = Op.getOperand(0);
7637   bool IsSigned = Opc == ISD::SINT_TO_FP;
7638   if (IntBits < FloatBits)
7639     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7640                             ResTy, ConvInput);
7641
7642   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7643                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7644   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7645                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7646                      DAG.getConstant(C, DL, MVT::i32));
7647 }
7648
7649 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7650 /// searches for and classifies those shifts.
7651 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7652                          bool &FromHi) {
7653   if (N.getOpcode() == ISD::SHL)
7654     FromHi = false;
7655   else if (N.getOpcode() == ISD::SRL)
7656     FromHi = true;
7657   else
7658     return false;
7659
7660   if (!isa<ConstantSDNode>(N.getOperand(1)))
7661     return false;
7662
7663   ShiftAmount = N->getConstantOperandVal(1);
7664   Src = N->getOperand(0);
7665   return true;
7666 }
7667
7668 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7669 /// registers viewed as a high/low pair. This function looks for the pattern:
7670 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7671 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7672 /// independent.
7673 static SDValue tryCombineToEXTR(SDNode *N,
7674                                 TargetLowering::DAGCombinerInfo &DCI) {
7675   SelectionDAG &DAG = DCI.DAG;
7676   SDLoc DL(N);
7677   EVT VT = N->getValueType(0);
7678
7679   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7680
7681   if (VT != MVT::i32 && VT != MVT::i64)
7682     return SDValue();
7683
7684   SDValue LHS;
7685   uint32_t ShiftLHS = 0;
7686   bool LHSFromHi = 0;
7687   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7688     return SDValue();
7689
7690   SDValue RHS;
7691   uint32_t ShiftRHS = 0;
7692   bool RHSFromHi = 0;
7693   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7694     return SDValue();
7695
7696   // If they're both trying to come from the high part of the register, they're
7697   // not really an EXTR.
7698   if (LHSFromHi == RHSFromHi)
7699     return SDValue();
7700
7701   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7702     return SDValue();
7703
7704   if (LHSFromHi) {
7705     std::swap(LHS, RHS);
7706     std::swap(ShiftLHS, ShiftRHS);
7707   }
7708
7709   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7710                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7711 }
7712
7713 static SDValue tryCombineToBSL(SDNode *N,
7714                                 TargetLowering::DAGCombinerInfo &DCI) {
7715   EVT VT = N->getValueType(0);
7716   SelectionDAG &DAG = DCI.DAG;
7717   SDLoc DL(N);
7718
7719   if (!VT.isVector())
7720     return SDValue();
7721
7722   SDValue N0 = N->getOperand(0);
7723   if (N0.getOpcode() != ISD::AND)
7724     return SDValue();
7725
7726   SDValue N1 = N->getOperand(1);
7727   if (N1.getOpcode() != ISD::AND)
7728     return SDValue();
7729
7730   // We only have to look for constant vectors here since the general, variable
7731   // case can be handled in TableGen.
7732   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7733   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7734   for (int i = 1; i >= 0; --i)
7735     for (int j = 1; j >= 0; --j) {
7736       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7737       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7738       if (!BVN0 || !BVN1)
7739         continue;
7740
7741       bool FoundMatch = true;
7742       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7743         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7744         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7745         if (!CN0 || !CN1 ||
7746             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7747           FoundMatch = false;
7748           break;
7749         }
7750       }
7751
7752       if (FoundMatch)
7753         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7754                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7755     }
7756
7757   return SDValue();
7758 }
7759
7760 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7761                                 const AArch64Subtarget *Subtarget) {
7762   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7763   if (!EnableAArch64ExtrGeneration)
7764     return SDValue();
7765   SelectionDAG &DAG = DCI.DAG;
7766   EVT VT = N->getValueType(0);
7767
7768   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7769     return SDValue();
7770
7771   SDValue Res = tryCombineToEXTR(N, DCI);
7772   if (Res.getNode())
7773     return Res;
7774
7775   Res = tryCombineToBSL(N, DCI);
7776   if (Res.getNode())
7777     return Res;
7778
7779   return SDValue();
7780 }
7781
7782 static SDValue performBitcastCombine(SDNode *N,
7783                                      TargetLowering::DAGCombinerInfo &DCI,
7784                                      SelectionDAG &DAG) {
7785   // Wait 'til after everything is legalized to try this. That way we have
7786   // legal vector types and such.
7787   if (DCI.isBeforeLegalizeOps())
7788     return SDValue();
7789
7790   // Remove extraneous bitcasts around an extract_subvector.
7791   // For example,
7792   //    (v4i16 (bitconvert
7793   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7794   //  becomes
7795   //    (extract_subvector ((v8i16 ...), (i64 4)))
7796
7797   // Only interested in 64-bit vectors as the ultimate result.
7798   EVT VT = N->getValueType(0);
7799   if (!VT.isVector())
7800     return SDValue();
7801   if (VT.getSimpleVT().getSizeInBits() != 64)
7802     return SDValue();
7803   // Is the operand an extract_subvector starting at the beginning or halfway
7804   // point of the vector? A low half may also come through as an
7805   // EXTRACT_SUBREG, so look for that, too.
7806   SDValue Op0 = N->getOperand(0);
7807   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7808       !(Op0->isMachineOpcode() &&
7809         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7810     return SDValue();
7811   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7812   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7813     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7814       return SDValue();
7815   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7816     if (idx != AArch64::dsub)
7817       return SDValue();
7818     // The dsub reference is equivalent to a lane zero subvector reference.
7819     idx = 0;
7820   }
7821   // Look through the bitcast of the input to the extract.
7822   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7823     return SDValue();
7824   SDValue Source = Op0->getOperand(0)->getOperand(0);
7825   // If the source type has twice the number of elements as our destination
7826   // type, we know this is an extract of the high or low half of the vector.
7827   EVT SVT = Source->getValueType(0);
7828   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7829     return SDValue();
7830
7831   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7832
7833   // Create the simplified form to just extract the low or high half of the
7834   // vector directly rather than bothering with the bitcasts.
7835   SDLoc dl(N);
7836   unsigned NumElements = VT.getVectorNumElements();
7837   if (idx) {
7838     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7839     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7840   } else {
7841     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7842     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7843                                       Source, SubReg),
7844                    0);
7845   }
7846 }
7847
7848 static SDValue performConcatVectorsCombine(SDNode *N,
7849                                            TargetLowering::DAGCombinerInfo &DCI,
7850                                            SelectionDAG &DAG) {
7851   SDLoc dl(N);
7852   EVT VT = N->getValueType(0);
7853   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7854
7855   // Optimize concat_vectors of truncated vectors, where the intermediate
7856   // type is illegal, to avoid said illegality,  e.g.,
7857   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7858   //                          (v2i16 (truncate (v2i64)))))
7859   // ->
7860   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7861   //                                    (v4i32 (bitcast (v2i64))),
7862   //                                    <0, 2, 4, 6>)))
7863   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7864   // on both input and result type, so we might generate worse code.
7865   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7866   if (N->getNumOperands() == 2 &&
7867       N0->getOpcode() == ISD::TRUNCATE &&
7868       N1->getOpcode() == ISD::TRUNCATE) {
7869     SDValue N00 = N0->getOperand(0);
7870     SDValue N10 = N1->getOperand(0);
7871     EVT N00VT = N00.getValueType();
7872
7873     if (N00VT == N10.getValueType() &&
7874         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7875         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7876       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7877       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7878       for (size_t i = 0; i < Mask.size(); ++i)
7879         Mask[i] = i * 2;
7880       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7881                          DAG.getVectorShuffle(
7882                              MidVT, dl,
7883                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7884                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7885     }
7886   }
7887
7888   // Wait 'til after everything is legalized to try this. That way we have
7889   // legal vector types and such.
7890   if (DCI.isBeforeLegalizeOps())
7891     return SDValue();
7892
7893   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7894   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7895   // canonicalise to that.
7896   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7897     assert(VT.getVectorElementType().getSizeInBits() == 64);
7898     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7899                        DAG.getConstant(0, dl, MVT::i64));
7900   }
7901
7902   // Canonicalise concat_vectors so that the right-hand vector has as few
7903   // bit-casts as possible before its real operation. The primary matching
7904   // destination for these operations will be the narrowing "2" instructions,
7905   // which depend on the operation being performed on this right-hand vector.
7906   // For example,
7907   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7908   // becomes
7909   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7910
7911   if (N1->getOpcode() != ISD::BITCAST)
7912     return SDValue();
7913   SDValue RHS = N1->getOperand(0);
7914   MVT RHSTy = RHS.getValueType().getSimpleVT();
7915   // If the RHS is not a vector, this is not the pattern we're looking for.
7916   if (!RHSTy.isVector())
7917     return SDValue();
7918
7919   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7920
7921   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7922                                   RHSTy.getVectorNumElements() * 2);
7923   return DAG.getNode(ISD::BITCAST, dl, VT,
7924                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7925                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7926                                  RHS));
7927 }
7928
7929 static SDValue tryCombineFixedPointConvert(SDNode *N,
7930                                            TargetLowering::DAGCombinerInfo &DCI,
7931                                            SelectionDAG &DAG) {
7932   // Wait 'til after everything is legalized to try this. That way we have
7933   // legal vector types and such.
7934   if (DCI.isBeforeLegalizeOps())
7935     return SDValue();
7936   // Transform a scalar conversion of a value from a lane extract into a
7937   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7938   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7939   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7940   //
7941   // The second form interacts better with instruction selection and the
7942   // register allocator to avoid cross-class register copies that aren't
7943   // coalescable due to a lane reference.
7944
7945   // Check the operand and see if it originates from a lane extract.
7946   SDValue Op1 = N->getOperand(1);
7947   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7948     // Yep, no additional predication needed. Perform the transform.
7949     SDValue IID = N->getOperand(0);
7950     SDValue Shift = N->getOperand(2);
7951     SDValue Vec = Op1.getOperand(0);
7952     SDValue Lane = Op1.getOperand(1);
7953     EVT ResTy = N->getValueType(0);
7954     EVT VecResTy;
7955     SDLoc DL(N);
7956
7957     // The vector width should be 128 bits by the time we get here, even
7958     // if it started as 64 bits (the extract_vector handling will have
7959     // done so).
7960     assert(Vec.getValueType().getSizeInBits() == 128 &&
7961            "unexpected vector size on extract_vector_elt!");
7962     if (Vec.getValueType() == MVT::v4i32)
7963       VecResTy = MVT::v4f32;
7964     else if (Vec.getValueType() == MVT::v2i64)
7965       VecResTy = MVT::v2f64;
7966     else
7967       llvm_unreachable("unexpected vector type!");
7968
7969     SDValue Convert =
7970         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7971     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7972   }
7973   return SDValue();
7974 }
7975
7976 // AArch64 high-vector "long" operations are formed by performing the non-high
7977 // version on an extract_subvector of each operand which gets the high half:
7978 //
7979 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7980 //
7981 // However, there are cases which don't have an extract_high explicitly, but
7982 // have another operation that can be made compatible with one for free. For
7983 // example:
7984 //
7985 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7986 //
7987 // This routine does the actual conversion of such DUPs, once outer routines
7988 // have determined that everything else is in order.
7989 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7990 // similarly here.
7991 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7992   switch (N.getOpcode()) {
7993   case AArch64ISD::DUP:
7994   case AArch64ISD::DUPLANE8:
7995   case AArch64ISD::DUPLANE16:
7996   case AArch64ISD::DUPLANE32:
7997   case AArch64ISD::DUPLANE64:
7998   case AArch64ISD::MOVI:
7999   case AArch64ISD::MOVIshift:
8000   case AArch64ISD::MOVIedit:
8001   case AArch64ISD::MOVImsl:
8002   case AArch64ISD::MVNIshift:
8003   case AArch64ISD::MVNImsl:
8004     break;
8005   default:
8006     // FMOV could be supported, but isn't very useful, as it would only occur
8007     // if you passed a bitcast' floating point immediate to an eligible long
8008     // integer op (addl, smull, ...).
8009     return SDValue();
8010   }
8011
8012   MVT NarrowTy = N.getSimpleValueType();
8013   if (!NarrowTy.is64BitVector())
8014     return SDValue();
8015
8016   MVT ElementTy = NarrowTy.getVectorElementType();
8017   unsigned NumElems = NarrowTy.getVectorNumElements();
8018   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8019
8020   SDLoc dl(N);
8021   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8022                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8023                      DAG.getConstant(NumElems, dl, MVT::i64));
8024 }
8025
8026 static bool isEssentiallyExtractSubvector(SDValue N) {
8027   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8028     return true;
8029
8030   return N.getOpcode() == ISD::BITCAST &&
8031          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8032 }
8033
8034 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8035 struct GenericSetCCInfo {
8036   const SDValue *Opnd0;
8037   const SDValue *Opnd1;
8038   ISD::CondCode CC;
8039 };
8040
8041 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8042 struct AArch64SetCCInfo {
8043   const SDValue *Cmp;
8044   AArch64CC::CondCode CC;
8045 };
8046
8047 /// \brief Helper structure to keep track of SetCC information.
8048 union SetCCInfo {
8049   GenericSetCCInfo Generic;
8050   AArch64SetCCInfo AArch64;
8051 };
8052
8053 /// \brief Helper structure to be able to read SetCC information.  If set to
8054 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8055 /// GenericSetCCInfo.
8056 struct SetCCInfoAndKind {
8057   SetCCInfo Info;
8058   bool IsAArch64;
8059 };
8060
8061 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8062 /// an
8063 /// AArch64 lowered one.
8064 /// \p SetCCInfo is filled accordingly.
8065 /// \post SetCCInfo is meanginfull only when this function returns true.
8066 /// \return True when Op is a kind of SET_CC operation.
8067 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8068   // If this is a setcc, this is straight forward.
8069   if (Op.getOpcode() == ISD::SETCC) {
8070     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8071     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8072     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8073     SetCCInfo.IsAArch64 = false;
8074     return true;
8075   }
8076   // Otherwise, check if this is a matching csel instruction.
8077   // In other words:
8078   // - csel 1, 0, cc
8079   // - csel 0, 1, !cc
8080   if (Op.getOpcode() != AArch64ISD::CSEL)
8081     return false;
8082   // Set the information about the operands.
8083   // TODO: we want the operands of the Cmp not the csel
8084   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8085   SetCCInfo.IsAArch64 = true;
8086   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8087       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8088
8089   // Check that the operands matches the constraints:
8090   // (1) Both operands must be constants.
8091   // (2) One must be 1 and the other must be 0.
8092   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8093   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8094
8095   // Check (1).
8096   if (!TValue || !FValue)
8097     return false;
8098
8099   // Check (2).
8100   if (!TValue->isOne()) {
8101     // Update the comparison when we are interested in !cc.
8102     std::swap(TValue, FValue);
8103     SetCCInfo.Info.AArch64.CC =
8104         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8105   }
8106   return TValue->isOne() && FValue->isNullValue();
8107 }
8108
8109 // Returns true if Op is setcc or zext of setcc.
8110 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8111   if (isSetCC(Op, Info))
8112     return true;
8113   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8114     isSetCC(Op->getOperand(0), Info));
8115 }
8116
8117 // The folding we want to perform is:
8118 // (add x, [zext] (setcc cc ...) )
8119 //   -->
8120 // (csel x, (add x, 1), !cc ...)
8121 //
8122 // The latter will get matched to a CSINC instruction.
8123 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8124   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8125   SDValue LHS = Op->getOperand(0);
8126   SDValue RHS = Op->getOperand(1);
8127   SetCCInfoAndKind InfoAndKind;
8128
8129   // If neither operand is a SET_CC, give up.
8130   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8131     std::swap(LHS, RHS);
8132     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8133       return SDValue();
8134   }
8135
8136   // FIXME: This could be generatized to work for FP comparisons.
8137   EVT CmpVT = InfoAndKind.IsAArch64
8138                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8139                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8140   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8141     return SDValue();
8142
8143   SDValue CCVal;
8144   SDValue Cmp;
8145   SDLoc dl(Op);
8146   if (InfoAndKind.IsAArch64) {
8147     CCVal = DAG.getConstant(
8148         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8149         MVT::i32);
8150     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8151   } else
8152     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8153                       *InfoAndKind.Info.Generic.Opnd1,
8154                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8155                       CCVal, DAG, dl);
8156
8157   EVT VT = Op->getValueType(0);
8158   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8159   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8160 }
8161
8162 // The basic add/sub long vector instructions have variants with "2" on the end
8163 // which act on the high-half of their inputs. They are normally matched by
8164 // patterns like:
8165 //
8166 // (add (zeroext (extract_high LHS)),
8167 //      (zeroext (extract_high RHS)))
8168 // -> uaddl2 vD, vN, vM
8169 //
8170 // However, if one of the extracts is something like a duplicate, this
8171 // instruction can still be used profitably. This function puts the DAG into a
8172 // more appropriate form for those patterns to trigger.
8173 static SDValue performAddSubLongCombine(SDNode *N,
8174                                         TargetLowering::DAGCombinerInfo &DCI,
8175                                         SelectionDAG &DAG) {
8176   if (DCI.isBeforeLegalizeOps())
8177     return SDValue();
8178
8179   MVT VT = N->getSimpleValueType(0);
8180   if (!VT.is128BitVector()) {
8181     if (N->getOpcode() == ISD::ADD)
8182       return performSetccAddFolding(N, DAG);
8183     return SDValue();
8184   }
8185
8186   // Make sure both branches are extended in the same way.
8187   SDValue LHS = N->getOperand(0);
8188   SDValue RHS = N->getOperand(1);
8189   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8190        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8191       LHS.getOpcode() != RHS.getOpcode())
8192     return SDValue();
8193
8194   unsigned ExtType = LHS.getOpcode();
8195
8196   // It's not worth doing if at least one of the inputs isn't already an
8197   // extract, but we don't know which it'll be so we have to try both.
8198   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8199     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8200     if (!RHS.getNode())
8201       return SDValue();
8202
8203     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8204   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8205     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8206     if (!LHS.getNode())
8207       return SDValue();
8208
8209     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8210   }
8211
8212   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8213 }
8214
8215 // Massage DAGs which we can use the high-half "long" operations on into
8216 // something isel will recognize better. E.g.
8217 //
8218 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8219 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8220 //                     (extract_high (v2i64 (dup128 scalar)))))
8221 //
8222 static SDValue tryCombineLongOpWithDup(SDNode *N,
8223                                        TargetLowering::DAGCombinerInfo &DCI,
8224                                        SelectionDAG &DAG) {
8225   if (DCI.isBeforeLegalizeOps())
8226     return SDValue();
8227
8228   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8229   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8230   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8231   assert(LHS.getValueType().is64BitVector() &&
8232          RHS.getValueType().is64BitVector() &&
8233          "unexpected shape for long operation");
8234
8235   // Either node could be a DUP, but it's not worth doing both of them (you'd
8236   // just as well use the non-high version) so look for a corresponding extract
8237   // operation on the other "wing".
8238   if (isEssentiallyExtractSubvector(LHS)) {
8239     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8240     if (!RHS.getNode())
8241       return SDValue();
8242   } else if (isEssentiallyExtractSubvector(RHS)) {
8243     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8244     if (!LHS.getNode())
8245       return SDValue();
8246   }
8247
8248   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8249   if (IsIntrinsic)
8250     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8251                        N->getOperand(0), LHS, RHS);
8252   else
8253     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8254                        LHS, RHS);
8255 }
8256
8257 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8258   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8259   unsigned ElemBits = ElemTy.getSizeInBits();
8260
8261   int64_t ShiftAmount;
8262   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8263     APInt SplatValue, SplatUndef;
8264     unsigned SplatBitSize;
8265     bool HasAnyUndefs;
8266     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8267                               HasAnyUndefs, ElemBits) ||
8268         SplatBitSize != ElemBits)
8269       return SDValue();
8270
8271     ShiftAmount = SplatValue.getSExtValue();
8272   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8273     ShiftAmount = CVN->getSExtValue();
8274   } else
8275     return SDValue();
8276
8277   unsigned Opcode;
8278   bool IsRightShift;
8279   switch (IID) {
8280   default:
8281     llvm_unreachable("Unknown shift intrinsic");
8282   case Intrinsic::aarch64_neon_sqshl:
8283     Opcode = AArch64ISD::SQSHL_I;
8284     IsRightShift = false;
8285     break;
8286   case Intrinsic::aarch64_neon_uqshl:
8287     Opcode = AArch64ISD::UQSHL_I;
8288     IsRightShift = false;
8289     break;
8290   case Intrinsic::aarch64_neon_srshl:
8291     Opcode = AArch64ISD::SRSHR_I;
8292     IsRightShift = true;
8293     break;
8294   case Intrinsic::aarch64_neon_urshl:
8295     Opcode = AArch64ISD::URSHR_I;
8296     IsRightShift = true;
8297     break;
8298   case Intrinsic::aarch64_neon_sqshlu:
8299     Opcode = AArch64ISD::SQSHLU_I;
8300     IsRightShift = false;
8301     break;
8302   }
8303
8304   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8305     SDLoc dl(N);
8306     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8307                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8308   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8309     SDLoc dl(N);
8310     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8311                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8312   }
8313
8314   return SDValue();
8315 }
8316
8317 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8318 // the intrinsics must be legal and take an i32, this means there's almost
8319 // certainly going to be a zext in the DAG which we can eliminate.
8320 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8321   SDValue AndN = N->getOperand(2);
8322   if (AndN.getOpcode() != ISD::AND)
8323     return SDValue();
8324
8325   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8326   if (!CMask || CMask->getZExtValue() != Mask)
8327     return SDValue();
8328
8329   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8330                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8331 }
8332
8333 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8334                                            SelectionDAG &DAG) {
8335   SDLoc dl(N);
8336   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8337                      DAG.getNode(Opc, dl,
8338                                  N->getOperand(1).getSimpleValueType(),
8339                                  N->getOperand(1)),
8340                      DAG.getConstant(0, dl, MVT::i64));
8341 }
8342
8343 static SDValue performIntrinsicCombine(SDNode *N,
8344                                        TargetLowering::DAGCombinerInfo &DCI,
8345                                        const AArch64Subtarget *Subtarget) {
8346   SelectionDAG &DAG = DCI.DAG;
8347   unsigned IID = getIntrinsicID(N);
8348   switch (IID) {
8349   default:
8350     break;
8351   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8352   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8353     return tryCombineFixedPointConvert(N, DCI, DAG);
8354   case Intrinsic::aarch64_neon_saddv:
8355     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8356   case Intrinsic::aarch64_neon_uaddv:
8357     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8358   case Intrinsic::aarch64_neon_sminv:
8359     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8360   case Intrinsic::aarch64_neon_uminv:
8361     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8362   case Intrinsic::aarch64_neon_smaxv:
8363     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8364   case Intrinsic::aarch64_neon_umaxv:
8365     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8366   case Intrinsic::aarch64_neon_fmax:
8367     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8368                        N->getOperand(1), N->getOperand(2));
8369   case Intrinsic::aarch64_neon_fmin:
8370     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8371                        N->getOperand(1), N->getOperand(2));
8372   case Intrinsic::aarch64_neon_sabd:
8373     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8374                        N->getOperand(1), N->getOperand(2));
8375   case Intrinsic::aarch64_neon_uabd:
8376     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8377                        N->getOperand(1), N->getOperand(2));
8378   case Intrinsic::aarch64_neon_fmaxnm:
8379     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8380                        N->getOperand(1), N->getOperand(2));
8381   case Intrinsic::aarch64_neon_fminnm:
8382     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8383                        N->getOperand(1), N->getOperand(2));
8384   case Intrinsic::aarch64_neon_smull:
8385   case Intrinsic::aarch64_neon_umull:
8386   case Intrinsic::aarch64_neon_pmull:
8387   case Intrinsic::aarch64_neon_sqdmull:
8388     return tryCombineLongOpWithDup(N, DCI, DAG);
8389   case Intrinsic::aarch64_neon_sqshl:
8390   case Intrinsic::aarch64_neon_uqshl:
8391   case Intrinsic::aarch64_neon_sqshlu:
8392   case Intrinsic::aarch64_neon_srshl:
8393   case Intrinsic::aarch64_neon_urshl:
8394     return tryCombineShiftImm(IID, N, DAG);
8395   case Intrinsic::aarch64_crc32b:
8396   case Intrinsic::aarch64_crc32cb:
8397     return tryCombineCRC32(0xff, N, DAG);
8398   case Intrinsic::aarch64_crc32h:
8399   case Intrinsic::aarch64_crc32ch:
8400     return tryCombineCRC32(0xffff, N, DAG);
8401   }
8402   return SDValue();
8403 }
8404
8405 static SDValue performExtendCombine(SDNode *N,
8406                                     TargetLowering::DAGCombinerInfo &DCI,
8407                                     SelectionDAG &DAG) {
8408   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8409   // we can convert that DUP into another extract_high (of a bigger DUP), which
8410   // helps the backend to decide that an sabdl2 would be useful, saving a real
8411   // extract_high operation.
8412   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8413       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8414        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8415     SDNode *ABDNode = N->getOperand(0).getNode();
8416     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8417     if (!NewABD.getNode())
8418       return SDValue();
8419
8420     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8421                        NewABD);
8422   }
8423
8424   // This is effectively a custom type legalization for AArch64.
8425   //
8426   // Type legalization will split an extend of a small, legal, type to a larger
8427   // illegal type by first splitting the destination type, often creating
8428   // illegal source types, which then get legalized in isel-confusing ways,
8429   // leading to really terrible codegen. E.g.,
8430   //   %result = v8i32 sext v8i8 %value
8431   // becomes
8432   //   %losrc = extract_subreg %value, ...
8433   //   %hisrc = extract_subreg %value, ...
8434   //   %lo = v4i32 sext v4i8 %losrc
8435   //   %hi = v4i32 sext v4i8 %hisrc
8436   // Things go rapidly downhill from there.
8437   //
8438   // For AArch64, the [sz]ext vector instructions can only go up one element
8439   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8440   // take two instructions.
8441   //
8442   // This implies that the most efficient way to do the extend from v8i8
8443   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8444   // the normal splitting to happen for the v8i16->v8i32.
8445
8446   // This is pre-legalization to catch some cases where the default
8447   // type legalization will create ill-tempered code.
8448   if (!DCI.isBeforeLegalizeOps())
8449     return SDValue();
8450
8451   // We're only interested in cleaning things up for non-legal vector types
8452   // here. If both the source and destination are legal, things will just
8453   // work naturally without any fiddling.
8454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8455   EVT ResVT = N->getValueType(0);
8456   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8457     return SDValue();
8458   // If the vector type isn't a simple VT, it's beyond the scope of what
8459   // we're  worried about here. Let legalization do its thing and hope for
8460   // the best.
8461   SDValue Src = N->getOperand(0);
8462   EVT SrcVT = Src->getValueType(0);
8463   if (!ResVT.isSimple() || !SrcVT.isSimple())
8464     return SDValue();
8465
8466   // If the source VT is a 64-bit vector, we can play games and get the
8467   // better results we want.
8468   if (SrcVT.getSizeInBits() != 64)
8469     return SDValue();
8470
8471   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8472   unsigned ElementCount = SrcVT.getVectorNumElements();
8473   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8474   SDLoc DL(N);
8475   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8476
8477   // Now split the rest of the operation into two halves, each with a 64
8478   // bit source.
8479   EVT LoVT, HiVT;
8480   SDValue Lo, Hi;
8481   unsigned NumElements = ResVT.getVectorNumElements();
8482   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8483   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8484                                  ResVT.getVectorElementType(), NumElements / 2);
8485
8486   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8487                                LoVT.getVectorNumElements());
8488   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8489                    DAG.getConstant(0, DL, MVT::i64));
8490   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8491                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8492   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8493   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8494
8495   // Now combine the parts back together so we still have a single result
8496   // like the combiner expects.
8497   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8498 }
8499
8500 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8501 /// value. The load store optimizer pass will merge them to store pair stores.
8502 /// This has better performance than a splat of the scalar followed by a split
8503 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8504 /// followed by an ext.b and two stores.
8505 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8506   SDValue StVal = St->getValue();
8507   EVT VT = StVal.getValueType();
8508
8509   // Don't replace floating point stores, they possibly won't be transformed to
8510   // stp because of the store pair suppress pass.
8511   if (VT.isFloatingPoint())
8512     return SDValue();
8513
8514   // Check for insert vector elements.
8515   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8516     return SDValue();
8517
8518   // We can express a splat as store pair(s) for 2 or 4 elements.
8519   unsigned NumVecElts = VT.getVectorNumElements();
8520   if (NumVecElts != 4 && NumVecElts != 2)
8521     return SDValue();
8522   SDValue SplatVal = StVal.getOperand(1);
8523   unsigned RemainInsertElts = NumVecElts - 1;
8524
8525   // Check that this is a splat.
8526   while (--RemainInsertElts) {
8527     SDValue NextInsertElt = StVal.getOperand(0);
8528     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8529       return SDValue();
8530     if (NextInsertElt.getOperand(1) != SplatVal)
8531       return SDValue();
8532     StVal = NextInsertElt;
8533   }
8534   unsigned OrigAlignment = St->getAlignment();
8535   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8536   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8537
8538   // Create scalar stores. This is at least as good as the code sequence for a
8539   // split unaligned store which is a dup.s, ext.b, and two stores.
8540   // Most of the time the three stores should be replaced by store pair
8541   // instructions (stp).
8542   SDLoc DL(St);
8543   SDValue BasePtr = St->getBasePtr();
8544   SDValue NewST1 =
8545       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8546                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8547
8548   unsigned Offset = EltOffset;
8549   while (--NumVecElts) {
8550     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8551                                     DAG.getConstant(Offset, DL, MVT::i64));
8552     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8553                           St->getPointerInfo(), St->isVolatile(),
8554                           St->isNonTemporal(), Alignment);
8555     Offset += EltOffset;
8556   }
8557   return NewST1;
8558 }
8559
8560 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8561                               SelectionDAG &DAG,
8562                               const AArch64Subtarget *Subtarget) {
8563   if (!DCI.isBeforeLegalize())
8564     return SDValue();
8565
8566   StoreSDNode *S = cast<StoreSDNode>(N);
8567   if (S->isVolatile())
8568     return SDValue();
8569
8570   // FIXME: The logic for deciding if an unaligned store should be split should
8571   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8572   // a call to that function here.
8573
8574   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8575   // page boundaries. We want to split such stores.
8576   if (!Subtarget->isCyclone())
8577     return SDValue();
8578
8579   // Don't split at -Oz.
8580   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8581     return SDValue();
8582
8583   SDValue StVal = S->getValue();
8584   EVT VT = StVal.getValueType();
8585
8586   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8587   // those up regresses performance on micro-benchmarks and olden/bh.
8588   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8589     return SDValue();
8590
8591   // Split unaligned 16B stores. They are terrible for performance.
8592   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8593   // extensions can use this to mark that it does not want splitting to happen
8594   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8595   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8596   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8597       S->getAlignment() <= 2)
8598     return SDValue();
8599
8600   // If we get a splat of a scalar convert this vector store to a store of
8601   // scalars. They will be merged into store pairs thereby removing two
8602   // instructions.
8603   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8604     return ReplacedSplat;
8605
8606   SDLoc DL(S);
8607   unsigned NumElts = VT.getVectorNumElements() / 2;
8608   // Split VT into two.
8609   EVT HalfVT =
8610       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8611   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8612                                    DAG.getConstant(0, DL, MVT::i64));
8613   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8614                                    DAG.getConstant(NumElts, DL, MVT::i64));
8615   SDValue BasePtr = S->getBasePtr();
8616   SDValue NewST1 =
8617       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8618                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8619   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8620                                   DAG.getConstant(8, DL, MVT::i64));
8621   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8622                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8623                       S->getAlignment());
8624 }
8625
8626 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8627 /// post-increment LD1R.
8628 static SDValue performPostLD1Combine(SDNode *N,
8629                                      TargetLowering::DAGCombinerInfo &DCI,
8630                                      bool IsLaneOp) {
8631   if (DCI.isBeforeLegalizeOps())
8632     return SDValue();
8633
8634   SelectionDAG &DAG = DCI.DAG;
8635   EVT VT = N->getValueType(0);
8636
8637   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8638   SDNode *LD = N->getOperand(LoadIdx).getNode();
8639   // If it is not LOAD, can not do such combine.
8640   if (LD->getOpcode() != ISD::LOAD)
8641     return SDValue();
8642
8643   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8644   EVT MemVT = LoadSDN->getMemoryVT();
8645   // Check if memory operand is the same type as the vector element.
8646   if (MemVT != VT.getVectorElementType())
8647     return SDValue();
8648
8649   // Check if there are other uses. If so, do not combine as it will introduce
8650   // an extra load.
8651   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8652        ++UI) {
8653     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8654       continue;
8655     if (*UI != N)
8656       return SDValue();
8657   }
8658
8659   SDValue Addr = LD->getOperand(1);
8660   SDValue Vector = N->getOperand(0);
8661   // Search for a use of the address operand that is an increment.
8662   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8663        Addr.getNode()->use_end(); UI != UE; ++UI) {
8664     SDNode *User = *UI;
8665     if (User->getOpcode() != ISD::ADD
8666         || UI.getUse().getResNo() != Addr.getResNo())
8667       continue;
8668
8669     // Check that the add is independent of the load.  Otherwise, folding it
8670     // would create a cycle.
8671     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8672       continue;
8673     // Also check that add is not used in the vector operand.  This would also
8674     // create a cycle.
8675     if (User->isPredecessorOf(Vector.getNode()))
8676       continue;
8677
8678     // If the increment is a constant, it must match the memory ref size.
8679     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8680     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8681       uint32_t IncVal = CInc->getZExtValue();
8682       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8683       if (IncVal != NumBytes)
8684         continue;
8685       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8686     }
8687
8688     // Finally, check that the vector doesn't depend on the load.
8689     // Again, this would create a cycle.
8690     // The load depending on the vector is fine, as that's the case for the
8691     // LD1*post we'll eventually generate anyway.
8692     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8693       continue;
8694
8695     SmallVector<SDValue, 8> Ops;
8696     Ops.push_back(LD->getOperand(0));  // Chain
8697     if (IsLaneOp) {
8698       Ops.push_back(Vector);           // The vector to be inserted
8699       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8700     }
8701     Ops.push_back(Addr);
8702     Ops.push_back(Inc);
8703
8704     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8705     SDVTList SDTys = DAG.getVTList(Tys);
8706     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8707     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8708                                            MemVT,
8709                                            LoadSDN->getMemOperand());
8710
8711     // Update the uses.
8712     SmallVector<SDValue, 2> NewResults;
8713     NewResults.push_back(SDValue(LD, 0));             // The result of load
8714     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8715     DCI.CombineTo(LD, NewResults);
8716     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8717     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8718
8719     break;
8720   }
8721   return SDValue();
8722 }
8723
8724 /// Simplify \Addr given that the top byte of it is ignored by HW during
8725 /// address translation.
8726 static bool performTBISimplification(SDValue Addr,
8727                                      TargetLowering::DAGCombinerInfo &DCI,
8728                                      SelectionDAG &DAG) {
8729   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8730   APInt KnownZero, KnownOne;
8731   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8732                                         DCI.isBeforeLegalizeOps());
8733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8734   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8735     DCI.CommitTargetLoweringOpt(TLO);
8736     return true;
8737   }
8738   return false;
8739 }
8740
8741 static SDValue performSTORECombine(SDNode *N,
8742                                    TargetLowering::DAGCombinerInfo &DCI,
8743                                    SelectionDAG &DAG,
8744                                    const AArch64Subtarget *Subtarget) {
8745   SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8746   if (Split.getNode())
8747     return Split;
8748
8749   if (Subtarget->supportsAddressTopByteIgnored() &&
8750       performTBISimplification(N->getOperand(2), DCI, DAG))
8751     return SDValue(N, 0);
8752
8753   return SDValue();
8754 }
8755
8756   /// This function handles the log2-shuffle pattern produced by the
8757 /// LoopVectorizer for the across vector reduction. It consists of
8758 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8759 /// are reduced, where s is an induction variable from 0 to
8760 /// log2(NumVectorElements).
8761 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8762                                                      unsigned Op,
8763                                                      SelectionDAG &DAG) {
8764   EVT VTy = OpV->getOperand(0).getValueType();
8765   if (!VTy.isVector())
8766     return SDValue();
8767
8768   int NumVecElts = VTy.getVectorNumElements();
8769   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8770     if (NumVecElts != 4)
8771       return SDValue();
8772   } else {
8773     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8774       return SDValue();
8775   }
8776
8777   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8778   SDValue PreOp = OpV;
8779   // Iterate over each step of the across vector reduction.
8780   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8781     SDValue CurOp = PreOp.getOperand(0);
8782     SDValue Shuffle = PreOp.getOperand(1);
8783     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8784       // Try to swap the 1st and 2nd operand as add and min/max instructions
8785       // are commutative.
8786       CurOp = PreOp.getOperand(1);
8787       Shuffle = PreOp.getOperand(0);
8788       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8789         return SDValue();
8790     }
8791
8792     // Check if the input vector is fed by the operator we want to handle,
8793     // except the last step; the very first input vector is not necessarily
8794     // the same operator we are handling.
8795     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8796       return SDValue();
8797
8798     // Check if it forms one step of the across vector reduction.
8799     // E.g.,
8800     //   %cur = add %1, %0
8801     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8802     //   %pre = add %cur, %shuffle
8803     if (Shuffle.getOperand(0) != CurOp)
8804       return SDValue();
8805
8806     int NumMaskElts = 1 << CurStep;
8807     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8808     // Check mask values in each step.
8809     // We expect the shuffle mask in each step follows a specific pattern
8810     // denoted here by the <M, U> form, where M is a sequence of integers
8811     // starting from NumMaskElts, increasing by 1, and the number integers
8812     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8813     // of undef in U should be NumVecElts - NumMaskElts.
8814     // E.g., for <8 x i16>, mask values in each step should be :
8815     //   step 0 : <1,u,u,u,u,u,u,u>
8816     //   step 1 : <2,3,u,u,u,u,u,u>
8817     //   step 2 : <4,5,6,7,u,u,u,u>
8818     for (int i = 0; i < NumVecElts; ++i)
8819       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8820           (i >= NumMaskElts && !(Mask[i] < 0)))
8821         return SDValue();
8822
8823     PreOp = CurOp;
8824   }
8825   unsigned Opcode;
8826   bool IsIntrinsic = false;
8827
8828   switch (Op) {
8829   default:
8830     llvm_unreachable("Unexpected operator for across vector reduction");
8831   case ISD::ADD:
8832     Opcode = AArch64ISD::UADDV;
8833     break;
8834   case ISD::SMAX:
8835     Opcode = AArch64ISD::SMAXV;
8836     break;
8837   case ISD::UMAX:
8838     Opcode = AArch64ISD::UMAXV;
8839     break;
8840   case ISD::SMIN:
8841     Opcode = AArch64ISD::SMINV;
8842     break;
8843   case ISD::UMIN:
8844     Opcode = AArch64ISD::UMINV;
8845     break;
8846   case ISD::FMAXNUM:
8847     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8848     IsIntrinsic = true;
8849     break;
8850   case ISD::FMINNUM:
8851     Opcode = Intrinsic::aarch64_neon_fminnmv;
8852     IsIntrinsic = true;
8853     break;
8854   }
8855   SDLoc DL(N);
8856
8857   return IsIntrinsic
8858              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8859                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8860              : DAG.getNode(
8861                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8862                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8863                    DAG.getConstant(0, DL, MVT::i64));
8864 }
8865
8866 /// Target-specific DAG combine for the across vector min/max reductions.
8867 /// This function specifically handles the final clean-up step of the vector
8868 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8869 /// pattern, which narrows down and finds the final min/max value from all
8870 /// elements of the vector.
8871 /// For example, for a <16 x i8> vector :
8872 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8873 ///   %smax0 = smax %arr, svn0
8874 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8875 ///   %smax1 = smax %smax0, %svn1
8876 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8877 ///   %smax2 = smax %smax1, svn2
8878 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8879 ///   %sc = setcc %smax2, %svn3, gt
8880 ///   %n0 = extract_vector_elt %sc, #0
8881 ///   %n1 = extract_vector_elt %smax2, #0
8882 ///   %n2 = extract_vector_elt $smax2, #1
8883 ///   %result = select %n0, %n1, n2
8884 ///     becomes :
8885 ///   %1 = smaxv %0
8886 ///   %result = extract_vector_elt %1, 0
8887 static SDValue
8888 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8889                                         const AArch64Subtarget *Subtarget) {
8890   if (!Subtarget->hasNEON())
8891     return SDValue();
8892
8893   SDValue N0 = N->getOperand(0);
8894   SDValue IfTrue = N->getOperand(1);
8895   SDValue IfFalse = N->getOperand(2);
8896
8897   // Check if the SELECT merges up the final result of the min/max
8898   // from a vector.
8899   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8900       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8901       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8902     return SDValue();
8903
8904   // Expect N0 is fed by SETCC.
8905   SDValue SetCC = N0.getOperand(0);
8906   EVT SetCCVT = SetCC.getValueType();
8907   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8908       SetCCVT.getVectorElementType() != MVT::i1)
8909     return SDValue();
8910
8911   SDValue VectorOp = SetCC.getOperand(0);
8912   unsigned Op = VectorOp->getOpcode();
8913   // Check if the input vector is fed by the operator we want to handle.
8914   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8915       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8916     return SDValue();
8917
8918   EVT VTy = VectorOp.getValueType();
8919   if (!VTy.isVector())
8920     return SDValue();
8921
8922   if (VTy.getSizeInBits() < 64)
8923     return SDValue();
8924
8925   EVT EltTy = VTy.getVectorElementType();
8926   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8927     if (EltTy != MVT::f32)
8928       return SDValue();
8929   } else {
8930     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8931       return SDValue();
8932   }
8933
8934   // Check if extracting from the same vector.
8935   // For example,
8936   //   %sc = setcc %vector, %svn1, gt
8937   //   %n0 = extract_vector_elt %sc, #0
8938   //   %n1 = extract_vector_elt %vector, #0
8939   //   %n2 = extract_vector_elt $vector, #1
8940   if (!(VectorOp == IfTrue->getOperand(0) &&
8941         VectorOp == IfFalse->getOperand(0)))
8942     return SDValue();
8943
8944   // Check if the condition code is matched with the operator type.
8945   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8946   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8947       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8948       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8949       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8950       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8951        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8952        CC != ISD::SETGE) ||
8953       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8954        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8955        CC != ISD::SETLE))
8956     return SDValue();
8957
8958   // Expect to check only lane 0 from the vector SETCC.
8959   if (!isa<ConstantSDNode>(N0.getOperand(1)) ||
8960       cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue() != 0)
8961     return SDValue();
8962
8963   // Expect to extract the true value from lane 0.
8964   if (!isa<ConstantSDNode>(IfTrue.getOperand(1)) ||
8965       cast<ConstantSDNode>(IfTrue.getOperand(1))->getZExtValue() != 0)
8966     return SDValue();
8967
8968   // Expect to extract the false value from lane 1.
8969   if (!isa<ConstantSDNode>(IfFalse.getOperand(1)) ||
8970       cast<ConstantSDNode>(IfFalse.getOperand(1))->getZExtValue() != 1)
8971     return SDValue();
8972
8973   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8974 }
8975
8976 /// Target-specific DAG combine for the across vector add reduction.
8977 /// This function specifically handles the final clean-up step of the vector
8978 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8979 /// pattern, which adds all elements of a vector together.
8980 /// For example, for a <4 x i32> vector :
8981 ///   %1 = vector_shuffle %0, <2,3,u,u>
8982 ///   %2 = add %0, %1
8983 ///   %3 = vector_shuffle %2, <1,u,u,u>
8984 ///   %4 = add %2, %3
8985 ///   %result = extract_vector_elt %4, 0
8986 /// becomes :
8987 ///   %0 = uaddv %0
8988 ///   %result = extract_vector_elt %0, 0
8989 static SDValue
8990 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
8991                                      const AArch64Subtarget *Subtarget) {
8992   if (!Subtarget->hasNEON())
8993     return SDValue();
8994   SDValue N0 = N->getOperand(0);
8995   SDValue N1 = N->getOperand(1);
8996
8997   // Check if the input vector is fed by the ADD.
8998   if (N0->getOpcode() != ISD::ADD)
8999     return SDValue();
9000
9001   // The vector extract idx must constant zero because we only expect the final
9002   // result of the reduction is placed in lane 0.
9003   if (!isa<ConstantSDNode>(N1) || cast<ConstantSDNode>(N1)->getZExtValue() != 0)
9004     return SDValue();
9005
9006   EVT VTy = N0.getValueType();
9007   if (!VTy.isVector())
9008     return SDValue();
9009
9010   EVT EltTy = VTy.getVectorElementType();
9011   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9012     return SDValue();
9013
9014   if (VTy.getSizeInBits() < 64)
9015     return SDValue();
9016
9017   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9018 }
9019
9020 /// Target-specific DAG combine function for NEON load/store intrinsics
9021 /// to merge base address updates.
9022 static SDValue performNEONPostLDSTCombine(SDNode *N,
9023                                           TargetLowering::DAGCombinerInfo &DCI,
9024                                           SelectionDAG &DAG) {
9025   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9026     return SDValue();
9027
9028   unsigned AddrOpIdx = N->getNumOperands() - 1;
9029   SDValue Addr = N->getOperand(AddrOpIdx);
9030
9031   // Search for a use of the address operand that is an increment.
9032   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9033        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9034     SDNode *User = *UI;
9035     if (User->getOpcode() != ISD::ADD ||
9036         UI.getUse().getResNo() != Addr.getResNo())
9037       continue;
9038
9039     // Check that the add is independent of the load/store.  Otherwise, folding
9040     // it would create a cycle.
9041     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9042       continue;
9043
9044     // Find the new opcode for the updating load/store.
9045     bool IsStore = false;
9046     bool IsLaneOp = false;
9047     bool IsDupOp = false;
9048     unsigned NewOpc = 0;
9049     unsigned NumVecs = 0;
9050     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9051     switch (IntNo) {
9052     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9053     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9054       NumVecs = 2; break;
9055     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9056       NumVecs = 3; break;
9057     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9058       NumVecs = 4; break;
9059     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9060       NumVecs = 2; IsStore = true; break;
9061     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9062       NumVecs = 3; IsStore = true; break;
9063     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9064       NumVecs = 4; IsStore = true; break;
9065     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9066       NumVecs = 2; break;
9067     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9068       NumVecs = 3; break;
9069     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9070       NumVecs = 4; break;
9071     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9072       NumVecs = 2; IsStore = true; break;
9073     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9074       NumVecs = 3; IsStore = true; break;
9075     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9076       NumVecs = 4; IsStore = true; break;
9077     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9078       NumVecs = 2; IsDupOp = true; break;
9079     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9080       NumVecs = 3; IsDupOp = true; break;
9081     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9082       NumVecs = 4; IsDupOp = true; break;
9083     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9084       NumVecs = 2; IsLaneOp = true; break;
9085     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9086       NumVecs = 3; IsLaneOp = true; break;
9087     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9088       NumVecs = 4; IsLaneOp = true; break;
9089     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9090       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9091     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9092       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9093     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9094       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9095     }
9096
9097     EVT VecTy;
9098     if (IsStore)
9099       VecTy = N->getOperand(2).getValueType();
9100     else
9101       VecTy = N->getValueType(0);
9102
9103     // If the increment is a constant, it must match the memory ref size.
9104     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9105     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9106       uint32_t IncVal = CInc->getZExtValue();
9107       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9108       if (IsLaneOp || IsDupOp)
9109         NumBytes /= VecTy.getVectorNumElements();
9110       if (IncVal != NumBytes)
9111         continue;
9112       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9113     }
9114     SmallVector<SDValue, 8> Ops;
9115     Ops.push_back(N->getOperand(0)); // Incoming chain
9116     // Load lane and store have vector list as input.
9117     if (IsLaneOp || IsStore)
9118       for (unsigned i = 2; i < AddrOpIdx; ++i)
9119         Ops.push_back(N->getOperand(i));
9120     Ops.push_back(Addr); // Base register
9121     Ops.push_back(Inc);
9122
9123     // Return Types.
9124     EVT Tys[6];
9125     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9126     unsigned n;
9127     for (n = 0; n < NumResultVecs; ++n)
9128       Tys[n] = VecTy;
9129     Tys[n++] = MVT::i64;  // Type of write back register
9130     Tys[n] = MVT::Other;  // Type of the chain
9131     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9132
9133     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9134     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9135                                            MemInt->getMemoryVT(),
9136                                            MemInt->getMemOperand());
9137
9138     // Update the uses.
9139     std::vector<SDValue> NewResults;
9140     for (unsigned i = 0; i < NumResultVecs; ++i) {
9141       NewResults.push_back(SDValue(UpdN.getNode(), i));
9142     }
9143     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9144     DCI.CombineTo(N, NewResults);
9145     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9146
9147     break;
9148   }
9149   return SDValue();
9150 }
9151
9152 // Checks to see if the value is the prescribed width and returns information
9153 // about its extension mode.
9154 static
9155 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9156   ExtType = ISD::NON_EXTLOAD;
9157   switch(V.getNode()->getOpcode()) {
9158   default:
9159     return false;
9160   case ISD::LOAD: {
9161     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9162     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9163        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9164       ExtType = LoadNode->getExtensionType();
9165       return true;
9166     }
9167     return false;
9168   }
9169   case ISD::AssertSext: {
9170     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9171     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9172        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9173       ExtType = ISD::SEXTLOAD;
9174       return true;
9175     }
9176     return false;
9177   }
9178   case ISD::AssertZext: {
9179     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9180     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9181        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9182       ExtType = ISD::ZEXTLOAD;
9183       return true;
9184     }
9185     return false;
9186   }
9187   case ISD::Constant:
9188   case ISD::TargetConstant: {
9189     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9190         1LL << (width - 1))
9191       return true;
9192     return false;
9193   }
9194   }
9195
9196   return true;
9197 }
9198
9199 // This function does a whole lot of voodoo to determine if the tests are
9200 // equivalent without and with a mask. Essentially what happens is that given a
9201 // DAG resembling:
9202 //
9203 //  +-------------+ +-------------+ +-------------+ +-------------+
9204 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9205 //  +-------------+ +-------------+ +-------------+ +-------------+
9206 //           |           |           |               |
9207 //           V           V           |    +----------+
9208 //          +-------------+  +----+  |    |
9209 //          |     ADD     |  |0xff|  |    |
9210 //          +-------------+  +----+  |    |
9211 //                  |           |    |    |
9212 //                  V           V    |    |
9213 //                 +-------------+   |    |
9214 //                 |     AND     |   |    |
9215 //                 +-------------+   |    |
9216 //                      |            |    |
9217 //                      +-----+      |    |
9218 //                            |      |    |
9219 //                            V      V    V
9220 //                           +-------------+
9221 //                           |     CMP     |
9222 //                           +-------------+
9223 //
9224 // The AND node may be safely removed for some combinations of inputs. In
9225 // particular we need to take into account the extension type of the Input,
9226 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9227 // width of the input (this can work for any width inputs, the above graph is
9228 // specific to 8 bits.
9229 //
9230 // The specific equations were worked out by generating output tables for each
9231 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9232 // problem was simplified by working with 4 bit inputs, which means we only
9233 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9234 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9235 // patterns present in both extensions (0,7). For every distinct set of
9236 // AddConstant and CompConstants bit patterns we can consider the masked and
9237 // unmasked versions to be equivalent if the result of this function is true for
9238 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9239 //
9240 //   sub      w8, w0, w1
9241 //   and      w10, w8, #0x0f
9242 //   cmp      w8, w2
9243 //   cset     w9, AArch64CC
9244 //   cmp      w10, w2
9245 //   cset     w11, AArch64CC
9246 //   cmp      w9, w11
9247 //   cset     w0, eq
9248 //   ret
9249 //
9250 // Since the above function shows when the outputs are equivalent it defines
9251 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9252 // would be expensive to run during compiles. The equations below were written
9253 // in a test harness that confirmed they gave equivalent outputs to the above
9254 // for all inputs function, so they can be used determine if the removal is
9255 // legal instead.
9256 //
9257 // isEquivalentMaskless() is the code for testing if the AND can be removed
9258 // factored out of the DAG recognition as the DAG can take several forms.
9259
9260 static
9261 bool isEquivalentMaskless(unsigned CC, unsigned width,
9262                           ISD::LoadExtType ExtType, signed AddConstant,
9263                           signed CompConstant) {
9264   // By being careful about our equations and only writing the in term
9265   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9266   // make them generally applicable to all bit widths.
9267   signed MaxUInt = (1 << width);
9268
9269   // For the purposes of these comparisons sign extending the type is
9270   // equivalent to zero extending the add and displacing it by half the integer
9271   // width. Provided we are careful and make sure our equations are valid over
9272   // the whole range we can just adjust the input and avoid writing equations
9273   // for sign extended inputs.
9274   if (ExtType == ISD::SEXTLOAD)
9275     AddConstant -= (1 << (width-1));
9276
9277   switch(CC) {
9278   case AArch64CC::LE:
9279   case AArch64CC::GT: {
9280     if ((AddConstant == 0) ||
9281         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9282         (AddConstant >= 0 && CompConstant < 0) ||
9283         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9284       return true;
9285   } break;
9286   case AArch64CC::LT:
9287   case AArch64CC::GE: {
9288     if ((AddConstant == 0) ||
9289         (AddConstant >= 0 && CompConstant <= 0) ||
9290         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9291       return true;
9292   } break;
9293   case AArch64CC::HI:
9294   case AArch64CC::LS: {
9295     if ((AddConstant >= 0 && CompConstant < 0) ||
9296        (AddConstant <= 0 && CompConstant >= -1 &&
9297         CompConstant < AddConstant + MaxUInt))
9298       return true;
9299   } break;
9300   case AArch64CC::PL:
9301   case AArch64CC::MI: {
9302     if ((AddConstant == 0) ||
9303         (AddConstant > 0 && CompConstant <= 0) ||
9304         (AddConstant < 0 && CompConstant <= AddConstant))
9305       return true;
9306   } break;
9307   case AArch64CC::LO:
9308   case AArch64CC::HS: {
9309     if ((AddConstant >= 0 && CompConstant <= 0) ||
9310         (AddConstant <= 0 && CompConstant >= 0 &&
9311          CompConstant <= AddConstant + MaxUInt))
9312       return true;
9313   } break;
9314   case AArch64CC::EQ:
9315   case AArch64CC::NE: {
9316     if ((AddConstant > 0 && CompConstant < 0) ||
9317         (AddConstant < 0 && CompConstant >= 0 &&
9318          CompConstant < AddConstant + MaxUInt) ||
9319         (AddConstant >= 0 && CompConstant >= 0 &&
9320          CompConstant >= AddConstant) ||
9321         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9322
9323       return true;
9324   } break;
9325   case AArch64CC::VS:
9326   case AArch64CC::VC:
9327   case AArch64CC::AL:
9328   case AArch64CC::NV:
9329     return true;
9330   case AArch64CC::Invalid:
9331     break;
9332   }
9333
9334   return false;
9335 }
9336
9337 static
9338 SDValue performCONDCombine(SDNode *N,
9339                            TargetLowering::DAGCombinerInfo &DCI,
9340                            SelectionDAG &DAG, unsigned CCIndex,
9341                            unsigned CmpIndex) {
9342   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9343   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9344   unsigned CondOpcode = SubsNode->getOpcode();
9345
9346   if (CondOpcode != AArch64ISD::SUBS)
9347     return SDValue();
9348
9349   // There is a SUBS feeding this condition. Is it fed by a mask we can
9350   // use?
9351
9352   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9353   unsigned MaskBits = 0;
9354
9355   if (AndNode->getOpcode() != ISD::AND)
9356     return SDValue();
9357
9358   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9359     uint32_t CNV = CN->getZExtValue();
9360     if (CNV == 255)
9361       MaskBits = 8;
9362     else if (CNV == 65535)
9363       MaskBits = 16;
9364   }
9365
9366   if (!MaskBits)
9367     return SDValue();
9368
9369   SDValue AddValue = AndNode->getOperand(0);
9370
9371   if (AddValue.getOpcode() != ISD::ADD)
9372     return SDValue();
9373
9374   // The basic dag structure is correct, grab the inputs and validate them.
9375
9376   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9377   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9378   SDValue SubsInputValue = SubsNode->getOperand(1);
9379
9380   // The mask is present and the provenance of all the values is a smaller type,
9381   // lets see if the mask is superfluous.
9382
9383   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9384       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9385     return SDValue();
9386
9387   ISD::LoadExtType ExtType;
9388
9389   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9390       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9391       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9392     return SDValue();
9393
9394   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9395                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9396                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9397     return SDValue();
9398
9399   // The AND is not necessary, remove it.
9400
9401   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9402                                SubsNode->getValueType(1));
9403   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9404
9405   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9406   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9407
9408   return SDValue(N, 0);
9409 }
9410
9411 // Optimize compare with zero and branch.
9412 static SDValue performBRCONDCombine(SDNode *N,
9413                                     TargetLowering::DAGCombinerInfo &DCI,
9414                                     SelectionDAG &DAG) {
9415   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9416   if (NV.getNode())
9417     N = NV.getNode();
9418   SDValue Chain = N->getOperand(0);
9419   SDValue Dest = N->getOperand(1);
9420   SDValue CCVal = N->getOperand(2);
9421   SDValue Cmp = N->getOperand(3);
9422
9423   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9424   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9425   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9426     return SDValue();
9427
9428   unsigned CmpOpc = Cmp.getOpcode();
9429   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9430     return SDValue();
9431
9432   // Only attempt folding if there is only one use of the flag and no use of the
9433   // value.
9434   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9435     return SDValue();
9436
9437   SDValue LHS = Cmp.getOperand(0);
9438   SDValue RHS = Cmp.getOperand(1);
9439
9440   assert(LHS.getValueType() == RHS.getValueType() &&
9441          "Expected the value type to be the same for both operands!");
9442   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9443     return SDValue();
9444
9445   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9446     std::swap(LHS, RHS);
9447
9448   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9449     return SDValue();
9450
9451   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9452       LHS.getOpcode() == ISD::SRL)
9453     return SDValue();
9454
9455   // Fold the compare into the branch instruction.
9456   SDValue BR;
9457   if (CC == AArch64CC::EQ)
9458     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9459   else
9460     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9461
9462   // Do not add new nodes to DAG combiner worklist.
9463   DCI.CombineTo(N, BR, false);
9464
9465   return SDValue();
9466 }
9467
9468 // vselect (v1i1 setcc) ->
9469 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9470 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9471 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9472 // such VSELECT.
9473 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9474   SDValue N0 = N->getOperand(0);
9475   EVT CCVT = N0.getValueType();
9476
9477   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9478       CCVT.getVectorElementType() != MVT::i1)
9479     return SDValue();
9480
9481   EVT ResVT = N->getValueType(0);
9482   EVT CmpVT = N0.getOperand(0).getValueType();
9483   // Only combine when the result type is of the same size as the compared
9484   // operands.
9485   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9486     return SDValue();
9487
9488   SDValue IfTrue = N->getOperand(1);
9489   SDValue IfFalse = N->getOperand(2);
9490   SDValue SetCC =
9491       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9492                    N0.getOperand(0), N0.getOperand(1),
9493                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9494   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9495                      IfTrue, IfFalse);
9496 }
9497
9498 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9499 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9500 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9501 /// with a vector one followed by a DUP shuffle on the result.
9502 static SDValue performSelectCombine(SDNode *N,
9503                                     TargetLowering::DAGCombinerInfo &DCI) {
9504   SelectionDAG &DAG = DCI.DAG;
9505   SDValue N0 = N->getOperand(0);
9506   EVT ResVT = N->getValueType(0);
9507
9508   if (N0.getOpcode() != ISD::SETCC)
9509     return SDValue();
9510
9511   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9512   // scalar SetCCResultType. We also don't expect vectors, because we assume
9513   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9514   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9515          "Scalar-SETCC feeding SELECT has unexpected result type!");
9516
9517   // If NumMaskElts == 0, the comparison is larger than select result. The
9518   // largest real NEON comparison is 64-bits per lane, which means the result is
9519   // at most 32-bits and an illegal vector. Just bail out for now.
9520   EVT SrcVT = N0.getOperand(0).getValueType();
9521
9522   // Don't try to do this optimization when the setcc itself has i1 operands.
9523   // There are no legal vectors of i1, so this would be pointless.
9524   if (SrcVT == MVT::i1)
9525     return SDValue();
9526
9527   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9528   if (!ResVT.isVector() || NumMaskElts == 0)
9529     return SDValue();
9530
9531   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9532   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9533
9534   // Also bail out if the vector CCVT isn't the same size as ResVT.
9535   // This can happen if the SETCC operand size doesn't divide the ResVT size
9536   // (e.g., f64 vs v3f32).
9537   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9538     return SDValue();
9539
9540   // Make sure we didn't create illegal types, if we're not supposed to.
9541   assert(DCI.isBeforeLegalize() ||
9542          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9543
9544   // First perform a vector comparison, where lane 0 is the one we're interested
9545   // in.
9546   SDLoc DL(N0);
9547   SDValue LHS =
9548       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9549   SDValue RHS =
9550       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9551   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9552
9553   // Now duplicate the comparison mask we want across all other lanes.
9554   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9555   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9556   Mask = DAG.getNode(ISD::BITCAST, DL,
9557                      ResVT.changeVectorElementTypeToInteger(), Mask);
9558
9559   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9560 }
9561
9562 /// Get rid of unnecessary NVCASTs (that don't change the type).
9563 static SDValue performNVCASTCombine(SDNode *N) {
9564   if (N->getValueType(0) == N->getOperand(0).getValueType())
9565     return N->getOperand(0);
9566
9567   return SDValue();
9568 }
9569
9570 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9571                                                  DAGCombinerInfo &DCI) const {
9572   SelectionDAG &DAG = DCI.DAG;
9573   switch (N->getOpcode()) {
9574   default:
9575     break;
9576   case ISD::ADD:
9577   case ISD::SUB:
9578     return performAddSubLongCombine(N, DCI, DAG);
9579   case ISD::XOR:
9580     return performXorCombine(N, DAG, DCI, Subtarget);
9581   case ISD::MUL:
9582     return performMulCombine(N, DAG, DCI, Subtarget);
9583   case ISD::SINT_TO_FP:
9584   case ISD::UINT_TO_FP:
9585     return performIntToFpCombine(N, DAG, Subtarget);
9586   case ISD::FP_TO_SINT:
9587   case ISD::FP_TO_UINT:
9588     return performFpToIntCombine(N, DAG, Subtarget);
9589   case ISD::FDIV:
9590     return performFDivCombine(N, DAG, Subtarget);
9591   case ISD::OR:
9592     return performORCombine(N, DCI, Subtarget);
9593   case ISD::INTRINSIC_WO_CHAIN:
9594     return performIntrinsicCombine(N, DCI, Subtarget);
9595   case ISD::ANY_EXTEND:
9596   case ISD::ZERO_EXTEND:
9597   case ISD::SIGN_EXTEND:
9598     return performExtendCombine(N, DCI, DAG);
9599   case ISD::BITCAST:
9600     return performBitcastCombine(N, DCI, DAG);
9601   case ISD::CONCAT_VECTORS:
9602     return performConcatVectorsCombine(N, DCI, DAG);
9603   case ISD::SELECT: {
9604     SDValue RV = performSelectCombine(N, DCI);
9605     if (!RV.getNode())
9606       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9607     return RV;
9608   }
9609   case ISD::VSELECT:
9610     return performVSelectCombine(N, DCI.DAG);
9611   case ISD::LOAD:
9612     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9613       return SDValue(N, 0);
9614     break;
9615   case ISD::STORE:
9616     return performSTORECombine(N, DCI, DAG, Subtarget);
9617   case AArch64ISD::BRCOND:
9618     return performBRCONDCombine(N, DCI, DAG);
9619   case AArch64ISD::CSEL:
9620     return performCONDCombine(N, DCI, DAG, 2, 3);
9621   case AArch64ISD::DUP:
9622     return performPostLD1Combine(N, DCI, false);
9623   case AArch64ISD::NVCAST:
9624     return performNVCASTCombine(N);
9625   case ISD::INSERT_VECTOR_ELT:
9626     return performPostLD1Combine(N, DCI, true);
9627   case ISD::EXTRACT_VECTOR_ELT:
9628     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9629   case ISD::INTRINSIC_VOID:
9630   case ISD::INTRINSIC_W_CHAIN:
9631     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9632     case Intrinsic::aarch64_neon_ld2:
9633     case Intrinsic::aarch64_neon_ld3:
9634     case Intrinsic::aarch64_neon_ld4:
9635     case Intrinsic::aarch64_neon_ld1x2:
9636     case Intrinsic::aarch64_neon_ld1x3:
9637     case Intrinsic::aarch64_neon_ld1x4:
9638     case Intrinsic::aarch64_neon_ld2lane:
9639     case Intrinsic::aarch64_neon_ld3lane:
9640     case Intrinsic::aarch64_neon_ld4lane:
9641     case Intrinsic::aarch64_neon_ld2r:
9642     case Intrinsic::aarch64_neon_ld3r:
9643     case Intrinsic::aarch64_neon_ld4r:
9644     case Intrinsic::aarch64_neon_st2:
9645     case Intrinsic::aarch64_neon_st3:
9646     case Intrinsic::aarch64_neon_st4:
9647     case Intrinsic::aarch64_neon_st1x2:
9648     case Intrinsic::aarch64_neon_st1x3:
9649     case Intrinsic::aarch64_neon_st1x4:
9650     case Intrinsic::aarch64_neon_st2lane:
9651     case Intrinsic::aarch64_neon_st3lane:
9652     case Intrinsic::aarch64_neon_st4lane:
9653       return performNEONPostLDSTCombine(N, DCI, DAG);
9654     default:
9655       break;
9656     }
9657   }
9658   return SDValue();
9659 }
9660
9661 // Check if the return value is used as only a return value, as otherwise
9662 // we can't perform a tail-call. In particular, we need to check for
9663 // target ISD nodes that are returns and any other "odd" constructs
9664 // that the generic analysis code won't necessarily catch.
9665 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9666                                                SDValue &Chain) const {
9667   if (N->getNumValues() != 1)
9668     return false;
9669   if (!N->hasNUsesOfValue(1, 0))
9670     return false;
9671
9672   SDValue TCChain = Chain;
9673   SDNode *Copy = *N->use_begin();
9674   if (Copy->getOpcode() == ISD::CopyToReg) {
9675     // If the copy has a glue operand, we conservatively assume it isn't safe to
9676     // perform a tail call.
9677     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9678         MVT::Glue)
9679       return false;
9680     TCChain = Copy->getOperand(0);
9681   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9682     return false;
9683
9684   bool HasRet = false;
9685   for (SDNode *Node : Copy->uses()) {
9686     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9687       return false;
9688     HasRet = true;
9689   }
9690
9691   if (!HasRet)
9692     return false;
9693
9694   Chain = TCChain;
9695   return true;
9696 }
9697
9698 // Return whether the an instruction can potentially be optimized to a tail
9699 // call. This will cause the optimizers to attempt to move, or duplicate,
9700 // return instructions to help enable tail call optimizations for this
9701 // instruction.
9702 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9703   if (!CI->isTailCall())
9704     return false;
9705
9706   return true;
9707 }
9708
9709 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9710                                                    SDValue &Offset,
9711                                                    ISD::MemIndexedMode &AM,
9712                                                    bool &IsInc,
9713                                                    SelectionDAG &DAG) const {
9714   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9715     return false;
9716
9717   Base = Op->getOperand(0);
9718   // All of the indexed addressing mode instructions take a signed
9719   // 9 bit immediate offset.
9720   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9721     int64_t RHSC = (int64_t)RHS->getZExtValue();
9722     if (RHSC >= 256 || RHSC <= -256)
9723       return false;
9724     IsInc = (Op->getOpcode() == ISD::ADD);
9725     Offset = Op->getOperand(1);
9726     return true;
9727   }
9728   return false;
9729 }
9730
9731 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9732                                                       SDValue &Offset,
9733                                                       ISD::MemIndexedMode &AM,
9734                                                       SelectionDAG &DAG) const {
9735   EVT VT;
9736   SDValue Ptr;
9737   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9738     VT = LD->getMemoryVT();
9739     Ptr = LD->getBasePtr();
9740   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9741     VT = ST->getMemoryVT();
9742     Ptr = ST->getBasePtr();
9743   } else
9744     return false;
9745
9746   bool IsInc;
9747   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9748     return false;
9749   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9750   return true;
9751 }
9752
9753 bool AArch64TargetLowering::getPostIndexedAddressParts(
9754     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9755     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9756   EVT VT;
9757   SDValue Ptr;
9758   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9759     VT = LD->getMemoryVT();
9760     Ptr = LD->getBasePtr();
9761   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9762     VT = ST->getMemoryVT();
9763     Ptr = ST->getBasePtr();
9764   } else
9765     return false;
9766
9767   bool IsInc;
9768   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9769     return false;
9770   // Post-indexing updates the base, so it's not a valid transform
9771   // if that's not the same as the load's pointer.
9772   if (Ptr != Base)
9773     return false;
9774   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9775   return true;
9776 }
9777
9778 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9779                                   SelectionDAG &DAG) {
9780   SDLoc DL(N);
9781   SDValue Op = N->getOperand(0);
9782
9783   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9784     return;
9785
9786   Op = SDValue(
9787       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9788                          DAG.getUNDEF(MVT::i32), Op,
9789                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9790       0);
9791   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9792   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9793 }
9794
9795 static void ReplaceReductionResults(SDNode *N,
9796                                     SmallVectorImpl<SDValue> &Results,
9797                                     SelectionDAG &DAG, unsigned InterOp,
9798                                     unsigned AcrossOp) {
9799   EVT LoVT, HiVT;
9800   SDValue Lo, Hi;
9801   SDLoc dl(N);
9802   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9803   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9804   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9805   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9806   Results.push_back(SplitVal);
9807 }
9808
9809 void AArch64TargetLowering::ReplaceNodeResults(
9810     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9811   switch (N->getOpcode()) {
9812   default:
9813     llvm_unreachable("Don't know how to custom expand this");
9814   case ISD::BITCAST:
9815     ReplaceBITCASTResults(N, Results, DAG);
9816     return;
9817   case AArch64ISD::SADDV:
9818     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9819     return;
9820   case AArch64ISD::UADDV:
9821     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9822     return;
9823   case AArch64ISD::SMINV:
9824     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9825     return;
9826   case AArch64ISD::UMINV:
9827     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9828     return;
9829   case AArch64ISD::SMAXV:
9830     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9831     return;
9832   case AArch64ISD::UMAXV:
9833     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9834     return;
9835   case ISD::FP_TO_UINT:
9836   case ISD::FP_TO_SINT:
9837     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9838     // Let normal code take care of it by not adding anything to Results.
9839     return;
9840   }
9841 }
9842
9843 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9844   return true;
9845 }
9846
9847 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9848   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9849   // reciprocal if there are three or more FDIVs.
9850   return 3;
9851 }
9852
9853 TargetLoweringBase::LegalizeTypeAction
9854 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9855   MVT SVT = VT.getSimpleVT();
9856   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9857   // v4i16, v2i32 instead of to promote.
9858   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9859       || SVT == MVT::v1f32)
9860     return TypeWidenVector;
9861
9862   return TargetLoweringBase::getPreferredVectorAction(VT);
9863 }
9864
9865 // Loads and stores less than 128-bits are already atomic; ones above that
9866 // are doomed anyway, so defer to the default libcall and blame the OS when
9867 // things go wrong.
9868 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9869   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9870   return Size == 128;
9871 }
9872
9873 // Loads and stores less than 128-bits are already atomic; ones above that
9874 // are doomed anyway, so defer to the default libcall and blame the OS when
9875 // things go wrong.
9876 TargetLowering::AtomicExpansionKind
9877 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9878   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9879   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9880 }
9881
9882 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9883 TargetLowering::AtomicExpansionKind
9884 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9885   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9886   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9887 }
9888
9889 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9890     AtomicCmpXchgInst *AI) const {
9891   return true;
9892 }
9893
9894 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9895                                              AtomicOrdering Ord) const {
9896   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9897   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9898   bool IsAcquire = isAtLeastAcquire(Ord);
9899
9900   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9901   // intrinsic must return {i64, i64} and we have to recombine them into a
9902   // single i128 here.
9903   if (ValTy->getPrimitiveSizeInBits() == 128) {
9904     Intrinsic::ID Int =
9905         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9906     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9907
9908     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9909     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9910
9911     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9912     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9913     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9914     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9915     return Builder.CreateOr(
9916         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9917   }
9918
9919   Type *Tys[] = { Addr->getType() };
9920   Intrinsic::ID Int =
9921       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9922   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9923
9924   return Builder.CreateTruncOrBitCast(
9925       Builder.CreateCall(Ldxr, Addr),
9926       cast<PointerType>(Addr->getType())->getElementType());
9927 }
9928
9929 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9930     IRBuilder<> &Builder) const {
9931   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9932   Builder.CreateCall(
9933       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9934 }
9935
9936 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9937                                                    Value *Val, Value *Addr,
9938                                                    AtomicOrdering Ord) const {
9939   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9940   bool IsRelease = isAtLeastRelease(Ord);
9941
9942   // Since the intrinsics must have legal type, the i128 intrinsics take two
9943   // parameters: "i64, i64". We must marshal Val into the appropriate form
9944   // before the call.
9945   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9946     Intrinsic::ID Int =
9947         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9948     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9949     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9950
9951     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9952     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9953     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9954     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9955   }
9956
9957   Intrinsic::ID Int =
9958       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9959   Type *Tys[] = { Addr->getType() };
9960   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9961
9962   return Builder.CreateCall(Stxr,
9963                             {Builder.CreateZExtOrBitCast(
9964                                  Val, Stxr->getFunctionType()->getParamType(0)),
9965                              Addr});
9966 }
9967
9968 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9969     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9970   return Ty->isArrayTy();
9971 }
9972
9973 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9974                                                             EVT) const {
9975   return false;
9976 }
9977
9978 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9979   if (!Subtarget->isTargetAndroid())
9980     return TargetLowering::getSafeStackPointerLocation(IRB);
9981
9982   // Android provides a fixed TLS slot for the SafeStack pointer. See the
9983   // definition of TLS_SLOT_SAFESTACK in
9984   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
9985   const unsigned TlsOffset = 0x48;
9986   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
9987   Function *ThreadPointerFunc =
9988       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
9989   return IRB.CreatePointerCast(
9990       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
9991       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
9992 }