Remove white space (test commit)
[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   // Exception handling.
200   // FIXME: These are guesses. Has this been defined yet?
201   setExceptionPointerRegister(AArch64::X0);
202   setExceptionSelectorRegister(AArch64::X1);
203
204   // Constant pool entries
205   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
206
207   // BlockAddress
208   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
209
210   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211   setOperationAction(ISD::ADDC, MVT::i32, Custom);
212   setOperationAction(ISD::ADDE, MVT::i32, Custom);
213   setOperationAction(ISD::SUBC, MVT::i32, Custom);
214   setOperationAction(ISD::SUBE, MVT::i32, Custom);
215   setOperationAction(ISD::ADDC, MVT::i64, Custom);
216   setOperationAction(ISD::ADDE, MVT::i64, Custom);
217   setOperationAction(ISD::SUBC, MVT::i64, Custom);
218   setOperationAction(ISD::SUBE, MVT::i64, Custom);
219
220   // AArch64 lacks both left-rotate and popcount instructions.
221   setOperationAction(ISD::ROTL, MVT::i32, Expand);
222   setOperationAction(ISD::ROTL, MVT::i64, Expand);
223
224   // AArch64 doesn't have {U|S}MUL_LOHI.
225   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
227
228
229   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230   // counterparts, which AArch64 supports directly.
231   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
235
236   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
238
239   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241   setOperationAction(ISD::SREM, MVT::i32, Expand);
242   setOperationAction(ISD::SREM, MVT::i64, Expand);
243   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::UREM, MVT::i32, Expand);
246   setOperationAction(ISD::UREM, MVT::i64, Expand);
247
248   // Custom lower Add/Sub/Mul with overflow.
249   setOperationAction(ISD::SADDO, MVT::i32, Custom);
250   setOperationAction(ISD::SADDO, MVT::i64, Custom);
251   setOperationAction(ISD::UADDO, MVT::i32, Custom);
252   setOperationAction(ISD::UADDO, MVT::i64, Custom);
253   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255   setOperationAction(ISD::USUBO, MVT::i32, Custom);
256   setOperationAction(ISD::USUBO, MVT::i64, Custom);
257   setOperationAction(ISD::SMULO, MVT::i32, Custom);
258   setOperationAction(ISD::SMULO, MVT::i64, Custom);
259   setOperationAction(ISD::UMULO, MVT::i32, Custom);
260   setOperationAction(ISD::UMULO, MVT::i64, Custom);
261
262   setOperationAction(ISD::FSIN, MVT::f32, Expand);
263   setOperationAction(ISD::FSIN, MVT::f64, Expand);
264   setOperationAction(ISD::FCOS, MVT::f32, Expand);
265   setOperationAction(ISD::FCOS, MVT::f64, Expand);
266   setOperationAction(ISD::FPOW, MVT::f32, Expand);
267   setOperationAction(ISD::FPOW, MVT::f64, Expand);
268   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
270
271   // f16 is a storage-only type, always promote it to f32.
272   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
273   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
274   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
275   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
276   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
277   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
278   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
279   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
280   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
281   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
282   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
283   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
284   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
285   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
286   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
287   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
288   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
289   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
290   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
291   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
292   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
293   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
294   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
295   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
296   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
297   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
298   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
299   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
300   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
301   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
302   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
303   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
304   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
305   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
306
307   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
308   // known to be safe.
309   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
321
322   // Expand all other v4f16 operations.
323   // FIXME: We could generate better code by promoting some operations to
324   // a pair of v4f32s
325   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
351
352
353   // v8f16 is also a storage-only type, so expand it.
354   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
385
386   // AArch64 has implementations of a lot of rounding-like FP operations.
387   for (MVT Ty : {MVT::f32, MVT::f64}) {
388     setOperationAction(ISD::FFLOOR, Ty, Legal);
389     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390     setOperationAction(ISD::FCEIL, Ty, Legal);
391     setOperationAction(ISD::FRINT, Ty, Legal);
392     setOperationAction(ISD::FTRUNC, Ty, Legal);
393     setOperationAction(ISD::FROUND, Ty, Legal);
394     setOperationAction(ISD::FMINNUM, Ty, Legal);
395     setOperationAction(ISD::FMAXNUM, Ty, Legal);
396     setOperationAction(ISD::FMINNAN, Ty, Legal);
397     setOperationAction(ISD::FMAXNAN, Ty, Legal);
398   }
399
400   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
401
402   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
403   // This requires the Performance Monitors extension.
404   if (Subtarget->hasPerfMon())
405     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
406
407   if (Subtarget->isTargetMachO()) {
408     // For iOS, we don't want to the normal expansion of a libcall to
409     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
410     // traffic.
411     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
412     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
413   } else {
414     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
415     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
416   }
417
418   // Make floating-point constants legal for the large code model, so they don't
419   // become loads from the constant pool.
420   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
421     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
422     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
423   }
424
425   // AArch64 does not have floating-point extending loads, i1 sign-extending
426   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
427   for (MVT VT : MVT::fp_valuetypes()) {
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
432   }
433   for (MVT VT : MVT::integer_valuetypes())
434     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
435
436   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
443
444   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
445   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
446
447   // Indexed loads and stores are supported.
448   for (unsigned im = (unsigned)ISD::PRE_INC;
449        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
450     setIndexedLoadAction(im, MVT::i8, Legal);
451     setIndexedLoadAction(im, MVT::i16, Legal);
452     setIndexedLoadAction(im, MVT::i32, Legal);
453     setIndexedLoadAction(im, MVT::i64, Legal);
454     setIndexedLoadAction(im, MVT::f64, Legal);
455     setIndexedLoadAction(im, MVT::f32, Legal);
456     setIndexedLoadAction(im, MVT::f16, Legal);
457     setIndexedStoreAction(im, MVT::i8, Legal);
458     setIndexedStoreAction(im, MVT::i16, Legal);
459     setIndexedStoreAction(im, MVT::i32, Legal);
460     setIndexedStoreAction(im, MVT::i64, Legal);
461     setIndexedStoreAction(im, MVT::f64, Legal);
462     setIndexedStoreAction(im, MVT::f32, Legal);
463     setIndexedStoreAction(im, MVT::f16, Legal);
464   }
465
466   // Trap.
467   setOperationAction(ISD::TRAP, MVT::Other, Legal);
468
469   // We combine OR nodes for bitfield operations.
470   setTargetDAGCombine(ISD::OR);
471
472   // Vector add and sub nodes may conceal a high-half opportunity.
473   // Also, try to fold ADD into CSINC/CSINV..
474   setTargetDAGCombine(ISD::ADD);
475   setTargetDAGCombine(ISD::SUB);
476
477   setTargetDAGCombine(ISD::XOR);
478   setTargetDAGCombine(ISD::SINT_TO_FP);
479   setTargetDAGCombine(ISD::UINT_TO_FP);
480
481   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
482
483   setTargetDAGCombine(ISD::ANY_EXTEND);
484   setTargetDAGCombine(ISD::ZERO_EXTEND);
485   setTargetDAGCombine(ISD::SIGN_EXTEND);
486   setTargetDAGCombine(ISD::BITCAST);
487   setTargetDAGCombine(ISD::CONCAT_VECTORS);
488   setTargetDAGCombine(ISD::STORE);
489
490   setTargetDAGCombine(ISD::MUL);
491
492   setTargetDAGCombine(ISD::SELECT);
493   setTargetDAGCombine(ISD::VSELECT);
494
495   setTargetDAGCombine(ISD::INTRINSIC_VOID);
496   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
498   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
499
500   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
501   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
502   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
503
504   setStackPointerRegisterToSaveRestore(AArch64::SP);
505
506   setSchedulingPreference(Sched::Hybrid);
507
508   // Enable TBZ/TBNZ
509   MaskAndBranchFoldingIsLegal = true;
510   EnableExtLdPromotion = true;
511
512   setMinFunctionAlignment(2);
513
514   setHasExtractBitsInsn(true);
515
516   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
517
518   if (Subtarget->hasNEON()) {
519     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
520     // silliness like this:
521     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
522     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
523     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
524     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
525     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
526     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
527     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
528     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
529     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
530     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
531     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
532     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
533     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
534     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
535     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
536     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
537     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
538     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
539     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
541     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
542     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
543     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
544     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
545     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
546
547     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
548     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
549     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
550     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
551     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
552
553     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554
555     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
556     // elements smaller than i32, so promote the input to i32 first.
557     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
558     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
559     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
560     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
561     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
562     // -> v8f16 conversions.
563     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
564     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
565     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
566     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
567     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
568     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
569     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
570     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
571     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
572     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
573     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
574     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
576
577     // AArch64 doesn't have MUL.2d:
578     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
579     // Custom handling for some quad-vector types to detect MULL.
580     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
581     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
582     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
583
584     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
585     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
586     // Likewise, narrowing and extending vector loads/stores aren't handled
587     // directly.
588     for (MVT VT : MVT::vector_valuetypes()) {
589       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
590
591       setOperationAction(ISD::MULHS, VT, Expand);
592       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
593       setOperationAction(ISD::MULHU, VT, Expand);
594       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
595
596       setOperationAction(ISD::BSWAP, VT, Expand);
597
598       for (MVT InnerVT : MVT::vector_valuetypes()) {
599         setTruncStoreAction(VT, InnerVT, Expand);
600         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
601         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
602         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
603       }
604     }
605
606     // AArch64 has implementations of a lot of rounding-like FP operations.
607     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
608       setOperationAction(ISD::FFLOOR, Ty, Legal);
609       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
610       setOperationAction(ISD::FCEIL, Ty, Legal);
611       setOperationAction(ISD::FRINT, Ty, Legal);
612       setOperationAction(ISD::FTRUNC, Ty, Legal);
613       setOperationAction(ISD::FROUND, Ty, Legal);
614     }
615   }
616
617   // Prefer likely predicted branches to selects on out-of-order cores.
618   if (Subtarget->isCortexA57())
619     PredictableSelectIsExpensive = true;
620 }
621
622 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
623   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
624     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
625     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
626
627     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
628     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
629   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
630     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
631     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
632
633     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
634     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
635   }
636
637   // Mark vector float intrinsics as expand.
638   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
639     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
640     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
641     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
642     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
643     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
648
649     // But we do support custom-lowering for FCOPYSIGN.
650     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
651   }
652
653   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
654   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
655   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
656   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
657   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
665
666   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
667   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
668   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
669   for (MVT InnerVT : MVT::all_valuetypes())
670     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
671
672   // CNT supports only B element sizes.
673   if (VT != MVT::v8i8 && VT != MVT::v16i8)
674     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
675
676   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
677   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
678   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
679   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
680   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
681
682   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
683   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
684
685   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
686   // i64.
687   if (!VT.isFloatingPoint() &&
688       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
689     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
690                             ISD::SABSDIFF, ISD::UABSDIFF})
691       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
692
693   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
694   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
695     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
696                             ISD::FMINNUM, ISD::FMAXNUM})
697       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
698
699   if (Subtarget->isLittleEndian()) {
700     for (unsigned im = (unsigned)ISD::PRE_INC;
701          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
702       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
703       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
704     }
705   }
706 }
707
708 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
709   addRegisterClass(VT, &AArch64::FPR64RegClass);
710   addTypeForNEON(VT, MVT::v2i32);
711 }
712
713 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
714   addRegisterClass(VT, &AArch64::FPR128RegClass);
715   addTypeForNEON(VT, MVT::v4i32);
716 }
717
718 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
719                                               EVT VT) const {
720   if (!VT.isVector())
721     return MVT::i32;
722   return VT.changeVectorElementTypeToInteger();
723 }
724
725 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
726 /// Mask are known to be either zero or one and return them in the
727 /// KnownZero/KnownOne bitsets.
728 void AArch64TargetLowering::computeKnownBitsForTargetNode(
729     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
730     const SelectionDAG &DAG, unsigned Depth) const {
731   switch (Op.getOpcode()) {
732   default:
733     break;
734   case AArch64ISD::CSEL: {
735     APInt KnownZero2, KnownOne2;
736     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
737     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
738     KnownZero &= KnownZero2;
739     KnownOne &= KnownOne2;
740     break;
741   }
742   case ISD::INTRINSIC_W_CHAIN: {
743     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
744     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
745     switch (IntID) {
746     default: return;
747     case Intrinsic::aarch64_ldaxr:
748     case Intrinsic::aarch64_ldxr: {
749       unsigned BitWidth = KnownOne.getBitWidth();
750       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
751       unsigned MemBits = VT.getScalarType().getSizeInBits();
752       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
753       return;
754     }
755     }
756     break;
757   }
758   case ISD::INTRINSIC_WO_CHAIN:
759   case ISD::INTRINSIC_VOID: {
760     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
761     switch (IntNo) {
762     default:
763       break;
764     case Intrinsic::aarch64_neon_umaxv:
765     case Intrinsic::aarch64_neon_uminv: {
766       // Figure out the datatype of the vector operand. The UMINV instruction
767       // will zero extend the result, so we can mark as known zero all the
768       // bits larger than the element datatype. 32-bit or larget doesn't need
769       // this as those are legal types and will be handled by isel directly.
770       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
771       unsigned BitWidth = KnownZero.getBitWidth();
772       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
773         assert(BitWidth >= 8 && "Unexpected width!");
774         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
775         KnownZero |= Mask;
776       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
777         assert(BitWidth >= 16 && "Unexpected width!");
778         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
779         KnownZero |= Mask;
780       }
781       break;
782     } break;
783     }
784   }
785   }
786 }
787
788 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
789                                                   EVT) const {
790   return MVT::i64;
791 }
792
793 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
794                                                            unsigned AddrSpace,
795                                                            unsigned Align,
796                                                            bool *Fast) const {
797   if (Subtarget->requiresStrictAlign())
798     return false;
799   // FIXME: True for Cyclone, but not necessary others.
800   if (Fast)
801     *Fast = true;
802   return true;
803 }
804
805 FastISel *
806 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
807                                       const TargetLibraryInfo *libInfo) const {
808   return AArch64::createFastISel(funcInfo, libInfo);
809 }
810
811 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
812   switch ((AArch64ISD::NodeType)Opcode) {
813   case AArch64ISD::FIRST_NUMBER:      break;
814   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
815   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
816   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
817   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
818   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
819   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
820   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
821   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
822   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
823   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
824   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
825   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
826   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
827   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
828   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
829   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
830   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
831   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
832   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
833   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
834   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
835   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
836   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
837   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
838   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
839   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
840   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
841   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
842   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
843   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
844   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
845   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
846   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
847   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
848   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
849   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
850   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
851   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
852   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
853   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
854   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
855   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
856   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
857   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
858   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
859   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
860   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
861   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
862   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
863   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
864   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
865   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
866   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
867   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
868   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
869   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
870   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
871   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
872   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
873   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
874   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
875   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
876   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
877   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
878   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
879   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
880   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
881   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
882   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
883   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
884   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
885   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
886   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
887   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
888   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
889   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
890   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
891   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
892   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
893   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
894   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
895   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
896   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
897   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
898   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
899   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
900   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
901   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
902   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
903   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
904   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
905   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
906   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
907   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
908   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
909   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
910   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
911   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
912   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
913   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
914   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
915   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
916   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
917   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
918   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
919   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
920   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
921   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
922   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
923   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
924   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
925   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
926   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
927   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
928   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
929   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
930   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
931   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
932   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
933   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
934   }
935   return nullptr;
936 }
937
938 MachineBasicBlock *
939 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
940                                     MachineBasicBlock *MBB) const {
941   // We materialise the F128CSEL pseudo-instruction as some control flow and a
942   // phi node:
943
944   // OrigBB:
945   //     [... previous instrs leading to comparison ...]
946   //     b.ne TrueBB
947   //     b EndBB
948   // TrueBB:
949   //     ; Fallthrough
950   // EndBB:
951   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
952
953   MachineFunction *MF = MBB->getParent();
954   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
955   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
956   DebugLoc DL = MI->getDebugLoc();
957   MachineFunction::iterator It = MBB;
958   ++It;
959
960   unsigned DestReg = MI->getOperand(0).getReg();
961   unsigned IfTrueReg = MI->getOperand(1).getReg();
962   unsigned IfFalseReg = MI->getOperand(2).getReg();
963   unsigned CondCode = MI->getOperand(3).getImm();
964   bool NZCVKilled = MI->getOperand(4).isKill();
965
966   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
967   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
968   MF->insert(It, TrueBB);
969   MF->insert(It, EndBB);
970
971   // Transfer rest of current basic-block to EndBB
972   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
973                 MBB->end());
974   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
975
976   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
977   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
978   MBB->addSuccessor(TrueBB);
979   MBB->addSuccessor(EndBB);
980
981   // TrueBB falls through to the end.
982   TrueBB->addSuccessor(EndBB);
983
984   if (!NZCVKilled) {
985     TrueBB->addLiveIn(AArch64::NZCV);
986     EndBB->addLiveIn(AArch64::NZCV);
987   }
988
989   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
990       .addReg(IfTrueReg)
991       .addMBB(TrueBB)
992       .addReg(IfFalseReg)
993       .addMBB(MBB);
994
995   MI->eraseFromParent();
996   return EndBB;
997 }
998
999 MachineBasicBlock *
1000 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1001                                                  MachineBasicBlock *BB) const {
1002   switch (MI->getOpcode()) {
1003   default:
1004 #ifndef NDEBUG
1005     MI->dump();
1006 #endif
1007     llvm_unreachable("Unexpected instruction for custom inserter!");
1008
1009   case AArch64::F128CSEL:
1010     return EmitF128CSEL(MI, BB);
1011
1012   case TargetOpcode::STACKMAP:
1013   case TargetOpcode::PATCHPOINT:
1014     return emitPatchPoint(MI, BB);
1015   }
1016 }
1017
1018 //===----------------------------------------------------------------------===//
1019 // AArch64 Lowering private implementation.
1020 //===----------------------------------------------------------------------===//
1021
1022 //===----------------------------------------------------------------------===//
1023 // Lowering Code
1024 //===----------------------------------------------------------------------===//
1025
1026 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1027 /// CC
1028 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1029   switch (CC) {
1030   default:
1031     llvm_unreachable("Unknown condition code!");
1032   case ISD::SETNE:
1033     return AArch64CC::NE;
1034   case ISD::SETEQ:
1035     return AArch64CC::EQ;
1036   case ISD::SETGT:
1037     return AArch64CC::GT;
1038   case ISD::SETGE:
1039     return AArch64CC::GE;
1040   case ISD::SETLT:
1041     return AArch64CC::LT;
1042   case ISD::SETLE:
1043     return AArch64CC::LE;
1044   case ISD::SETUGT:
1045     return AArch64CC::HI;
1046   case ISD::SETUGE:
1047     return AArch64CC::HS;
1048   case ISD::SETULT:
1049     return AArch64CC::LO;
1050   case ISD::SETULE:
1051     return AArch64CC::LS;
1052   }
1053 }
1054
1055 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1056 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1057                                   AArch64CC::CondCode &CondCode,
1058                                   AArch64CC::CondCode &CondCode2) {
1059   CondCode2 = AArch64CC::AL;
1060   switch (CC) {
1061   default:
1062     llvm_unreachable("Unknown FP condition!");
1063   case ISD::SETEQ:
1064   case ISD::SETOEQ:
1065     CondCode = AArch64CC::EQ;
1066     break;
1067   case ISD::SETGT:
1068   case ISD::SETOGT:
1069     CondCode = AArch64CC::GT;
1070     break;
1071   case ISD::SETGE:
1072   case ISD::SETOGE:
1073     CondCode = AArch64CC::GE;
1074     break;
1075   case ISD::SETOLT:
1076     CondCode = AArch64CC::MI;
1077     break;
1078   case ISD::SETOLE:
1079     CondCode = AArch64CC::LS;
1080     break;
1081   case ISD::SETONE:
1082     CondCode = AArch64CC::MI;
1083     CondCode2 = AArch64CC::GT;
1084     break;
1085   case ISD::SETO:
1086     CondCode = AArch64CC::VC;
1087     break;
1088   case ISD::SETUO:
1089     CondCode = AArch64CC::VS;
1090     break;
1091   case ISD::SETUEQ:
1092     CondCode = AArch64CC::EQ;
1093     CondCode2 = AArch64CC::VS;
1094     break;
1095   case ISD::SETUGT:
1096     CondCode = AArch64CC::HI;
1097     break;
1098   case ISD::SETUGE:
1099     CondCode = AArch64CC::PL;
1100     break;
1101   case ISD::SETLT:
1102   case ISD::SETULT:
1103     CondCode = AArch64CC::LT;
1104     break;
1105   case ISD::SETLE:
1106   case ISD::SETULE:
1107     CondCode = AArch64CC::LE;
1108     break;
1109   case ISD::SETNE:
1110   case ISD::SETUNE:
1111     CondCode = AArch64CC::NE;
1112     break;
1113   }
1114 }
1115
1116 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1117 /// CC usable with the vector instructions. Fewer operations are available
1118 /// without a real NZCV register, so we have to use less efficient combinations
1119 /// to get the same effect.
1120 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1121                                         AArch64CC::CondCode &CondCode,
1122                                         AArch64CC::CondCode &CondCode2,
1123                                         bool &Invert) {
1124   Invert = false;
1125   switch (CC) {
1126   default:
1127     // Mostly the scalar mappings work fine.
1128     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1129     break;
1130   case ISD::SETUO:
1131     Invert = true; // Fallthrough
1132   case ISD::SETO:
1133     CondCode = AArch64CC::MI;
1134     CondCode2 = AArch64CC::GE;
1135     break;
1136   case ISD::SETUEQ:
1137   case ISD::SETULT:
1138   case ISD::SETULE:
1139   case ISD::SETUGT:
1140   case ISD::SETUGE:
1141     // All of the compare-mask comparisons are ordered, but we can switch
1142     // between the two by a double inversion. E.g. ULE == !OGT.
1143     Invert = true;
1144     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1145     break;
1146   }
1147 }
1148
1149 static bool isLegalArithImmed(uint64_t C) {
1150   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1151   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1152 }
1153
1154 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1155                               SDLoc dl, SelectionDAG &DAG) {
1156   EVT VT = LHS.getValueType();
1157
1158   if (VT.isFloatingPoint())
1159     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1160
1161   // The CMP instruction is just an alias for SUBS, and representing it as
1162   // SUBS means that it's possible to get CSE with subtract operations.
1163   // A later phase can perform the optimization of setting the destination
1164   // register to WZR/XZR if it ends up being unused.
1165   unsigned Opcode = AArch64ISD::SUBS;
1166
1167   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1168       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1169       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1170     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1171     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1172     // can be set differently by this operation. It comes down to whether
1173     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1174     // everything is fine. If not then the optimization is wrong. Thus general
1175     // comparisons are only valid if op2 != 0.
1176
1177     // So, finally, the only LLVM-native comparisons that don't mention C and V
1178     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1179     // the absence of information about op2.
1180     Opcode = AArch64ISD::ADDS;
1181     RHS = RHS.getOperand(1);
1182   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1183              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1184              !isUnsignedIntSetCC(CC)) {
1185     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1186     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1187     // of the signed comparisons.
1188     Opcode = AArch64ISD::ANDS;
1189     RHS = LHS.getOperand(1);
1190     LHS = LHS.getOperand(0);
1191   }
1192
1193   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1194       .getValue(1);
1195 }
1196
1197 /// \defgroup AArch64CCMP CMP;CCMP matching
1198 ///
1199 /// These functions deal with the formation of CMP;CCMP;... sequences.
1200 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1201 /// a comparison. They set the NZCV flags to a predefined value if their
1202 /// predicate is false. This allows to express arbitrary conjunctions, for
1203 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1204 /// expressed as:
1205 ///   cmp A
1206 ///   ccmp B, inv(CB), CA
1207 ///   check for CB flags
1208 ///
1209 /// In general we can create code for arbitrary "... (and (and A B) C)"
1210 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1211 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1212 /// negation operations:
1213 /// We can negate the results of a single comparison by inverting the flags
1214 /// used when the predicate fails and inverting the flags tested in the next
1215 /// instruction; We can also negate the results of the whole previous
1216 /// conditional compare sequence by inverting the flags tested in the next
1217 /// instruction. However there is no way to negate the result of a partial
1218 /// sequence.
1219 ///
1220 /// Therefore on encountering an "or" expression we can negate the subtree on
1221 /// one side and have to be able to push the negate to the leafs of the subtree
1222 /// on the other side (see also the comments in code). As complete example:
1223 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1224 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1225 /// is transformed to
1226 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1227 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1228 /// and implemented as:
1229 ///   cmp C
1230 ///   ccmp D, inv(CD), CC
1231 ///   ccmp A, CA, inv(CD)
1232 ///   ccmp B, CB, inv(CA)
1233 ///   check for CB flags
1234 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1235 /// by conditional compare sequences.
1236 /// @{
1237
1238 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1239 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1240                                          ISD::CondCode CC, SDValue CCOp,
1241                                          SDValue Condition, unsigned NZCV,
1242                                          SDLoc DL, SelectionDAG &DAG) {
1243   unsigned Opcode = 0;
1244   if (LHS.getValueType().isFloatingPoint())
1245     Opcode = AArch64ISD::FCCMP;
1246   else if (RHS.getOpcode() == ISD::SUB) {
1247     SDValue SubOp0 = RHS.getOperand(0);
1248     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1249       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1250         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1251         Opcode = AArch64ISD::CCMN;
1252         RHS = RHS.getOperand(1);
1253       }
1254   }
1255   if (Opcode == 0)
1256     Opcode = AArch64ISD::CCMP;
1257
1258   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1259   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1260 }
1261
1262 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1263 /// CanPushNegate is set to true if we can push a negate operation through
1264 /// the tree in a was that we are left with AND operations and negate operations
1265 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1266 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1267 /// brought into such a form.
1268 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1269                                          unsigned Depth = 0) {
1270   if (!Val.hasOneUse())
1271     return false;
1272   unsigned Opcode = Val->getOpcode();
1273   if (Opcode == ISD::SETCC) {
1274     CanPushNegate = true;
1275     return true;
1276   }
1277   // Protect against stack overflow.
1278   if (Depth > 15)
1279     return false;
1280   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1281     SDValue O0 = Val->getOperand(0);
1282     SDValue O1 = Val->getOperand(1);
1283     bool CanPushNegateL;
1284     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1285       return false;
1286     bool CanPushNegateR;
1287     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1288       return false;
1289     // We cannot push a negate through an AND operation (it would become an OR),
1290     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1291     // push the negate through the x/y subtrees.
1292     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1293     return true;
1294   }
1295   return false;
1296 }
1297
1298 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1299 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1300 /// Tries to transform the given i1 producing node @p Val to a series compare
1301 /// and conditional compare operations. @returns an NZCV flags producing node
1302 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1303 /// transformation was not possible.
1304 /// On recursive invocations @p PushNegate may be set to true to have negation
1305 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1306 /// for the comparisons in the current subtree; @p Depth limits the search
1307 /// depth to avoid stack overflow.
1308 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1309     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1310     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1311     unsigned Depth = 0) {
1312   // We're at a tree leaf, produce a conditional comparison operation.
1313   unsigned Opcode = Val->getOpcode();
1314   if (Opcode == ISD::SETCC) {
1315     SDValue LHS = Val->getOperand(0);
1316     SDValue RHS = Val->getOperand(1);
1317     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1318     bool isInteger = LHS.getValueType().isInteger();
1319     if (PushNegate)
1320       CC = getSetCCInverse(CC, isInteger);
1321     SDLoc DL(Val);
1322     // Determine OutCC and handle FP special case.
1323     if (isInteger) {
1324       OutCC = changeIntCCToAArch64CC(CC);
1325     } else {
1326       assert(LHS.getValueType().isFloatingPoint());
1327       AArch64CC::CondCode ExtraCC;
1328       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1329       // Surpisingly some floating point conditions can't be tested with a
1330       // single condition code. Construct an additional comparison in this case.
1331       // See comment below on how we deal with OR conditions.
1332       if (ExtraCC != AArch64CC::AL) {
1333         SDValue ExtraCmp;
1334         if (!CCOp.getNode())
1335           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1336         else {
1337           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1338           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1339           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1340           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1341                                                NZCV, DL, DAG);
1342         }
1343         CCOp = ExtraCmp;
1344         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1345         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1346       }
1347     }
1348
1349     // Produce a normal comparison if we are first in the chain
1350     if (!CCOp.getNode())
1351       return emitComparison(LHS, RHS, CC, DL, DAG);
1352     // Otherwise produce a ccmp.
1353     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1354     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1355     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1356     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1357                                      DAG);
1358   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1359     return SDValue();
1360
1361   assert((Opcode == ISD::OR || !PushNegate)
1362          && "Can only push negate through OR operation");
1363
1364   // Check if both sides can be transformed.
1365   SDValue LHS = Val->getOperand(0);
1366   SDValue RHS = Val->getOperand(1);
1367   bool CanPushNegateL;
1368   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1369     return SDValue();
1370   bool CanPushNegateR;
1371   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1372     return SDValue();
1373
1374   // Do we need to negate our operands?
1375   bool NegateOperands = Opcode == ISD::OR;
1376   // We can negate the results of all previous operations by inverting the
1377   // predicate flags giving us a free negation for one side. For the other side
1378   // we need to be able to push the negation to the leafs of the tree.
1379   if (NegateOperands) {
1380     if (!CanPushNegateL && !CanPushNegateR)
1381       return SDValue();
1382     // Order the side where we can push the negate through to LHS.
1383     if (!CanPushNegateL && CanPushNegateR)
1384       std::swap(LHS, RHS);
1385   } else {
1386     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1387     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1388     if (NeedsNegOutL && NeedsNegOutR)
1389       return SDValue();
1390     // Order the side where we need to negate the output flags to RHS so it
1391     // gets emitted first.
1392     if (NeedsNegOutL)
1393       std::swap(LHS, RHS);
1394   }
1395
1396   // Emit RHS. If we want to negate the tree we only need to push a negate
1397   // through if we are already in a PushNegate case, otherwise we can negate
1398   // the "flags to test" afterwards.
1399   AArch64CC::CondCode RHSCC;
1400   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1401                                                 CCOp, Predicate, Depth+1);
1402   if (NegateOperands && !PushNegate)
1403     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1404   // Emit LHS. We must push the negate through if we need to negate it.
1405   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1406                                                 CmpR, RHSCC, Depth+1);
1407   // If we transformed an OR to and AND then we have to negate the result
1408   // (or absorb a PushNegate resulting in a double negation).
1409   if (Opcode == ISD::OR && !PushNegate)
1410     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1411   return CmpL;
1412 }
1413
1414 /// @}
1415
1416 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1417                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1418   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1419     EVT VT = RHS.getValueType();
1420     uint64_t C = RHSC->getZExtValue();
1421     if (!isLegalArithImmed(C)) {
1422       // Constant does not fit, try adjusting it by one?
1423       switch (CC) {
1424       default:
1425         break;
1426       case ISD::SETLT:
1427       case ISD::SETGE:
1428         if ((VT == MVT::i32 && C != 0x80000000 &&
1429              isLegalArithImmed((uint32_t)(C - 1))) ||
1430             (VT == MVT::i64 && C != 0x80000000ULL &&
1431              isLegalArithImmed(C - 1ULL))) {
1432           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1433           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1434           RHS = DAG.getConstant(C, dl, VT);
1435         }
1436         break;
1437       case ISD::SETULT:
1438       case ISD::SETUGE:
1439         if ((VT == MVT::i32 && C != 0 &&
1440              isLegalArithImmed((uint32_t)(C - 1))) ||
1441             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1442           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1443           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1444           RHS = DAG.getConstant(C, dl, VT);
1445         }
1446         break;
1447       case ISD::SETLE:
1448       case ISD::SETGT:
1449         if ((VT == MVT::i32 && C != INT32_MAX &&
1450              isLegalArithImmed((uint32_t)(C + 1))) ||
1451             (VT == MVT::i64 && C != INT64_MAX &&
1452              isLegalArithImmed(C + 1ULL))) {
1453           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1454           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1455           RHS = DAG.getConstant(C, dl, VT);
1456         }
1457         break;
1458       case ISD::SETULE:
1459       case ISD::SETUGT:
1460         if ((VT == MVT::i32 && C != UINT32_MAX &&
1461              isLegalArithImmed((uint32_t)(C + 1))) ||
1462             (VT == MVT::i64 && C != UINT64_MAX &&
1463              isLegalArithImmed(C + 1ULL))) {
1464           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1465           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1466           RHS = DAG.getConstant(C, dl, VT);
1467         }
1468         break;
1469       }
1470     }
1471   }
1472   SDValue Cmp;
1473   AArch64CC::CondCode AArch64CC;
1474   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1475     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1476
1477     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1478     // For the i8 operand, the largest immediate is 255, so this can be easily
1479     // encoded in the compare instruction. For the i16 operand, however, the
1480     // largest immediate cannot be encoded in the compare.
1481     // Therefore, use a sign extending load and cmn to avoid materializing the
1482     // -1 constant. For example,
1483     // movz w1, #65535
1484     // ldrh w0, [x0, #0]
1485     // cmp w0, w1
1486     // >
1487     // ldrsh w0, [x0, #0]
1488     // cmn w0, #1
1489     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1490     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1491     // ensure both the LHS and RHS are truly zero extended and to make sure the
1492     // transformation is profitable.
1493     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1494         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1495         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1496         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1497       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1498       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1499         SDValue SExt =
1500             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1501                         DAG.getValueType(MVT::i16));
1502         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1503                                                    RHS.getValueType()),
1504                              CC, dl, DAG);
1505         AArch64CC = changeIntCCToAArch64CC(CC);
1506       }
1507     }
1508
1509     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1510       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1511         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1512           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1513       }
1514     }
1515   }
1516
1517   if (!Cmp) {
1518     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1519     AArch64CC = changeIntCCToAArch64CC(CC);
1520   }
1521   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1522   return Cmp;
1523 }
1524
1525 static std::pair<SDValue, SDValue>
1526 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1527   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1528          "Unsupported value type");
1529   SDValue Value, Overflow;
1530   SDLoc DL(Op);
1531   SDValue LHS = Op.getOperand(0);
1532   SDValue RHS = Op.getOperand(1);
1533   unsigned Opc = 0;
1534   switch (Op.getOpcode()) {
1535   default:
1536     llvm_unreachable("Unknown overflow instruction!");
1537   case ISD::SADDO:
1538     Opc = AArch64ISD::ADDS;
1539     CC = AArch64CC::VS;
1540     break;
1541   case ISD::UADDO:
1542     Opc = AArch64ISD::ADDS;
1543     CC = AArch64CC::HS;
1544     break;
1545   case ISD::SSUBO:
1546     Opc = AArch64ISD::SUBS;
1547     CC = AArch64CC::VS;
1548     break;
1549   case ISD::USUBO:
1550     Opc = AArch64ISD::SUBS;
1551     CC = AArch64CC::LO;
1552     break;
1553   // Multiply needs a little bit extra work.
1554   case ISD::SMULO:
1555   case ISD::UMULO: {
1556     CC = AArch64CC::NE;
1557     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1558     if (Op.getValueType() == MVT::i32) {
1559       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1560       // For a 32 bit multiply with overflow check we want the instruction
1561       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1562       // need to generate the following pattern:
1563       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1564       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1565       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1566       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1567       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1568                                 DAG.getConstant(0, DL, MVT::i64));
1569       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1570       // operation. We need to clear out the upper 32 bits, because we used a
1571       // widening multiply that wrote all 64 bits. In the end this should be a
1572       // noop.
1573       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1574       if (IsSigned) {
1575         // The signed overflow check requires more than just a simple check for
1576         // any bit set in the upper 32 bits of the result. These bits could be
1577         // just the sign bits of a negative number. To perform the overflow
1578         // check we have to arithmetic shift right the 32nd bit of the result by
1579         // 31 bits. Then we compare the result to the upper 32 bits.
1580         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1581                                         DAG.getConstant(32, DL, MVT::i64));
1582         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1583         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1584                                         DAG.getConstant(31, DL, MVT::i64));
1585         // It is important that LowerBits is last, otherwise the arithmetic
1586         // shift will not be folded into the compare (SUBS).
1587         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1588         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1589                        .getValue(1);
1590       } else {
1591         // The overflow check for unsigned multiply is easy. We only need to
1592         // check if any of the upper 32 bits are set. This can be done with a
1593         // CMP (shifted register). For that we need to generate the following
1594         // pattern:
1595         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1596         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1597                                         DAG.getConstant(32, DL, MVT::i64));
1598         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1599         Overflow =
1600             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1601                         DAG.getConstant(0, DL, MVT::i64),
1602                         UpperBits).getValue(1);
1603       }
1604       break;
1605     }
1606     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1607     // For the 64 bit multiply
1608     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1609     if (IsSigned) {
1610       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1611       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1612                                       DAG.getConstant(63, DL, MVT::i64));
1613       // It is important that LowerBits is last, otherwise the arithmetic
1614       // shift will not be folded into the compare (SUBS).
1615       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1616       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1617                      .getValue(1);
1618     } else {
1619       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1620       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1621       Overflow =
1622           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1623                       DAG.getConstant(0, DL, MVT::i64),
1624                       UpperBits).getValue(1);
1625     }
1626     break;
1627   }
1628   } // switch (...)
1629
1630   if (Opc) {
1631     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1632
1633     // Emit the AArch64 operation with overflow check.
1634     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1635     Overflow = Value.getValue(1);
1636   }
1637   return std::make_pair(Value, Overflow);
1638 }
1639
1640 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1641                                              RTLIB::Libcall Call) const {
1642   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1643   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1644                      SDLoc(Op)).first;
1645 }
1646
1647 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1648   SDValue Sel = Op.getOperand(0);
1649   SDValue Other = Op.getOperand(1);
1650
1651   // If neither operand is a SELECT_CC, give up.
1652   if (Sel.getOpcode() != ISD::SELECT_CC)
1653     std::swap(Sel, Other);
1654   if (Sel.getOpcode() != ISD::SELECT_CC)
1655     return Op;
1656
1657   // The folding we want to perform is:
1658   // (xor x, (select_cc a, b, cc, 0, -1) )
1659   //   -->
1660   // (csel x, (xor x, -1), cc ...)
1661   //
1662   // The latter will get matched to a CSINV instruction.
1663
1664   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1665   SDValue LHS = Sel.getOperand(0);
1666   SDValue RHS = Sel.getOperand(1);
1667   SDValue TVal = Sel.getOperand(2);
1668   SDValue FVal = Sel.getOperand(3);
1669   SDLoc dl(Sel);
1670
1671   // FIXME: This could be generalized to non-integer comparisons.
1672   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1673     return Op;
1674
1675   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1676   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1677
1678   // The values aren't constants, this isn't the pattern we're looking for.
1679   if (!CFVal || !CTVal)
1680     return Op;
1681
1682   // We can commute the SELECT_CC by inverting the condition.  This
1683   // might be needed to make this fit into a CSINV pattern.
1684   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1685     std::swap(TVal, FVal);
1686     std::swap(CTVal, CFVal);
1687     CC = ISD::getSetCCInverse(CC, true);
1688   }
1689
1690   // If the constants line up, perform the transform!
1691   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1692     SDValue CCVal;
1693     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1694
1695     FVal = Other;
1696     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1697                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1698
1699     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1700                        CCVal, Cmp);
1701   }
1702
1703   return Op;
1704 }
1705
1706 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1707   EVT VT = Op.getValueType();
1708
1709   // Let legalize expand this if it isn't a legal type yet.
1710   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1711     return SDValue();
1712
1713   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1714
1715   unsigned Opc;
1716   bool ExtraOp = false;
1717   switch (Op.getOpcode()) {
1718   default:
1719     llvm_unreachable("Invalid code");
1720   case ISD::ADDC:
1721     Opc = AArch64ISD::ADDS;
1722     break;
1723   case ISD::SUBC:
1724     Opc = AArch64ISD::SUBS;
1725     break;
1726   case ISD::ADDE:
1727     Opc = AArch64ISD::ADCS;
1728     ExtraOp = true;
1729     break;
1730   case ISD::SUBE:
1731     Opc = AArch64ISD::SBCS;
1732     ExtraOp = true;
1733     break;
1734   }
1735
1736   if (!ExtraOp)
1737     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1738   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1739                      Op.getOperand(2));
1740 }
1741
1742 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1743   // Let legalize expand this if it isn't a legal type yet.
1744   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1745     return SDValue();
1746
1747   SDLoc dl(Op);
1748   AArch64CC::CondCode CC;
1749   // The actual operation that sets the overflow or carry flag.
1750   SDValue Value, Overflow;
1751   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1752
1753   // We use 0 and 1 as false and true values.
1754   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1755   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1756
1757   // We use an inverted condition, because the conditional select is inverted
1758   // too. This will allow it to be selected to a single instruction:
1759   // CSINC Wd, WZR, WZR, invert(cond).
1760   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1761   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1762                          CCVal, Overflow);
1763
1764   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1765   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1766 }
1767
1768 // Prefetch operands are:
1769 // 1: Address to prefetch
1770 // 2: bool isWrite
1771 // 3: int locality (0 = no locality ... 3 = extreme locality)
1772 // 4: bool isDataCache
1773 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1774   SDLoc DL(Op);
1775   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1776   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1777   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1778
1779   bool IsStream = !Locality;
1780   // When the locality number is set
1781   if (Locality) {
1782     // The front-end should have filtered out the out-of-range values
1783     assert(Locality <= 3 && "Prefetch locality out-of-range");
1784     // The locality degree is the opposite of the cache speed.
1785     // Put the number the other way around.
1786     // The encoding starts at 0 for level 1
1787     Locality = 3 - Locality;
1788   }
1789
1790   // built the mask value encoding the expected behavior.
1791   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1792                    (!IsData << 3) |     // IsDataCache bit
1793                    (Locality << 1) |    // Cache level bits
1794                    (unsigned)IsStream;  // Stream bit
1795   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1796                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1797 }
1798
1799 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1800                                               SelectionDAG &DAG) const {
1801   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1802
1803   RTLIB::Libcall LC;
1804   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1805
1806   return LowerF128Call(Op, DAG, LC);
1807 }
1808
1809 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1810                                              SelectionDAG &DAG) const {
1811   if (Op.getOperand(0).getValueType() != MVT::f128) {
1812     // It's legal except when f128 is involved
1813     return Op;
1814   }
1815
1816   RTLIB::Libcall LC;
1817   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1818
1819   // FP_ROUND node has a second operand indicating whether it is known to be
1820   // precise. That doesn't take part in the LibCall so we can't directly use
1821   // LowerF128Call.
1822   SDValue SrcVal = Op.getOperand(0);
1823   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1824                      /*isSigned*/ false, SDLoc(Op)).first;
1825 }
1826
1827 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1828   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1829   // Any additional optimization in this function should be recorded
1830   // in the cost tables.
1831   EVT InVT = Op.getOperand(0).getValueType();
1832   EVT VT = Op.getValueType();
1833
1834   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1835     SDLoc dl(Op);
1836     SDValue Cv =
1837         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1838                     Op.getOperand(0));
1839     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1840   }
1841
1842   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1843     SDLoc dl(Op);
1844     MVT ExtVT =
1845         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1846                          VT.getVectorNumElements());
1847     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1848     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1849   }
1850
1851   // Type changing conversions are illegal.
1852   return Op;
1853 }
1854
1855 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1856                                               SelectionDAG &DAG) const {
1857   if (Op.getOperand(0).getValueType().isVector())
1858     return LowerVectorFP_TO_INT(Op, DAG);
1859
1860   // f16 conversions are promoted to f32.
1861   if (Op.getOperand(0).getValueType() == MVT::f16) {
1862     SDLoc dl(Op);
1863     return DAG.getNode(
1864         Op.getOpcode(), dl, Op.getValueType(),
1865         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1866   }
1867
1868   if (Op.getOperand(0).getValueType() != MVT::f128) {
1869     // It's legal except when f128 is involved
1870     return Op;
1871   }
1872
1873   RTLIB::Libcall LC;
1874   if (Op.getOpcode() == ISD::FP_TO_SINT)
1875     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1876   else
1877     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1878
1879   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1880   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1881                      SDLoc(Op)).first;
1882 }
1883
1884 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1885   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1886   // Any additional optimization in this function should be recorded
1887   // in the cost tables.
1888   EVT VT = Op.getValueType();
1889   SDLoc dl(Op);
1890   SDValue In = Op.getOperand(0);
1891   EVT InVT = In.getValueType();
1892
1893   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1894     MVT CastVT =
1895         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1896                          InVT.getVectorNumElements());
1897     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1898     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1899   }
1900
1901   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1902     unsigned CastOpc =
1903         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1904     EVT CastVT = VT.changeVectorElementTypeToInteger();
1905     In = DAG.getNode(CastOpc, dl, CastVT, In);
1906     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1907   }
1908
1909   return Op;
1910 }
1911
1912 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1913                                             SelectionDAG &DAG) const {
1914   if (Op.getValueType().isVector())
1915     return LowerVectorINT_TO_FP(Op, DAG);
1916
1917   // f16 conversions are promoted to f32.
1918   if (Op.getValueType() == MVT::f16) {
1919     SDLoc dl(Op);
1920     return DAG.getNode(
1921         ISD::FP_ROUND, dl, MVT::f16,
1922         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1923         DAG.getIntPtrConstant(0, dl));
1924   }
1925
1926   // i128 conversions are libcalls.
1927   if (Op.getOperand(0).getValueType() == MVT::i128)
1928     return SDValue();
1929
1930   // Other conversions are legal, unless it's to the completely software-based
1931   // fp128.
1932   if (Op.getValueType() != MVT::f128)
1933     return Op;
1934
1935   RTLIB::Libcall LC;
1936   if (Op.getOpcode() == ISD::SINT_TO_FP)
1937     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1938   else
1939     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1940
1941   return LowerF128Call(Op, DAG, LC);
1942 }
1943
1944 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1945                                             SelectionDAG &DAG) const {
1946   // For iOS, we want to call an alternative entry point: __sincos_stret,
1947   // which returns the values in two S / D registers.
1948   SDLoc dl(Op);
1949   SDValue Arg = Op.getOperand(0);
1950   EVT ArgVT = Arg.getValueType();
1951   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1952
1953   ArgListTy Args;
1954   ArgListEntry Entry;
1955
1956   Entry.Node = Arg;
1957   Entry.Ty = ArgTy;
1958   Entry.isSExt = false;
1959   Entry.isZExt = false;
1960   Args.push_back(Entry);
1961
1962   const char *LibcallName =
1963       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1964   SDValue Callee =
1965       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1966
1967   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1968   TargetLowering::CallLoweringInfo CLI(DAG);
1969   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1970     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1971
1972   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1973   return CallResult.first;
1974 }
1975
1976 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1977   if (Op.getValueType() != MVT::f16)
1978     return SDValue();
1979
1980   assert(Op.getOperand(0).getValueType() == MVT::i16);
1981   SDLoc DL(Op);
1982
1983   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1984   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1985   return SDValue(
1986       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1987                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1988       0);
1989 }
1990
1991 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1992   if (OrigVT.getSizeInBits() >= 64)
1993     return OrigVT;
1994
1995   assert(OrigVT.isSimple() && "Expecting a simple value type");
1996
1997   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1998   switch (OrigSimpleTy) {
1999   default: llvm_unreachable("Unexpected Vector Type");
2000   case MVT::v2i8:
2001   case MVT::v2i16:
2002      return MVT::v2i32;
2003   case MVT::v4i8:
2004     return  MVT::v4i16;
2005   }
2006 }
2007
2008 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2009                                                  const EVT &OrigTy,
2010                                                  const EVT &ExtTy,
2011                                                  unsigned ExtOpcode) {
2012   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2013   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2014   // 64-bits we need to insert a new extension so that it will be 64-bits.
2015   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2016   if (OrigTy.getSizeInBits() >= 64)
2017     return N;
2018
2019   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2020   EVT NewVT = getExtensionTo64Bits(OrigTy);
2021
2022   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2023 }
2024
2025 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2026                                    bool isSigned) {
2027   EVT VT = N->getValueType(0);
2028
2029   if (N->getOpcode() != ISD::BUILD_VECTOR)
2030     return false;
2031
2032   for (const SDValue &Elt : N->op_values()) {
2033     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2034       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2035       unsigned HalfSize = EltSize / 2;
2036       if (isSigned) {
2037         if (!isIntN(HalfSize, C->getSExtValue()))
2038           return false;
2039       } else {
2040         if (!isUIntN(HalfSize, C->getZExtValue()))
2041           return false;
2042       }
2043       continue;
2044     }
2045     return false;
2046   }
2047
2048   return true;
2049 }
2050
2051 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2052   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2053     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2054                                              N->getOperand(0)->getValueType(0),
2055                                              N->getValueType(0),
2056                                              N->getOpcode());
2057
2058   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2059   EVT VT = N->getValueType(0);
2060   SDLoc dl(N);
2061   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2062   unsigned NumElts = VT.getVectorNumElements();
2063   MVT TruncVT = MVT::getIntegerVT(EltSize);
2064   SmallVector<SDValue, 8> Ops;
2065   for (unsigned i = 0; i != NumElts; ++i) {
2066     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2067     const APInt &CInt = C->getAPIntValue();
2068     // Element types smaller than 32 bits are not legal, so use i32 elements.
2069     // The values are implicitly truncated so sext vs. zext doesn't matter.
2070     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2071   }
2072   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2073                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2074 }
2075
2076 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2077   if (N->getOpcode() == ISD::SIGN_EXTEND)
2078     return true;
2079   if (isExtendedBUILD_VECTOR(N, DAG, true))
2080     return true;
2081   return false;
2082 }
2083
2084 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2085   if (N->getOpcode() == ISD::ZERO_EXTEND)
2086     return true;
2087   if (isExtendedBUILD_VECTOR(N, DAG, false))
2088     return true;
2089   return false;
2090 }
2091
2092 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2093   unsigned Opcode = N->getOpcode();
2094   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2095     SDNode *N0 = N->getOperand(0).getNode();
2096     SDNode *N1 = N->getOperand(1).getNode();
2097     return N0->hasOneUse() && N1->hasOneUse() &&
2098       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2099   }
2100   return false;
2101 }
2102
2103 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2104   unsigned Opcode = N->getOpcode();
2105   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2106     SDNode *N0 = N->getOperand(0).getNode();
2107     SDNode *N1 = N->getOperand(1).getNode();
2108     return N0->hasOneUse() && N1->hasOneUse() &&
2109       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2110   }
2111   return false;
2112 }
2113
2114 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2115   // Multiplications are only custom-lowered for 128-bit vectors so that
2116   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2117   EVT VT = Op.getValueType();
2118   assert(VT.is128BitVector() && VT.isInteger() &&
2119          "unexpected type for custom-lowering ISD::MUL");
2120   SDNode *N0 = Op.getOperand(0).getNode();
2121   SDNode *N1 = Op.getOperand(1).getNode();
2122   unsigned NewOpc = 0;
2123   bool isMLA = false;
2124   bool isN0SExt = isSignExtended(N0, DAG);
2125   bool isN1SExt = isSignExtended(N1, DAG);
2126   if (isN0SExt && isN1SExt)
2127     NewOpc = AArch64ISD::SMULL;
2128   else {
2129     bool isN0ZExt = isZeroExtended(N0, DAG);
2130     bool isN1ZExt = isZeroExtended(N1, DAG);
2131     if (isN0ZExt && isN1ZExt)
2132       NewOpc = AArch64ISD::UMULL;
2133     else if (isN1SExt || isN1ZExt) {
2134       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2135       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2136       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2137         NewOpc = AArch64ISD::SMULL;
2138         isMLA = true;
2139       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2140         NewOpc =  AArch64ISD::UMULL;
2141         isMLA = true;
2142       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2143         std::swap(N0, N1);
2144         NewOpc =  AArch64ISD::UMULL;
2145         isMLA = true;
2146       }
2147     }
2148
2149     if (!NewOpc) {
2150       if (VT == MVT::v2i64)
2151         // Fall through to expand this.  It is not legal.
2152         return SDValue();
2153       else
2154         // Other vector multiplications are legal.
2155         return Op;
2156     }
2157   }
2158
2159   // Legalize to a S/UMULL instruction
2160   SDLoc DL(Op);
2161   SDValue Op0;
2162   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2163   if (!isMLA) {
2164     Op0 = skipExtensionForVectorMULL(N0, DAG);
2165     assert(Op0.getValueType().is64BitVector() &&
2166            Op1.getValueType().is64BitVector() &&
2167            "unexpected types for extended operands to VMULL");
2168     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2169   }
2170   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2171   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2172   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2173   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2174   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2175   EVT Op1VT = Op1.getValueType();
2176   return DAG.getNode(N0->getOpcode(), DL, VT,
2177                      DAG.getNode(NewOpc, DL, VT,
2178                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2179                      DAG.getNode(NewOpc, DL, VT,
2180                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2181 }
2182
2183 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2184                                                      SelectionDAG &DAG) const {
2185   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2186   SDLoc dl(Op);
2187   switch (IntNo) {
2188   default: return SDValue();    // Don't custom lower most intrinsics.
2189   case Intrinsic::aarch64_thread_pointer: {
2190     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2191     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2192   }
2193   case Intrinsic::aarch64_neon_smax:
2194     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2195                        Op.getOperand(1), Op.getOperand(2));
2196   case Intrinsic::aarch64_neon_umax:
2197     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2198                        Op.getOperand(1), Op.getOperand(2));
2199   case Intrinsic::aarch64_neon_smin:
2200     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2201                        Op.getOperand(1), Op.getOperand(2));
2202   case Intrinsic::aarch64_neon_umin:
2203     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2204                        Op.getOperand(1), Op.getOperand(2));
2205   }
2206 }
2207
2208 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2209                                               SelectionDAG &DAG) const {
2210   switch (Op.getOpcode()) {
2211   default:
2212     llvm_unreachable("unimplemented operand");
2213     return SDValue();
2214   case ISD::BITCAST:
2215     return LowerBITCAST(Op, DAG);
2216   case ISD::GlobalAddress:
2217     return LowerGlobalAddress(Op, DAG);
2218   case ISD::GlobalTLSAddress:
2219     return LowerGlobalTLSAddress(Op, DAG);
2220   case ISD::SETCC:
2221     return LowerSETCC(Op, DAG);
2222   case ISD::BR_CC:
2223     return LowerBR_CC(Op, DAG);
2224   case ISD::SELECT:
2225     return LowerSELECT(Op, DAG);
2226   case ISD::SELECT_CC:
2227     return LowerSELECT_CC(Op, DAG);
2228   case ISD::JumpTable:
2229     return LowerJumpTable(Op, DAG);
2230   case ISD::ConstantPool:
2231     return LowerConstantPool(Op, DAG);
2232   case ISD::BlockAddress:
2233     return LowerBlockAddress(Op, DAG);
2234   case ISD::VASTART:
2235     return LowerVASTART(Op, DAG);
2236   case ISD::VACOPY:
2237     return LowerVACOPY(Op, DAG);
2238   case ISD::VAARG:
2239     return LowerVAARG(Op, DAG);
2240   case ISD::ADDC:
2241   case ISD::ADDE:
2242   case ISD::SUBC:
2243   case ISD::SUBE:
2244     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2245   case ISD::SADDO:
2246   case ISD::UADDO:
2247   case ISD::SSUBO:
2248   case ISD::USUBO:
2249   case ISD::SMULO:
2250   case ISD::UMULO:
2251     return LowerXALUO(Op, DAG);
2252   case ISD::FADD:
2253     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2254   case ISD::FSUB:
2255     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2256   case ISD::FMUL:
2257     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2258   case ISD::FDIV:
2259     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2260   case ISD::FP_ROUND:
2261     return LowerFP_ROUND(Op, DAG);
2262   case ISD::FP_EXTEND:
2263     return LowerFP_EXTEND(Op, DAG);
2264   case ISD::FRAMEADDR:
2265     return LowerFRAMEADDR(Op, DAG);
2266   case ISD::RETURNADDR:
2267     return LowerRETURNADDR(Op, DAG);
2268   case ISD::INSERT_VECTOR_ELT:
2269     return LowerINSERT_VECTOR_ELT(Op, DAG);
2270   case ISD::EXTRACT_VECTOR_ELT:
2271     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2272   case ISD::BUILD_VECTOR:
2273     return LowerBUILD_VECTOR(Op, DAG);
2274   case ISD::VECTOR_SHUFFLE:
2275     return LowerVECTOR_SHUFFLE(Op, DAG);
2276   case ISD::EXTRACT_SUBVECTOR:
2277     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2278   case ISD::SRA:
2279   case ISD::SRL:
2280   case ISD::SHL:
2281     return LowerVectorSRA_SRL_SHL(Op, DAG);
2282   case ISD::SHL_PARTS:
2283     return LowerShiftLeftParts(Op, DAG);
2284   case ISD::SRL_PARTS:
2285   case ISD::SRA_PARTS:
2286     return LowerShiftRightParts(Op, DAG);
2287   case ISD::CTPOP:
2288     return LowerCTPOP(Op, DAG);
2289   case ISD::FCOPYSIGN:
2290     return LowerFCOPYSIGN(Op, DAG);
2291   case ISD::AND:
2292     return LowerVectorAND(Op, DAG);
2293   case ISD::OR:
2294     return LowerVectorOR(Op, DAG);
2295   case ISD::XOR:
2296     return LowerXOR(Op, DAG);
2297   case ISD::PREFETCH:
2298     return LowerPREFETCH(Op, DAG);
2299   case ISD::SINT_TO_FP:
2300   case ISD::UINT_TO_FP:
2301     return LowerINT_TO_FP(Op, DAG);
2302   case ISD::FP_TO_SINT:
2303   case ISD::FP_TO_UINT:
2304     return LowerFP_TO_INT(Op, DAG);
2305   case ISD::FSINCOS:
2306     return LowerFSINCOS(Op, DAG);
2307   case ISD::MUL:
2308     return LowerMUL(Op, DAG);
2309   case ISD::INTRINSIC_WO_CHAIN:
2310     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2311   }
2312 }
2313
2314 /// getFunctionAlignment - Return the Log2 alignment of this function.
2315 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2316   return 2;
2317 }
2318
2319 //===----------------------------------------------------------------------===//
2320 //                      Calling Convention Implementation
2321 //===----------------------------------------------------------------------===//
2322
2323 #include "AArch64GenCallingConv.inc"
2324
2325 /// Selects the correct CCAssignFn for a given CallingConvention value.
2326 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2327                                                      bool IsVarArg) const {
2328   switch (CC) {
2329   default:
2330     llvm_unreachable("Unsupported calling convention.");
2331   case CallingConv::WebKit_JS:
2332     return CC_AArch64_WebKit_JS;
2333   case CallingConv::GHC:
2334     return CC_AArch64_GHC;
2335   case CallingConv::C:
2336   case CallingConv::Fast:
2337     if (!Subtarget->isTargetDarwin())
2338       return CC_AArch64_AAPCS;
2339     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2340   }
2341 }
2342
2343 SDValue AArch64TargetLowering::LowerFormalArguments(
2344     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2345     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2346     SmallVectorImpl<SDValue> &InVals) const {
2347   MachineFunction &MF = DAG.getMachineFunction();
2348   MachineFrameInfo *MFI = MF.getFrameInfo();
2349
2350   // Assign locations to all of the incoming arguments.
2351   SmallVector<CCValAssign, 16> ArgLocs;
2352   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2353                  *DAG.getContext());
2354
2355   // At this point, Ins[].VT may already be promoted to i32. To correctly
2356   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2357   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2358   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2359   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2360   // LocVT.
2361   unsigned NumArgs = Ins.size();
2362   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2363   unsigned CurArgIdx = 0;
2364   for (unsigned i = 0; i != NumArgs; ++i) {
2365     MVT ValVT = Ins[i].VT;
2366     if (Ins[i].isOrigArg()) {
2367       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2368       CurArgIdx = Ins[i].getOrigArgIndex();
2369
2370       // Get type of the original argument.
2371       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2372                                   /*AllowUnknown*/ true);
2373       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2374       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2375       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2376         ValVT = MVT::i8;
2377       else if (ActualMVT == MVT::i16)
2378         ValVT = MVT::i16;
2379     }
2380     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2381     bool Res =
2382         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2383     assert(!Res && "Call operand has unhandled type");
2384     (void)Res;
2385   }
2386   assert(ArgLocs.size() == Ins.size());
2387   SmallVector<SDValue, 16> ArgValues;
2388   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2389     CCValAssign &VA = ArgLocs[i];
2390
2391     if (Ins[i].Flags.isByVal()) {
2392       // Byval is used for HFAs in the PCS, but the system should work in a
2393       // non-compliant manner for larger structs.
2394       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2395       int Size = Ins[i].Flags.getByValSize();
2396       unsigned NumRegs = (Size + 7) / 8;
2397
2398       // FIXME: This works on big-endian for composite byvals, which are the common
2399       // case. It should also work for fundamental types too.
2400       unsigned FrameIdx =
2401         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2402       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2403       InVals.push_back(FrameIdxN);
2404
2405       continue;
2406     }
2407     
2408     if (VA.isRegLoc()) {
2409       // Arguments stored in registers.
2410       EVT RegVT = VA.getLocVT();
2411
2412       SDValue ArgValue;
2413       const TargetRegisterClass *RC;
2414
2415       if (RegVT == MVT::i32)
2416         RC = &AArch64::GPR32RegClass;
2417       else if (RegVT == MVT::i64)
2418         RC = &AArch64::GPR64RegClass;
2419       else if (RegVT == MVT::f16)
2420         RC = &AArch64::FPR16RegClass;
2421       else if (RegVT == MVT::f32)
2422         RC = &AArch64::FPR32RegClass;
2423       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2424         RC = &AArch64::FPR64RegClass;
2425       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2426         RC = &AArch64::FPR128RegClass;
2427       else
2428         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2429
2430       // Transform the arguments in physical registers into virtual ones.
2431       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2432       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2433
2434       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2435       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2436       // truncate to the right size.
2437       switch (VA.getLocInfo()) {
2438       default:
2439         llvm_unreachable("Unknown loc info!");
2440       case CCValAssign::Full:
2441         break;
2442       case CCValAssign::BCvt:
2443         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2444         break;
2445       case CCValAssign::AExt:
2446       case CCValAssign::SExt:
2447       case CCValAssign::ZExt:
2448         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2449         // nodes after our lowering.
2450         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2451         break;
2452       }
2453
2454       InVals.push_back(ArgValue);
2455
2456     } else { // VA.isRegLoc()
2457       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2458       unsigned ArgOffset = VA.getLocMemOffset();
2459       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2460
2461       uint32_t BEAlign = 0;
2462       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2463           !Ins[i].Flags.isInConsecutiveRegs())
2464         BEAlign = 8 - ArgSize;
2465
2466       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2467
2468       // Create load nodes to retrieve arguments from the stack.
2469       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2470       SDValue ArgValue;
2471
2472       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2473       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2474       MVT MemVT = VA.getValVT();
2475
2476       switch (VA.getLocInfo()) {
2477       default:
2478         break;
2479       case CCValAssign::BCvt:
2480         MemVT = VA.getLocVT();
2481         break;
2482       case CCValAssign::SExt:
2483         ExtType = ISD::SEXTLOAD;
2484         break;
2485       case CCValAssign::ZExt:
2486         ExtType = ISD::ZEXTLOAD;
2487         break;
2488       case CCValAssign::AExt:
2489         ExtType = ISD::EXTLOAD;
2490         break;
2491       }
2492
2493       ArgValue = DAG.getExtLoad(
2494           ExtType, DL, VA.getLocVT(), Chain, FIN,
2495           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2496           MemVT, false, false, false, 0);
2497
2498       InVals.push_back(ArgValue);
2499     }
2500   }
2501
2502   // varargs
2503   if (isVarArg) {
2504     if (!Subtarget->isTargetDarwin()) {
2505       // The AAPCS variadic function ABI is identical to the non-variadic
2506       // one. As a result there may be more arguments in registers and we should
2507       // save them for future reference.
2508       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2509     }
2510
2511     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2512     // This will point to the next argument passed via stack.
2513     unsigned StackOffset = CCInfo.getNextStackOffset();
2514     // We currently pass all varargs at 8-byte alignment.
2515     StackOffset = ((StackOffset + 7) & ~7);
2516     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2517   }
2518
2519   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2520   unsigned StackArgSize = CCInfo.getNextStackOffset();
2521   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2522   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2523     // This is a non-standard ABI so by fiat I say we're allowed to make full
2524     // use of the stack area to be popped, which must be aligned to 16 bytes in
2525     // any case:
2526     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2527
2528     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2529     // a multiple of 16.
2530     FuncInfo->setArgumentStackToRestore(StackArgSize);
2531
2532     // This realignment carries over to the available bytes below. Our own
2533     // callers will guarantee the space is free by giving an aligned value to
2534     // CALLSEQ_START.
2535   }
2536   // Even if we're not expected to free up the space, it's useful to know how
2537   // much is there while considering tail calls (because we can reuse it).
2538   FuncInfo->setBytesInStackArgArea(StackArgSize);
2539
2540   return Chain;
2541 }
2542
2543 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2544                                                 SelectionDAG &DAG, SDLoc DL,
2545                                                 SDValue &Chain) const {
2546   MachineFunction &MF = DAG.getMachineFunction();
2547   MachineFrameInfo *MFI = MF.getFrameInfo();
2548   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2549   auto PtrVT = getPointerTy(DAG.getDataLayout());
2550
2551   SmallVector<SDValue, 8> MemOps;
2552
2553   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2554                                           AArch64::X3, AArch64::X4, AArch64::X5,
2555                                           AArch64::X6, AArch64::X7 };
2556   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2557   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2558
2559   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2560   int GPRIdx = 0;
2561   if (GPRSaveSize != 0) {
2562     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2563
2564     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2565
2566     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2567       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2568       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2569       SDValue Store = DAG.getStore(
2570           Val.getValue(1), DL, Val, FIN,
2571           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2572           false, 0);
2573       MemOps.push_back(Store);
2574       FIN =
2575           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2576     }
2577   }
2578   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2579   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2580
2581   if (Subtarget->hasFPARMv8()) {
2582     static const MCPhysReg FPRArgRegs[] = {
2583         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2584         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2585     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2586     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2587
2588     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2589     int FPRIdx = 0;
2590     if (FPRSaveSize != 0) {
2591       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2592
2593       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2594
2595       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2596         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2597         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2598
2599         SDValue Store = DAG.getStore(
2600             Val.getValue(1), DL, Val, FIN,
2601             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2602             false, false, 0);
2603         MemOps.push_back(Store);
2604         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2605                           DAG.getConstant(16, DL, PtrVT));
2606       }
2607     }
2608     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2609     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2610   }
2611
2612   if (!MemOps.empty()) {
2613     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2614   }
2615 }
2616
2617 /// LowerCallResult - Lower the result values of a call into the
2618 /// appropriate copies out of appropriate physical registers.
2619 SDValue AArch64TargetLowering::LowerCallResult(
2620     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2621     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2622     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2623     SDValue ThisVal) const {
2624   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2625                           ? RetCC_AArch64_WebKit_JS
2626                           : RetCC_AArch64_AAPCS;
2627   // Assign locations to each value returned by this call.
2628   SmallVector<CCValAssign, 16> RVLocs;
2629   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2630                  *DAG.getContext());
2631   CCInfo.AnalyzeCallResult(Ins, RetCC);
2632
2633   // Copy all of the result registers out of their specified physreg.
2634   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2635     CCValAssign VA = RVLocs[i];
2636
2637     // Pass 'this' value directly from the argument to return value, to avoid
2638     // reg unit interference
2639     if (i == 0 && isThisReturn) {
2640       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2641              "unexpected return calling convention register assignment");
2642       InVals.push_back(ThisVal);
2643       continue;
2644     }
2645
2646     SDValue Val =
2647         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2648     Chain = Val.getValue(1);
2649     InFlag = Val.getValue(2);
2650
2651     switch (VA.getLocInfo()) {
2652     default:
2653       llvm_unreachable("Unknown loc info!");
2654     case CCValAssign::Full:
2655       break;
2656     case CCValAssign::BCvt:
2657       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2658       break;
2659     }
2660
2661     InVals.push_back(Val);
2662   }
2663
2664   return Chain;
2665 }
2666
2667 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2668     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2669     bool isCalleeStructRet, bool isCallerStructRet,
2670     const SmallVectorImpl<ISD::OutputArg> &Outs,
2671     const SmallVectorImpl<SDValue> &OutVals,
2672     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2673   // For CallingConv::C this function knows whether the ABI needs
2674   // changing. That's not true for other conventions so they will have to opt in
2675   // manually.
2676   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2677     return false;
2678
2679   const MachineFunction &MF = DAG.getMachineFunction();
2680   const Function *CallerF = MF.getFunction();
2681   CallingConv::ID CallerCC = CallerF->getCallingConv();
2682   bool CCMatch = CallerCC == CalleeCC;
2683
2684   // Byval parameters hand the function a pointer directly into the stack area
2685   // we want to reuse during a tail call. Working around this *is* possible (see
2686   // X86) but less efficient and uglier in LowerCall.
2687   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2688                                     e = CallerF->arg_end();
2689        i != e; ++i)
2690     if (i->hasByValAttr())
2691       return false;
2692
2693   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2694     if (IsTailCallConvention(CalleeCC) && CCMatch)
2695       return true;
2696     return false;
2697   }
2698
2699   // Externally-defined functions with weak linkage should not be
2700   // tail-called on AArch64 when the OS does not support dynamic
2701   // pre-emption of symbols, as the AAELF spec requires normal calls
2702   // to undefined weak functions to be replaced with a NOP or jump to the
2703   // next instruction. The behaviour of branch instructions in this
2704   // situation (as used for tail calls) is implementation-defined, so we
2705   // cannot rely on the linker replacing the tail call with a return.
2706   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2707     const GlobalValue *GV = G->getGlobal();
2708     const Triple &TT = getTargetMachine().getTargetTriple();
2709     if (GV->hasExternalWeakLinkage() &&
2710         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2711       return false;
2712   }
2713
2714   // Now we search for cases where we can use a tail call without changing the
2715   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2716   // concept.
2717
2718   // I want anyone implementing a new calling convention to think long and hard
2719   // about this assert.
2720   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2721          "Unexpected variadic calling convention");
2722
2723   if (isVarArg && !Outs.empty()) {
2724     // At least two cases here: if caller is fastcc then we can't have any
2725     // memory arguments (we'd be expected to clean up the stack afterwards). If
2726     // caller is C then we could potentially use its argument area.
2727
2728     // FIXME: for now we take the most conservative of these in both cases:
2729     // disallow all variadic memory operands.
2730     SmallVector<CCValAssign, 16> ArgLocs;
2731     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2732                    *DAG.getContext());
2733
2734     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2735     for (const CCValAssign &ArgLoc : ArgLocs)
2736       if (!ArgLoc.isRegLoc())
2737         return false;
2738   }
2739
2740   // If the calling conventions do not match, then we'd better make sure the
2741   // results are returned in the same way as what the caller expects.
2742   if (!CCMatch) {
2743     SmallVector<CCValAssign, 16> RVLocs1;
2744     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2745                     *DAG.getContext());
2746     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2747
2748     SmallVector<CCValAssign, 16> RVLocs2;
2749     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2750                     *DAG.getContext());
2751     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2752
2753     if (RVLocs1.size() != RVLocs2.size())
2754       return false;
2755     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2756       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2757         return false;
2758       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2759         return false;
2760       if (RVLocs1[i].isRegLoc()) {
2761         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2762           return false;
2763       } else {
2764         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2765           return false;
2766       }
2767     }
2768   }
2769
2770   // Nothing more to check if the callee is taking no arguments
2771   if (Outs.empty())
2772     return true;
2773
2774   SmallVector<CCValAssign, 16> ArgLocs;
2775   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2776                  *DAG.getContext());
2777
2778   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2779
2780   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2781
2782   // If the stack arguments for this call would fit into our own save area then
2783   // the call can be made tail.
2784   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2785 }
2786
2787 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2788                                                    SelectionDAG &DAG,
2789                                                    MachineFrameInfo *MFI,
2790                                                    int ClobberedFI) const {
2791   SmallVector<SDValue, 8> ArgChains;
2792   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2793   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2794
2795   // Include the original chain at the beginning of the list. When this is
2796   // used by target LowerCall hooks, this helps legalize find the
2797   // CALLSEQ_BEGIN node.
2798   ArgChains.push_back(Chain);
2799
2800   // Add a chain value for each stack argument corresponding
2801   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2802                             UE = DAG.getEntryNode().getNode()->use_end();
2803        U != UE; ++U)
2804     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2805       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2806         if (FI->getIndex() < 0) {
2807           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2808           int64_t InLastByte = InFirstByte;
2809           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2810
2811           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2812               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2813             ArgChains.push_back(SDValue(L, 1));
2814         }
2815
2816   // Build a tokenfactor for all the chains.
2817   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2818 }
2819
2820 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2821                                                    bool TailCallOpt) const {
2822   return CallCC == CallingConv::Fast && TailCallOpt;
2823 }
2824
2825 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2826   return CallCC == CallingConv::Fast;
2827 }
2828
2829 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2830 /// and add input and output parameter nodes.
2831 SDValue
2832 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2833                                  SmallVectorImpl<SDValue> &InVals) const {
2834   SelectionDAG &DAG = CLI.DAG;
2835   SDLoc &DL = CLI.DL;
2836   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2837   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2838   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2839   SDValue Chain = CLI.Chain;
2840   SDValue Callee = CLI.Callee;
2841   bool &IsTailCall = CLI.IsTailCall;
2842   CallingConv::ID CallConv = CLI.CallConv;
2843   bool IsVarArg = CLI.IsVarArg;
2844
2845   MachineFunction &MF = DAG.getMachineFunction();
2846   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2847   bool IsThisReturn = false;
2848
2849   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2850   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2851   bool IsSibCall = false;
2852
2853   if (IsTailCall) {
2854     // Check if it's really possible to do a tail call.
2855     IsTailCall = isEligibleForTailCallOptimization(
2856         Callee, CallConv, IsVarArg, IsStructRet,
2857         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2858     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2859       report_fatal_error("failed to perform tail call elimination on a call "
2860                          "site marked musttail");
2861
2862     // A sibling call is one where we're under the usual C ABI and not planning
2863     // to change that but can still do a tail call:
2864     if (!TailCallOpt && IsTailCall)
2865       IsSibCall = true;
2866
2867     if (IsTailCall)
2868       ++NumTailCalls;
2869   }
2870
2871   // Analyze operands of the call, assigning locations to each operand.
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2874                  *DAG.getContext());
2875
2876   if (IsVarArg) {
2877     // Handle fixed and variable vector arguments differently.
2878     // Variable vector arguments always go into memory.
2879     unsigned NumArgs = Outs.size();
2880
2881     for (unsigned i = 0; i != NumArgs; ++i) {
2882       MVT ArgVT = Outs[i].VT;
2883       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2884       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2885                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2886       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2887       assert(!Res && "Call operand has unhandled type");
2888       (void)Res;
2889     }
2890   } else {
2891     // At this point, Outs[].VT may already be promoted to i32. To correctly
2892     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2893     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2894     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2895     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2896     // LocVT.
2897     unsigned NumArgs = Outs.size();
2898     for (unsigned i = 0; i != NumArgs; ++i) {
2899       MVT ValVT = Outs[i].VT;
2900       // Get type of the original argument.
2901       EVT ActualVT = getValueType(DAG.getDataLayout(),
2902                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2903                                   /*AllowUnknown*/ true);
2904       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2905       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2906       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2907       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2908         ValVT = MVT::i8;
2909       else if (ActualMVT == MVT::i16)
2910         ValVT = MVT::i16;
2911
2912       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2913       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2914       assert(!Res && "Call operand has unhandled type");
2915       (void)Res;
2916     }
2917   }
2918
2919   // Get a count of how many bytes are to be pushed on the stack.
2920   unsigned NumBytes = CCInfo.getNextStackOffset();
2921
2922   if (IsSibCall) {
2923     // Since we're not changing the ABI to make this a tail call, the memory
2924     // operands are already available in the caller's incoming argument space.
2925     NumBytes = 0;
2926   }
2927
2928   // FPDiff is the byte offset of the call's argument area from the callee's.
2929   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2930   // by this amount for a tail call. In a sibling call it must be 0 because the
2931   // caller will deallocate the entire stack and the callee still expects its
2932   // arguments to begin at SP+0. Completely unused for non-tail calls.
2933   int FPDiff = 0;
2934
2935   if (IsTailCall && !IsSibCall) {
2936     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2937
2938     // Since callee will pop argument stack as a tail call, we must keep the
2939     // popped size 16-byte aligned.
2940     NumBytes = RoundUpToAlignment(NumBytes, 16);
2941
2942     // FPDiff will be negative if this tail call requires more space than we
2943     // would automatically have in our incoming argument space. Positive if we
2944     // can actually shrink the stack.
2945     FPDiff = NumReusableBytes - NumBytes;
2946
2947     // The stack pointer must be 16-byte aligned at all times it's used for a
2948     // memory operation, which in practice means at *all* times and in
2949     // particular across call boundaries. Therefore our own arguments started at
2950     // a 16-byte aligned SP and the delta applied for the tail call should
2951     // satisfy the same constraint.
2952     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2953   }
2954
2955   // Adjust the stack pointer for the new arguments...
2956   // These operations are automatically eliminated by the prolog/epilog pass
2957   if (!IsSibCall)
2958     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2959                                                               true),
2960                                  DL);
2961
2962   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2963                                         getPointerTy(DAG.getDataLayout()));
2964
2965   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2966   SmallVector<SDValue, 8> MemOpChains;
2967   auto PtrVT = getPointerTy(DAG.getDataLayout());
2968
2969   // Walk the register/memloc assignments, inserting copies/loads.
2970   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2971        ++i, ++realArgIdx) {
2972     CCValAssign &VA = ArgLocs[i];
2973     SDValue Arg = OutVals[realArgIdx];
2974     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2975
2976     // Promote the value if needed.
2977     switch (VA.getLocInfo()) {
2978     default:
2979       llvm_unreachable("Unknown loc info!");
2980     case CCValAssign::Full:
2981       break;
2982     case CCValAssign::SExt:
2983       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2984       break;
2985     case CCValAssign::ZExt:
2986       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2987       break;
2988     case CCValAssign::AExt:
2989       if (Outs[realArgIdx].ArgVT == MVT::i1) {
2990         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2991         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2992         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2993       }
2994       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2995       break;
2996     case CCValAssign::BCvt:
2997       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2998       break;
2999     case CCValAssign::FPExt:
3000       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3001       break;
3002     }
3003
3004     if (VA.isRegLoc()) {
3005       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3006         assert(VA.getLocVT() == MVT::i64 &&
3007                "unexpected calling convention register assignment");
3008         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3009                "unexpected use of 'returned'");
3010         IsThisReturn = true;
3011       }
3012       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3013     } else {
3014       assert(VA.isMemLoc());
3015
3016       SDValue DstAddr;
3017       MachinePointerInfo DstInfo;
3018
3019       // FIXME: This works on big-endian for composite byvals, which are the
3020       // common case. It should also work for fundamental types too.
3021       uint32_t BEAlign = 0;
3022       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3023                                         : VA.getValVT().getSizeInBits();
3024       OpSize = (OpSize + 7) / 8;
3025       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3026           !Flags.isInConsecutiveRegs()) {
3027         if (OpSize < 8)
3028           BEAlign = 8 - OpSize;
3029       }
3030       unsigned LocMemOffset = VA.getLocMemOffset();
3031       int32_t Offset = LocMemOffset + BEAlign;
3032       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3033       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3034
3035       if (IsTailCall) {
3036         Offset = Offset + FPDiff;
3037         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3038
3039         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3040         DstInfo =
3041             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3042
3043         // Make sure any stack arguments overlapping with where we're storing
3044         // are loaded before this eventual operation. Otherwise they'll be
3045         // clobbered.
3046         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3047       } else {
3048         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3049
3050         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3051         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3052                                                LocMemOffset);
3053       }
3054
3055       if (Outs[i].Flags.isByVal()) {
3056         SDValue SizeNode =
3057             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3058         SDValue Cpy = DAG.getMemcpy(
3059             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3060             /*isVol = */ false, /*AlwaysInline = */ false,
3061             /*isTailCall = */ false,
3062             DstInfo, MachinePointerInfo());
3063
3064         MemOpChains.push_back(Cpy);
3065       } else {
3066         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3067         // promoted to a legal register type i32, we should truncate Arg back to
3068         // i1/i8/i16.
3069         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3070             VA.getValVT() == MVT::i16)
3071           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3072
3073         SDValue Store =
3074             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3075         MemOpChains.push_back(Store);
3076       }
3077     }
3078   }
3079
3080   if (!MemOpChains.empty())
3081     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3082
3083   // Build a sequence of copy-to-reg nodes chained together with token chain
3084   // and flag operands which copy the outgoing args into the appropriate regs.
3085   SDValue InFlag;
3086   for (auto &RegToPass : RegsToPass) {
3087     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3088                              RegToPass.second, InFlag);
3089     InFlag = Chain.getValue(1);
3090   }
3091
3092   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3093   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3094   // node so that legalize doesn't hack it.
3095   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3096       Subtarget->isTargetMachO()) {
3097     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3098       const GlobalValue *GV = G->getGlobal();
3099       bool InternalLinkage = GV->hasInternalLinkage();
3100       if (InternalLinkage)
3101         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3102       else {
3103         Callee =
3104             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3105         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3106       }
3107     } else if (ExternalSymbolSDNode *S =
3108                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3109       const char *Sym = S->getSymbol();
3110       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3111       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3112     }
3113   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3114     const GlobalValue *GV = G->getGlobal();
3115     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3116   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3117     const char *Sym = S->getSymbol();
3118     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3119   }
3120
3121   // We don't usually want to end the call-sequence here because we would tidy
3122   // the frame up *after* the call, however in the ABI-changing tail-call case
3123   // we've carefully laid out the parameters so that when sp is reset they'll be
3124   // in the correct location.
3125   if (IsTailCall && !IsSibCall) {
3126     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3127                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3128     InFlag = Chain.getValue(1);
3129   }
3130
3131   std::vector<SDValue> Ops;
3132   Ops.push_back(Chain);
3133   Ops.push_back(Callee);
3134
3135   if (IsTailCall) {
3136     // Each tail call may have to adjust the stack by a different amount, so
3137     // this information must travel along with the operation for eventual
3138     // consumption by emitEpilogue.
3139     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3140   }
3141
3142   // Add argument registers to the end of the list so that they are known live
3143   // into the call.
3144   for (auto &RegToPass : RegsToPass)
3145     Ops.push_back(DAG.getRegister(RegToPass.first,
3146                                   RegToPass.second.getValueType()));
3147
3148   // Add a register mask operand representing the call-preserved registers.
3149   const uint32_t *Mask;
3150   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3151   if (IsThisReturn) {
3152     // For 'this' returns, use the X0-preserving mask if applicable
3153     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3154     if (!Mask) {
3155       IsThisReturn = false;
3156       Mask = TRI->getCallPreservedMask(MF, CallConv);
3157     }
3158   } else
3159     Mask = TRI->getCallPreservedMask(MF, CallConv);
3160
3161   assert(Mask && "Missing call preserved mask for calling convention");
3162   Ops.push_back(DAG.getRegisterMask(Mask));
3163
3164   if (InFlag.getNode())
3165     Ops.push_back(InFlag);
3166
3167   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168
3169   // If we're doing a tall call, use a TC_RETURN here rather than an
3170   // actual call instruction.
3171   if (IsTailCall) {
3172     MF.getFrameInfo()->setHasTailCall();
3173     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3174   }
3175
3176   // Returns a chain and a flag for retval copy to use.
3177   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3178   InFlag = Chain.getValue(1);
3179
3180   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3181                                 ? RoundUpToAlignment(NumBytes, 16)
3182                                 : 0;
3183
3184   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3185                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3186                              InFlag, DL);
3187   if (!Ins.empty())
3188     InFlag = Chain.getValue(1);
3189
3190   // Handle result values, copying them out of physregs into vregs that we
3191   // return.
3192   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3193                          InVals, IsThisReturn,
3194                          IsThisReturn ? OutVals[0] : SDValue());
3195 }
3196
3197 bool AArch64TargetLowering::CanLowerReturn(
3198     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3199     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3200   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3201                           ? RetCC_AArch64_WebKit_JS
3202                           : RetCC_AArch64_AAPCS;
3203   SmallVector<CCValAssign, 16> RVLocs;
3204   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3205   return CCInfo.CheckReturn(Outs, RetCC);
3206 }
3207
3208 SDValue
3209 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3210                                    bool isVarArg,
3211                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3212                                    const SmallVectorImpl<SDValue> &OutVals,
3213                                    SDLoc DL, SelectionDAG &DAG) const {
3214   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3215                           ? RetCC_AArch64_WebKit_JS
3216                           : RetCC_AArch64_AAPCS;
3217   SmallVector<CCValAssign, 16> RVLocs;
3218   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3219                  *DAG.getContext());
3220   CCInfo.AnalyzeReturn(Outs, RetCC);
3221
3222   // Copy the result values into the output registers.
3223   SDValue Flag;
3224   SmallVector<SDValue, 4> RetOps(1, Chain);
3225   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3226        ++i, ++realRVLocIdx) {
3227     CCValAssign &VA = RVLocs[i];
3228     assert(VA.isRegLoc() && "Can only return in registers!");
3229     SDValue Arg = OutVals[realRVLocIdx];
3230
3231     switch (VA.getLocInfo()) {
3232     default:
3233       llvm_unreachable("Unknown loc info!");
3234     case CCValAssign::Full:
3235       if (Outs[i].ArgVT == MVT::i1) {
3236         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3237         // value. This is strictly redundant on Darwin (which uses "zeroext
3238         // i1"), but will be optimised out before ISel.
3239         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3240         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3241       }
3242       break;
3243     case CCValAssign::BCvt:
3244       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3245       break;
3246     }
3247
3248     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3249     Flag = Chain.getValue(1);
3250     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3251   }
3252
3253   RetOps[0] = Chain; // Update chain.
3254
3255   // Add the flag if we have it.
3256   if (Flag.getNode())
3257     RetOps.push_back(Flag);
3258
3259   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3260 }
3261
3262 //===----------------------------------------------------------------------===//
3263 //  Other Lowering Code
3264 //===----------------------------------------------------------------------===//
3265
3266 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3267                                                   SelectionDAG &DAG) const {
3268   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3269   SDLoc DL(Op);
3270   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3271   const GlobalValue *GV = GN->getGlobal();
3272   unsigned char OpFlags =
3273       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3274
3275   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3276          "unexpected offset in global node");
3277
3278   // This also catched the large code model case for Darwin.
3279   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3280     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3281     // FIXME: Once remat is capable of dealing with instructions with register
3282     // operands, expand this into two nodes instead of using a wrapper node.
3283     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3284   }
3285
3286   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3287     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3288            "use of MO_CONSTPOOL only supported on small model");
3289     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3290     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3291     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3292     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3293     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3294     SDValue GlobalAddr = DAG.getLoad(
3295         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3296         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3297         /*isVolatile=*/false,
3298         /*isNonTemporal=*/true,
3299         /*isInvariant=*/true, 8);
3300     if (GN->getOffset() != 0)
3301       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3302                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3303     return GlobalAddr;
3304   }
3305
3306   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3307     const unsigned char MO_NC = AArch64II::MO_NC;
3308     return DAG.getNode(
3309         AArch64ISD::WrapperLarge, DL, PtrVT,
3310         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3311         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3312         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3313         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3314   } else {
3315     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3316     // the only correct model on Darwin.
3317     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3318                                             OpFlags | AArch64II::MO_PAGE);
3319     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3320     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3321
3322     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3323     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3324   }
3325 }
3326
3327 /// \brief Convert a TLS address reference into the correct sequence of loads
3328 /// and calls to compute the variable's address (for Darwin, currently) and
3329 /// return an SDValue containing the final node.
3330
3331 /// Darwin only has one TLS scheme which must be capable of dealing with the
3332 /// fully general situation, in the worst case. This means:
3333 ///     + "extern __thread" declaration.
3334 ///     + Defined in a possibly unknown dynamic library.
3335 ///
3336 /// The general system is that each __thread variable has a [3 x i64] descriptor
3337 /// which contains information used by the runtime to calculate the address. The
3338 /// only part of this the compiler needs to know about is the first xword, which
3339 /// contains a function pointer that must be called with the address of the
3340 /// entire descriptor in "x0".
3341 ///
3342 /// Since this descriptor may be in a different unit, in general even the
3343 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3344 /// is:
3345 ///     adrp x0, _var@TLVPPAGE
3346 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3347 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3348 ///                                      ; the function pointer
3349 ///     blr x1                           ; Uses descriptor address in x0
3350 ///     ; Address of _var is now in x0.
3351 ///
3352 /// If the address of _var's descriptor *is* known to the linker, then it can
3353 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3354 /// a slight efficiency gain.
3355 SDValue
3356 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3357                                                    SelectionDAG &DAG) const {
3358   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3359
3360   SDLoc DL(Op);
3361   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3362   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3363
3364   SDValue TLVPAddr =
3365       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3366   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3367
3368   // The first entry in the descriptor is a function pointer that we must call
3369   // to obtain the address of the variable.
3370   SDValue Chain = DAG.getEntryNode();
3371   SDValue FuncTLVGet =
3372       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3373                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3374                   true, true, 8);
3375   Chain = FuncTLVGet.getValue(1);
3376
3377   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3378   MFI->setAdjustsStack(true);
3379
3380   // TLS calls preserve all registers except those that absolutely must be
3381   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3382   // silly).
3383   const uint32_t *Mask =
3384       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3385
3386   // Finally, we can make the call. This is just a degenerate version of a
3387   // normal AArch64 call node: x0 takes the address of the descriptor, and
3388   // returns the address of the variable in this thread.
3389   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3390   Chain =
3391       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3392                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3393                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3394   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3395 }
3396
3397 /// When accessing thread-local variables under either the general-dynamic or
3398 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3399 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3400 /// is a function pointer to carry out the resolution.
3401 ///
3402 /// The sequence is:
3403 ///    adrp  x0, :tlsdesc:var
3404 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3405 ///    add   x0, x0, #:tlsdesc_lo12:var
3406 ///    .tlsdesccall var
3407 ///    blr   x1
3408 ///    (TPIDR_EL0 offset now in x0)
3409 ///
3410 ///  The above sequence must be produced unscheduled, to enable the linker to
3411 ///  optimize/relax this sequence.
3412 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3413 ///  above sequence, and expanded really late in the compilation flow, to ensure
3414 ///  the sequence is produced as per above.
3415 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3416                                                       SelectionDAG &DAG) const {
3417   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3418
3419   SDValue Chain = DAG.getEntryNode();
3420   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3421
3422   SmallVector<SDValue, 2> Ops;
3423   Ops.push_back(Chain);
3424   Ops.push_back(SymAddr);
3425
3426   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3427   SDValue Glue = Chain.getValue(1);
3428
3429   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3430 }
3431
3432 SDValue
3433 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3434                                                 SelectionDAG &DAG) const {
3435   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3436   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3437          "ELF TLS only supported in small memory model");
3438   // Different choices can be made for the maximum size of the TLS area for a
3439   // module. For the small address model, the default TLS size is 16MiB and the
3440   // maximum TLS size is 4GiB.
3441   // FIXME: add -mtls-size command line option and make it control the 16MiB
3442   // vs. 4GiB code sequence generation.
3443   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3444
3445   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3446
3447   if (DAG.getTarget().Options.EmulatedTLS)
3448     return LowerToTLSEmulatedModel(GA, DAG);
3449
3450   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3451     if (Model == TLSModel::LocalDynamic)
3452       Model = TLSModel::GeneralDynamic;
3453   }
3454
3455   SDValue TPOff;
3456   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3457   SDLoc DL(Op);
3458   const GlobalValue *GV = GA->getGlobal();
3459
3460   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3461
3462   if (Model == TLSModel::LocalExec) {
3463     SDValue HiVar = DAG.getTargetGlobalAddress(
3464         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3465     SDValue LoVar = DAG.getTargetGlobalAddress(
3466         GV, DL, PtrVT, 0,
3467         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3468
3469     SDValue TPWithOff_lo =
3470         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3471                                    HiVar,
3472                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3473                 0);
3474     SDValue TPWithOff =
3475         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3476                                    LoVar,
3477                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3478                 0);
3479     return TPWithOff;
3480   } else if (Model == TLSModel::InitialExec) {
3481     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3482     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3483   } else if (Model == TLSModel::LocalDynamic) {
3484     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3485     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3486     // the beginning of the module's TLS region, followed by a DTPREL offset
3487     // calculation.
3488
3489     // These accesses will need deduplicating if there's more than one.
3490     AArch64FunctionInfo *MFI =
3491         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3492     MFI->incNumLocalDynamicTLSAccesses();
3493
3494     // The call needs a relocation too for linker relaxation. It doesn't make
3495     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3496     // the address.
3497     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3498                                                   AArch64II::MO_TLS);
3499
3500     // Now we can calculate the offset from TPIDR_EL0 to this module's
3501     // thread-local area.
3502     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3503
3504     // Now use :dtprel_whatever: operations to calculate this variable's offset
3505     // in its thread-storage area.
3506     SDValue HiVar = DAG.getTargetGlobalAddress(
3507         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3508     SDValue LoVar = DAG.getTargetGlobalAddress(
3509         GV, DL, MVT::i64, 0,
3510         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3511
3512     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3513                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3514                     0);
3515     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3516                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3517                     0);
3518   } else if (Model == TLSModel::GeneralDynamic) {
3519     // The call needs a relocation too for linker relaxation. It doesn't make
3520     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3521     // the address.
3522     SDValue SymAddr =
3523         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3524
3525     // Finally we can make a call to calculate the offset from tpidr_el0.
3526     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3527   } else
3528     llvm_unreachable("Unsupported ELF TLS access model");
3529
3530   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3531 }
3532
3533 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3534                                                      SelectionDAG &DAG) const {
3535   if (Subtarget->isTargetDarwin())
3536     return LowerDarwinGlobalTLSAddress(Op, DAG);
3537   else if (Subtarget->isTargetELF())
3538     return LowerELFGlobalTLSAddress(Op, DAG);
3539
3540   llvm_unreachable("Unexpected platform trying to use TLS");
3541 }
3542 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3543   SDValue Chain = Op.getOperand(0);
3544   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3545   SDValue LHS = Op.getOperand(2);
3546   SDValue RHS = Op.getOperand(3);
3547   SDValue Dest = Op.getOperand(4);
3548   SDLoc dl(Op);
3549
3550   // Handle f128 first, since lowering it will result in comparing the return
3551   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3552   // is expecting to deal with.
3553   if (LHS.getValueType() == MVT::f128) {
3554     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3555
3556     // If softenSetCCOperands returned a scalar, we need to compare the result
3557     // against zero to select between true and false values.
3558     if (!RHS.getNode()) {
3559       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3560       CC = ISD::SETNE;
3561     }
3562   }
3563
3564   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3565   // instruction.
3566   unsigned Opc = LHS.getOpcode();
3567   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3568       cast<ConstantSDNode>(RHS)->isOne() &&
3569       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3570        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3571     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3572            "Unexpected condition code.");
3573     // Only lower legal XALUO ops.
3574     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3575       return SDValue();
3576
3577     // The actual operation with overflow check.
3578     AArch64CC::CondCode OFCC;
3579     SDValue Value, Overflow;
3580     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3581
3582     if (CC == ISD::SETNE)
3583       OFCC = getInvertedCondCode(OFCC);
3584     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3585
3586     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3587                        Overflow);
3588   }
3589
3590   if (LHS.getValueType().isInteger()) {
3591     assert((LHS.getValueType() == RHS.getValueType()) &&
3592            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3593
3594     // If the RHS of the comparison is zero, we can potentially fold this
3595     // to a specialized branch.
3596     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3597     if (RHSC && RHSC->getZExtValue() == 0) {
3598       if (CC == ISD::SETEQ) {
3599         // See if we can use a TBZ to fold in an AND as well.
3600         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3601         // out of bounds, a late MI-layer pass rewrites branches.
3602         // 403.gcc is an example that hits this case.
3603         if (LHS.getOpcode() == ISD::AND &&
3604             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3605             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3606           SDValue Test = LHS.getOperand(0);
3607           uint64_t Mask = LHS.getConstantOperandVal(1);
3608           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3609                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3610                              Dest);
3611         }
3612
3613         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3614       } else if (CC == ISD::SETNE) {
3615         // See if we can use a TBZ to fold in an AND as well.
3616         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3617         // out of bounds, a late MI-layer pass rewrites branches.
3618         // 403.gcc is an example that hits this case.
3619         if (LHS.getOpcode() == ISD::AND &&
3620             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3621             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3622           SDValue Test = LHS.getOperand(0);
3623           uint64_t Mask = LHS.getConstantOperandVal(1);
3624           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3625                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3626                              Dest);
3627         }
3628
3629         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3630       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3631         // Don't combine AND since emitComparison converts the AND to an ANDS
3632         // (a.k.a. TST) and the test in the test bit and branch instruction
3633         // becomes redundant.  This would also increase register pressure.
3634         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3635         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3636                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3637       }
3638     }
3639     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3640         LHS.getOpcode() != ISD::AND) {
3641       // Don't combine AND since emitComparison converts the AND to an ANDS
3642       // (a.k.a. TST) and the test in the test bit and branch instruction
3643       // becomes redundant.  This would also increase register pressure.
3644       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3645       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3646                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3647     }
3648
3649     SDValue CCVal;
3650     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3651     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3652                        Cmp);
3653   }
3654
3655   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3656
3657   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3658   // clean.  Some of them require two branches to implement.
3659   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3660   AArch64CC::CondCode CC1, CC2;
3661   changeFPCCToAArch64CC(CC, CC1, CC2);
3662   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3663   SDValue BR1 =
3664       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3665   if (CC2 != AArch64CC::AL) {
3666     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3667     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3668                        Cmp);
3669   }
3670
3671   return BR1;
3672 }
3673
3674 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3675                                               SelectionDAG &DAG) const {
3676   EVT VT = Op.getValueType();
3677   SDLoc DL(Op);
3678
3679   SDValue In1 = Op.getOperand(0);
3680   SDValue In2 = Op.getOperand(1);
3681   EVT SrcVT = In2.getValueType();
3682
3683   if (SrcVT.bitsLT(VT))
3684     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3685   else if (SrcVT.bitsGT(VT))
3686     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3687
3688   EVT VecVT;
3689   EVT EltVT;
3690   uint64_t EltMask;
3691   SDValue VecVal1, VecVal2;
3692   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3693     EltVT = MVT::i32;
3694     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3695     EltMask = 0x80000000ULL;
3696
3697     if (!VT.isVector()) {
3698       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3699                                           DAG.getUNDEF(VecVT), In1);
3700       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3701                                           DAG.getUNDEF(VecVT), In2);
3702     } else {
3703       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3704       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3705     }
3706   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3707     EltVT = MVT::i64;
3708     VecVT = MVT::v2i64;
3709
3710     // We want to materialize a mask with the high bit set, but the AdvSIMD
3711     // immediate moves cannot materialize that in a single instruction for
3712     // 64-bit elements. Instead, materialize zero and then negate it.
3713     EltMask = 0;
3714
3715     if (!VT.isVector()) {
3716       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3717                                           DAG.getUNDEF(VecVT), In1);
3718       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, 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 {
3725     llvm_unreachable("Invalid type for copysign!");
3726   }
3727
3728   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3729
3730   // If we couldn't materialize the mask above, then the mask vector will be
3731   // the zero vector, and we need to negate it here.
3732   if (VT == MVT::f64 || VT == MVT::v2f64) {
3733     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3734     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3735     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3736   }
3737
3738   SDValue Sel =
3739       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3740
3741   if (VT == MVT::f32)
3742     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3743   else if (VT == MVT::f64)
3744     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3745   else
3746     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3747 }
3748
3749 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3750   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3751           Attribute::NoImplicitFloat))
3752     return SDValue();
3753
3754   if (!Subtarget->hasNEON())
3755     return SDValue();
3756
3757   // While there is no integer popcount instruction, it can
3758   // be more efficiently lowered to the following sequence that uses
3759   // AdvSIMD registers/instructions as long as the copies to/from
3760   // the AdvSIMD registers are cheap.
3761   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3762   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3763   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3764   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3765   SDValue Val = Op.getOperand(0);
3766   SDLoc DL(Op);
3767   EVT VT = Op.getValueType();
3768
3769   if (VT == MVT::i32)
3770     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3771   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3772
3773   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3774   SDValue UaddLV = DAG.getNode(
3775       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3776       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3777
3778   if (VT == MVT::i64)
3779     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3780   return UaddLV;
3781 }
3782
3783 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3784
3785   if (Op.getValueType().isVector())
3786     return LowerVSETCC(Op, DAG);
3787
3788   SDValue LHS = Op.getOperand(0);
3789   SDValue RHS = Op.getOperand(1);
3790   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3791   SDLoc dl(Op);
3792
3793   // We chose ZeroOrOneBooleanContents, so use zero and one.
3794   EVT VT = Op.getValueType();
3795   SDValue TVal = DAG.getConstant(1, dl, VT);
3796   SDValue FVal = DAG.getConstant(0, dl, VT);
3797
3798   // Handle f128 first, since one possible outcome is a normal integer
3799   // comparison which gets picked up by the next if statement.
3800   if (LHS.getValueType() == MVT::f128) {
3801     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3802
3803     // If softenSetCCOperands returned a scalar, use it.
3804     if (!RHS.getNode()) {
3805       assert(LHS.getValueType() == Op.getValueType() &&
3806              "Unexpected setcc expansion!");
3807       return LHS;
3808     }
3809   }
3810
3811   if (LHS.getValueType().isInteger()) {
3812     SDValue CCVal;
3813     SDValue Cmp =
3814         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3815
3816     // Note that we inverted the condition above, so we reverse the order of
3817     // the true and false operands here.  This will allow the setcc to be
3818     // matched to a single CSINC instruction.
3819     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3820   }
3821
3822   // Now we know we're dealing with FP values.
3823   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824
3825   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3826   // and do the comparison.
3827   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3828
3829   AArch64CC::CondCode CC1, CC2;
3830   changeFPCCToAArch64CC(CC, CC1, CC2);
3831   if (CC2 == AArch64CC::AL) {
3832     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3833     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3834
3835     // Note that we inverted the condition above, so we reverse the order of
3836     // the true and false operands here.  This will allow the setcc to be
3837     // matched to a single CSINC instruction.
3838     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3839   } else {
3840     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3841     // totally clean.  Some of them require two CSELs to implement.  As is in
3842     // this case, we emit the first CSEL and then emit a second using the output
3843     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3844
3845     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3846     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3847     SDValue CS1 =
3848         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3849
3850     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3851     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3852   }
3853 }
3854
3855 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3856                                               SDValue RHS, SDValue TVal,
3857                                               SDValue FVal, SDLoc dl,
3858                                               SelectionDAG &DAG) const {
3859   // Handle f128 first, because it will result in a comparison of some RTLIB
3860   // call result against zero.
3861   if (LHS.getValueType() == MVT::f128) {
3862     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3863
3864     // If softenSetCCOperands returned a scalar, we need to compare the result
3865     // against zero to select between true and false values.
3866     if (!RHS.getNode()) {
3867       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3868       CC = ISD::SETNE;
3869     }
3870   }
3871
3872   // Handle integers first.
3873   if (LHS.getValueType().isInteger()) {
3874     assert((LHS.getValueType() == RHS.getValueType()) &&
3875            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3876
3877     unsigned Opcode = AArch64ISD::CSEL;
3878
3879     // If both the TVal and the FVal are constants, see if we can swap them in
3880     // order to for a CSINV or CSINC out of them.
3881     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3882     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3883
3884     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3885       std::swap(TVal, FVal);
3886       std::swap(CTVal, CFVal);
3887       CC = ISD::getSetCCInverse(CC, true);
3888     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3889       std::swap(TVal, FVal);
3890       std::swap(CTVal, CFVal);
3891       CC = ISD::getSetCCInverse(CC, true);
3892     } else if (TVal.getOpcode() == ISD::XOR) {
3893       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3894       // with a CSINV rather than a CSEL.
3895       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3896
3897       if (CVal && CVal->isAllOnesValue()) {
3898         std::swap(TVal, FVal);
3899         std::swap(CTVal, CFVal);
3900         CC = ISD::getSetCCInverse(CC, true);
3901       }
3902     } else if (TVal.getOpcode() == ISD::SUB) {
3903       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3904       // that we can match with a CSNEG rather than a CSEL.
3905       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3906
3907       if (CVal && CVal->isNullValue()) {
3908         std::swap(TVal, FVal);
3909         std::swap(CTVal, CFVal);
3910         CC = ISD::getSetCCInverse(CC, true);
3911       }
3912     } else if (CTVal && CFVal) {
3913       const int64_t TrueVal = CTVal->getSExtValue();
3914       const int64_t FalseVal = CFVal->getSExtValue();
3915       bool Swap = false;
3916
3917       // If both TVal and FVal are constants, see if FVal is the
3918       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3919       // instead of a CSEL in that case.
3920       if (TrueVal == ~FalseVal) {
3921         Opcode = AArch64ISD::CSINV;
3922       } else if (TrueVal == -FalseVal) {
3923         Opcode = AArch64ISD::CSNEG;
3924       } else if (TVal.getValueType() == MVT::i32) {
3925         // If our operands are only 32-bit wide, make sure we use 32-bit
3926         // arithmetic for the check whether we can use CSINC. This ensures that
3927         // the addition in the check will wrap around properly in case there is
3928         // an overflow (which would not be the case if we do the check with
3929         // 64-bit arithmetic).
3930         const uint32_t TrueVal32 = CTVal->getZExtValue();
3931         const uint32_t FalseVal32 = CFVal->getZExtValue();
3932
3933         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3934           Opcode = AArch64ISD::CSINC;
3935
3936           if (TrueVal32 > FalseVal32) {
3937             Swap = true;
3938           }
3939         }
3940         // 64-bit check whether we can use CSINC.
3941       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3942         Opcode = AArch64ISD::CSINC;
3943
3944         if (TrueVal > FalseVal) {
3945           Swap = true;
3946         }
3947       }
3948
3949       // Swap TVal and FVal if necessary.
3950       if (Swap) {
3951         std::swap(TVal, FVal);
3952         std::swap(CTVal, CFVal);
3953         CC = ISD::getSetCCInverse(CC, true);
3954       }
3955
3956       if (Opcode != AArch64ISD::CSEL) {
3957         // Drop FVal since we can get its value by simply inverting/negating
3958         // TVal.
3959         FVal = TVal;
3960       }
3961     }
3962
3963     SDValue CCVal;
3964     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3965
3966     EVT VT = TVal.getValueType();
3967     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3968   }
3969
3970   // Now we know we're dealing with FP values.
3971   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3972   assert(LHS.getValueType() == RHS.getValueType());
3973   EVT VT = TVal.getValueType();
3974   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3975
3976   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3977   // clean.  Some of them require two CSELs to implement.
3978   AArch64CC::CondCode CC1, CC2;
3979   changeFPCCToAArch64CC(CC, CC1, CC2);
3980   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3981   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3982
3983   // If we need a second CSEL, emit it, using the output of the first as the
3984   // RHS.  We're effectively OR'ing the two CC's together.
3985   if (CC2 != AArch64CC::AL) {
3986     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3987     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3988   }
3989
3990   // Otherwise, return the output of the first CSEL.
3991   return CS1;
3992 }
3993
3994 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3995                                               SelectionDAG &DAG) const {
3996   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3997   SDValue LHS = Op.getOperand(0);
3998   SDValue RHS = Op.getOperand(1);
3999   SDValue TVal = Op.getOperand(2);
4000   SDValue FVal = Op.getOperand(3);
4001   SDLoc DL(Op);
4002   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4003 }
4004
4005 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4006                                            SelectionDAG &DAG) const {
4007   SDValue CCVal = Op->getOperand(0);
4008   SDValue TVal = Op->getOperand(1);
4009   SDValue FVal = Op->getOperand(2);
4010   SDLoc DL(Op);
4011
4012   unsigned Opc = CCVal.getOpcode();
4013   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4014   // instruction.
4015   if (CCVal.getResNo() == 1 &&
4016       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4017        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4018     // Only lower legal XALUO ops.
4019     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4020       return SDValue();
4021
4022     AArch64CC::CondCode OFCC;
4023     SDValue Value, Overflow;
4024     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4025     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4026
4027     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4028                        CCVal, Overflow);
4029   }
4030
4031   // Lower it the same way as we would lower a SELECT_CC node.
4032   ISD::CondCode CC;
4033   SDValue LHS, RHS;
4034   if (CCVal.getOpcode() == ISD::SETCC) {
4035     LHS = CCVal.getOperand(0);
4036     RHS = CCVal.getOperand(1);
4037     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4038   } else {
4039     LHS = CCVal;
4040     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4041     CC = ISD::SETNE;
4042   }
4043   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4044 }
4045
4046 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4047                                               SelectionDAG &DAG) const {
4048   // Jump table entries as PC relative offsets. No additional tweaking
4049   // is necessary here. Just get the address of the jump table.
4050   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4051   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4052   SDLoc DL(Op);
4053
4054   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4055       !Subtarget->isTargetMachO()) {
4056     const unsigned char MO_NC = AArch64II::MO_NC;
4057     return DAG.getNode(
4058         AArch64ISD::WrapperLarge, DL, PtrVT,
4059         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4060         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4061         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4062         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4063                                AArch64II::MO_G0 | MO_NC));
4064   }
4065
4066   SDValue Hi =
4067       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4068   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4069                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4070   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4071   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4072 }
4073
4074 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4075                                                  SelectionDAG &DAG) const {
4076   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4077   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4078   SDLoc DL(Op);
4079
4080   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4081     // Use the GOT for the large code model on iOS.
4082     if (Subtarget->isTargetMachO()) {
4083       SDValue GotAddr = DAG.getTargetConstantPool(
4084           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4085           AArch64II::MO_GOT);
4086       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4087     }
4088
4089     const unsigned char MO_NC = AArch64II::MO_NC;
4090     return DAG.getNode(
4091         AArch64ISD::WrapperLarge, DL, PtrVT,
4092         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4093                                   CP->getOffset(), AArch64II::MO_G3),
4094         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4095                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4096         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4097                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4098         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4099                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4100   } else {
4101     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4102     // ELF, the only valid one on Darwin.
4103     SDValue Hi =
4104         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4105                                   CP->getOffset(), AArch64II::MO_PAGE);
4106     SDValue Lo = DAG.getTargetConstantPool(
4107         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4108         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4109
4110     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4111     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4112   }
4113 }
4114
4115 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4116                                                SelectionDAG &DAG) const {
4117   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4118   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4119   SDLoc DL(Op);
4120   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4121       !Subtarget->isTargetMachO()) {
4122     const unsigned char MO_NC = AArch64II::MO_NC;
4123     return DAG.getNode(
4124         AArch64ISD::WrapperLarge, DL, PtrVT,
4125         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4126         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4127         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4128         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4129   } else {
4130     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4131     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4132                                                              AArch64II::MO_NC);
4133     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4134     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4135   }
4136 }
4137
4138 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4139                                                  SelectionDAG &DAG) const {
4140   AArch64FunctionInfo *FuncInfo =
4141       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4142
4143   SDLoc DL(Op);
4144   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4145                                  getPointerTy(DAG.getDataLayout()));
4146   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4147   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4148                       MachinePointerInfo(SV), false, false, 0);
4149 }
4150
4151 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4152                                                 SelectionDAG &DAG) const {
4153   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4154   // Standard, section B.3.
4155   MachineFunction &MF = DAG.getMachineFunction();
4156   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4157   auto PtrVT = getPointerTy(DAG.getDataLayout());
4158   SDLoc DL(Op);
4159
4160   SDValue Chain = Op.getOperand(0);
4161   SDValue VAList = Op.getOperand(1);
4162   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4163   SmallVector<SDValue, 4> MemOps;
4164
4165   // void *__stack at offset 0
4166   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4167   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4168                                 MachinePointerInfo(SV), false, false, 8));
4169
4170   // void *__gr_top at offset 8
4171   int GPRSize = FuncInfo->getVarArgsGPRSize();
4172   if (GPRSize > 0) {
4173     SDValue GRTop, GRTopAddr;
4174
4175     GRTopAddr =
4176         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4177
4178     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4179     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4180                         DAG.getConstant(GPRSize, DL, PtrVT));
4181
4182     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4183                                   MachinePointerInfo(SV, 8), false, false, 8));
4184   }
4185
4186   // void *__vr_top at offset 16
4187   int FPRSize = FuncInfo->getVarArgsFPRSize();
4188   if (FPRSize > 0) {
4189     SDValue VRTop, VRTopAddr;
4190     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4191                             DAG.getConstant(16, DL, PtrVT));
4192
4193     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4194     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4195                         DAG.getConstant(FPRSize, DL, PtrVT));
4196
4197     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4198                                   MachinePointerInfo(SV, 16), false, false, 8));
4199   }
4200
4201   // int __gr_offs at offset 24
4202   SDValue GROffsAddr =
4203       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4204   MemOps.push_back(DAG.getStore(Chain, DL,
4205                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4206                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4207                                 false, 4));
4208
4209   // int __vr_offs at offset 28
4210   SDValue VROffsAddr =
4211       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4212   MemOps.push_back(DAG.getStore(Chain, DL,
4213                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4214                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4215                                 false, 4));
4216
4217   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4218 }
4219
4220 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4221                                             SelectionDAG &DAG) const {
4222   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4223                                      : LowerAAPCS_VASTART(Op, DAG);
4224 }
4225
4226 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4227                                            SelectionDAG &DAG) const {
4228   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4229   // pointer.
4230   SDLoc DL(Op);
4231   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4232   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4233   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4234
4235   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4236                        Op.getOperand(2),
4237                        DAG.getConstant(VaListSize, DL, MVT::i32),
4238                        8, false, false, false, MachinePointerInfo(DestSV),
4239                        MachinePointerInfo(SrcSV));
4240 }
4241
4242 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4243   assert(Subtarget->isTargetDarwin() &&
4244          "automatic va_arg instruction only works on Darwin");
4245
4246   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4247   EVT VT = Op.getValueType();
4248   SDLoc DL(Op);
4249   SDValue Chain = Op.getOperand(0);
4250   SDValue Addr = Op.getOperand(1);
4251   unsigned Align = Op.getConstantOperandVal(3);
4252   auto PtrVT = getPointerTy(DAG.getDataLayout());
4253
4254   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4255                                false, false, false, 0);
4256   Chain = VAList.getValue(1);
4257
4258   if (Align > 8) {
4259     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4260     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4261                          DAG.getConstant(Align - 1, DL, PtrVT));
4262     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4263                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4264   }
4265
4266   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4267   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4268
4269   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4270   // up to 64 bits.  At the very least, we have to increase the striding of the
4271   // vaargs list to match this, and for FP values we need to introduce
4272   // FP_ROUND nodes as well.
4273   if (VT.isInteger() && !VT.isVector())
4274     ArgSize = 8;
4275   bool NeedFPTrunc = false;
4276   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4277     ArgSize = 8;
4278     NeedFPTrunc = true;
4279   }
4280
4281   // Increment the pointer, VAList, to the next vaarg
4282   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4283                                DAG.getConstant(ArgSize, DL, PtrVT));
4284   // Store the incremented VAList to the legalized pointer
4285   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4286                                  false, false, 0);
4287
4288   // Load the actual argument out of the pointer VAList
4289   if (NeedFPTrunc) {
4290     // Load the value as an f64.
4291     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4292                                  MachinePointerInfo(), false, false, false, 0);
4293     // Round the value down to an f32.
4294     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4295                                    DAG.getIntPtrConstant(1, DL));
4296     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4297     // Merge the rounded value with the chain output of the load.
4298     return DAG.getMergeValues(Ops, DL);
4299   }
4300
4301   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4302                      false, false, 0);
4303 }
4304
4305 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4306                                               SelectionDAG &DAG) const {
4307   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4308   MFI->setFrameAddressIsTaken(true);
4309
4310   EVT VT = Op.getValueType();
4311   SDLoc DL(Op);
4312   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4313   SDValue FrameAddr =
4314       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4315   while (Depth--)
4316     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4317                             MachinePointerInfo(), false, false, false, 0);
4318   return FrameAddr;
4319 }
4320
4321 // FIXME? Maybe this could be a TableGen attribute on some registers and
4322 // this table could be generated automatically from RegInfo.
4323 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4324                                                   SelectionDAG &DAG) const {
4325   unsigned Reg = StringSwitch<unsigned>(RegName)
4326                        .Case("sp", AArch64::SP)
4327                        .Default(0);
4328   if (Reg)
4329     return Reg;
4330   report_fatal_error(Twine("Invalid register name \""
4331                               + StringRef(RegName)  + "\"."));
4332 }
4333
4334 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4335                                                SelectionDAG &DAG) const {
4336   MachineFunction &MF = DAG.getMachineFunction();
4337   MachineFrameInfo *MFI = MF.getFrameInfo();
4338   MFI->setReturnAddressIsTaken(true);
4339
4340   EVT VT = Op.getValueType();
4341   SDLoc DL(Op);
4342   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4343   if (Depth) {
4344     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4345     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4346     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4347                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4348                        MachinePointerInfo(), false, false, false, 0);
4349   }
4350
4351   // Return LR, which contains the return address. Mark it an implicit live-in.
4352   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4353   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4354 }
4355
4356 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4357 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4358 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4359                                                     SelectionDAG &DAG) const {
4360   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4361   EVT VT = Op.getValueType();
4362   unsigned VTBits = VT.getSizeInBits();
4363   SDLoc dl(Op);
4364   SDValue ShOpLo = Op.getOperand(0);
4365   SDValue ShOpHi = Op.getOperand(1);
4366   SDValue ShAmt = Op.getOperand(2);
4367   SDValue ARMcc;
4368   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4369
4370   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4371
4372   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4373                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4374   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4375   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4376                                    DAG.getConstant(VTBits, dl, MVT::i64));
4377   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4378
4379   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4380                                ISD::SETGE, dl, DAG);
4381   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4382
4383   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4384   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4385   SDValue Lo =
4386       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4387
4388   // AArch64 shifts larger than the register width are wrapped rather than
4389   // clamped, so we can't just emit "hi >> x".
4390   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4391   SDValue TrueValHi = Opc == ISD::SRA
4392                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4393                                         DAG.getConstant(VTBits - 1, dl,
4394                                                         MVT::i64))
4395                           : DAG.getConstant(0, dl, VT);
4396   SDValue Hi =
4397       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4398
4399   SDValue Ops[2] = { Lo, Hi };
4400   return DAG.getMergeValues(Ops, dl);
4401 }
4402
4403 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4404 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4405 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4406                                                  SelectionDAG &DAG) const {
4407   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4408   EVT VT = Op.getValueType();
4409   unsigned VTBits = VT.getSizeInBits();
4410   SDLoc dl(Op);
4411   SDValue ShOpLo = Op.getOperand(0);
4412   SDValue ShOpHi = Op.getOperand(1);
4413   SDValue ShAmt = Op.getOperand(2);
4414   SDValue ARMcc;
4415
4416   assert(Op.getOpcode() == ISD::SHL_PARTS);
4417   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4418                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4419   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4420   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4421                                    DAG.getConstant(VTBits, dl, MVT::i64));
4422   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4423   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4424
4425   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4426
4427   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4428                                ISD::SETGE, dl, DAG);
4429   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4430   SDValue Hi =
4431       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4432
4433   // AArch64 shifts of larger than register sizes are wrapped rather than
4434   // clamped, so we can't just emit "lo << a" if a is too big.
4435   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4436   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4437   SDValue Lo =
4438       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4439
4440   SDValue Ops[2] = { Lo, Hi };
4441   return DAG.getMergeValues(Ops, dl);
4442 }
4443
4444 bool AArch64TargetLowering::isOffsetFoldingLegal(
4445     const GlobalAddressSDNode *GA) const {
4446   // The AArch64 target doesn't support folding offsets into global addresses.
4447   return false;
4448 }
4449
4450 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4451   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4452   // FIXME: We should be able to handle f128 as well with a clever lowering.
4453   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4454     return true;
4455
4456   if (VT == MVT::f64)
4457     return AArch64_AM::getFP64Imm(Imm) != -1;
4458   else if (VT == MVT::f32)
4459     return AArch64_AM::getFP32Imm(Imm) != -1;
4460   return false;
4461 }
4462
4463 //===----------------------------------------------------------------------===//
4464 //                          AArch64 Optimization Hooks
4465 //===----------------------------------------------------------------------===//
4466
4467 //===----------------------------------------------------------------------===//
4468 //                          AArch64 Inline Assembly Support
4469 //===----------------------------------------------------------------------===//
4470
4471 // Table of Constraints
4472 // TODO: This is the current set of constraints supported by ARM for the
4473 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4474 //
4475 // r - A general register
4476 // w - An FP/SIMD register of some size in the range v0-v31
4477 // x - An FP/SIMD register of some size in the range v0-v15
4478 // I - Constant that can be used with an ADD instruction
4479 // J - Constant that can be used with a SUB instruction
4480 // K - Constant that can be used with a 32-bit logical instruction
4481 // L - Constant that can be used with a 64-bit logical instruction
4482 // M - Constant that can be used as a 32-bit MOV immediate
4483 // N - Constant that can be used as a 64-bit MOV immediate
4484 // Q - A memory reference with base register and no offset
4485 // S - A symbolic address
4486 // Y - Floating point constant zero
4487 // Z - Integer constant zero
4488 //
4489 //   Note that general register operands will be output using their 64-bit x
4490 // register name, whatever the size of the variable, unless the asm operand
4491 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4492 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4493 // %q modifier.
4494
4495 /// getConstraintType - Given a constraint letter, return the type of
4496 /// constraint it is for this target.
4497 AArch64TargetLowering::ConstraintType
4498 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4499   if (Constraint.size() == 1) {
4500     switch (Constraint[0]) {
4501     default:
4502       break;
4503     case 'z':
4504       return C_Other;
4505     case 'x':
4506     case 'w':
4507       return C_RegisterClass;
4508     // An address with a single base register. Due to the way we
4509     // currently handle addresses it is the same as 'r'.
4510     case 'Q':
4511       return C_Memory;
4512     }
4513   }
4514   return TargetLowering::getConstraintType(Constraint);
4515 }
4516
4517 /// Examine constraint type and operand type and determine a weight value.
4518 /// This object must already have been set up with the operand type
4519 /// and the current alternative constraint selected.
4520 TargetLowering::ConstraintWeight
4521 AArch64TargetLowering::getSingleConstraintMatchWeight(
4522     AsmOperandInfo &info, const char *constraint) const {
4523   ConstraintWeight weight = CW_Invalid;
4524   Value *CallOperandVal = info.CallOperandVal;
4525   // If we don't have a value, we can't do a match,
4526   // but allow it at the lowest weight.
4527   if (!CallOperandVal)
4528     return CW_Default;
4529   Type *type = CallOperandVal->getType();
4530   // Look at the constraint type.
4531   switch (*constraint) {
4532   default:
4533     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4534     break;
4535   case 'x':
4536   case 'w':
4537     if (type->isFloatingPointTy() || type->isVectorTy())
4538       weight = CW_Register;
4539     break;
4540   case 'z':
4541     weight = CW_Constant;
4542     break;
4543   }
4544   return weight;
4545 }
4546
4547 std::pair<unsigned, const TargetRegisterClass *>
4548 AArch64TargetLowering::getRegForInlineAsmConstraint(
4549     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4550   if (Constraint.size() == 1) {
4551     switch (Constraint[0]) {
4552     case 'r':
4553       if (VT.getSizeInBits() == 64)
4554         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4555       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4556     case 'w':
4557       if (VT == MVT::f32)
4558         return std::make_pair(0U, &AArch64::FPR32RegClass);
4559       if (VT.getSizeInBits() == 64)
4560         return std::make_pair(0U, &AArch64::FPR64RegClass);
4561       if (VT.getSizeInBits() == 128)
4562         return std::make_pair(0U, &AArch64::FPR128RegClass);
4563       break;
4564     // The instructions that this constraint is designed for can
4565     // only take 128-bit registers so just use that regclass.
4566     case 'x':
4567       if (VT.getSizeInBits() == 128)
4568         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4569       break;
4570     }
4571   }
4572   if (StringRef("{cc}").equals_lower(Constraint))
4573     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4574
4575   // Use the default implementation in TargetLowering to convert the register
4576   // constraint into a member of a register class.
4577   std::pair<unsigned, const TargetRegisterClass *> Res;
4578   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4579
4580   // Not found as a standard register?
4581   if (!Res.second) {
4582     unsigned Size = Constraint.size();
4583     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4584         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4585       int RegNo;
4586       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4587       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4588         // v0 - v31 are aliases of q0 - q31.
4589         // By default we'll emit v0-v31 for this unless there's a modifier where
4590         // we'll emit the correct register as well.
4591         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4592         Res.second = &AArch64::FPR128RegClass;
4593       }
4594     }
4595   }
4596
4597   return Res;
4598 }
4599
4600 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4601 /// vector.  If it is invalid, don't add anything to Ops.
4602 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4603     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4604     SelectionDAG &DAG) const {
4605   SDValue Result;
4606
4607   // Currently only support length 1 constraints.
4608   if (Constraint.length() != 1)
4609     return;
4610
4611   char ConstraintLetter = Constraint[0];
4612   switch (ConstraintLetter) {
4613   default:
4614     break;
4615
4616   // This set of constraints deal with valid constants for various instructions.
4617   // Validate and return a target constant for them if we can.
4618   case 'z': {
4619     // 'z' maps to xzr or wzr so it needs an input of 0.
4620     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4621     if (!C || C->getZExtValue() != 0)
4622       return;
4623
4624     if (Op.getValueType() == MVT::i64)
4625       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4626     else
4627       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4628     break;
4629   }
4630
4631   case 'I':
4632   case 'J':
4633   case 'K':
4634   case 'L':
4635   case 'M':
4636   case 'N':
4637     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4638     if (!C)
4639       return;
4640
4641     // Grab the value and do some validation.
4642     uint64_t CVal = C->getZExtValue();
4643     switch (ConstraintLetter) {
4644     // The I constraint applies only to simple ADD or SUB immediate operands:
4645     // i.e. 0 to 4095 with optional shift by 12
4646     // The J constraint applies only to ADD or SUB immediates that would be
4647     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4648     // instruction [or vice versa], in other words -1 to -4095 with optional
4649     // left shift by 12.
4650     case 'I':
4651       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4652         break;
4653       return;
4654     case 'J': {
4655       uint64_t NVal = -C->getSExtValue();
4656       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4657         CVal = C->getSExtValue();
4658         break;
4659       }
4660       return;
4661     }
4662     // The K and L constraints apply *only* to logical immediates, including
4663     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4664     // been removed and MOV should be used). So these constraints have to
4665     // distinguish between bit patterns that are valid 32-bit or 64-bit
4666     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4667     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4668     // versa.
4669     case 'K':
4670       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4671         break;
4672       return;
4673     case 'L':
4674       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4675         break;
4676       return;
4677     // The M and N constraints are a superset of K and L respectively, for use
4678     // with the MOV (immediate) alias. As well as the logical immediates they
4679     // also match 32 or 64-bit immediates that can be loaded either using a
4680     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4681     // (M) or 64-bit 0x1234000000000000 (N) etc.
4682     // As a note some of this code is liberally stolen from the asm parser.
4683     case 'M': {
4684       if (!isUInt<32>(CVal))
4685         return;
4686       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4687         break;
4688       if ((CVal & 0xFFFF) == CVal)
4689         break;
4690       if ((CVal & 0xFFFF0000ULL) == CVal)
4691         break;
4692       uint64_t NCVal = ~(uint32_t)CVal;
4693       if ((NCVal & 0xFFFFULL) == NCVal)
4694         break;
4695       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4696         break;
4697       return;
4698     }
4699     case 'N': {
4700       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4701         break;
4702       if ((CVal & 0xFFFFULL) == CVal)
4703         break;
4704       if ((CVal & 0xFFFF0000ULL) == CVal)
4705         break;
4706       if ((CVal & 0xFFFF00000000ULL) == CVal)
4707         break;
4708       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4709         break;
4710       uint64_t NCVal = ~CVal;
4711       if ((NCVal & 0xFFFFULL) == NCVal)
4712         break;
4713       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4714         break;
4715       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4716         break;
4717       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4718         break;
4719       return;
4720     }
4721     default:
4722       return;
4723     }
4724
4725     // All assembler immediates are 64-bit integers.
4726     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4727     break;
4728   }
4729
4730   if (Result.getNode()) {
4731     Ops.push_back(Result);
4732     return;
4733   }
4734
4735   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4736 }
4737
4738 //===----------------------------------------------------------------------===//
4739 //                     AArch64 Advanced SIMD Support
4740 //===----------------------------------------------------------------------===//
4741
4742 /// WidenVector - Given a value in the V64 register class, produce the
4743 /// equivalent value in the V128 register class.
4744 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4745   EVT VT = V64Reg.getValueType();
4746   unsigned NarrowSize = VT.getVectorNumElements();
4747   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4748   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4749   SDLoc DL(V64Reg);
4750
4751   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4752                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4753 }
4754
4755 /// getExtFactor - Determine the adjustment factor for the position when
4756 /// generating an "extract from vector registers" instruction.
4757 static unsigned getExtFactor(SDValue &V) {
4758   EVT EltType = V.getValueType().getVectorElementType();
4759   return EltType.getSizeInBits() / 8;
4760 }
4761
4762 /// NarrowVector - Given a value in the V128 register class, produce the
4763 /// equivalent value in the V64 register class.
4764 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4765   EVT VT = V128Reg.getValueType();
4766   unsigned WideSize = VT.getVectorNumElements();
4767   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4768   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4769   SDLoc DL(V128Reg);
4770
4771   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4772 }
4773
4774 // Gather data to see if the operation can be modelled as a
4775 // shuffle in combination with VEXTs.
4776 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4777                                                   SelectionDAG &DAG) const {
4778   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4779   SDLoc dl(Op);
4780   EVT VT = Op.getValueType();
4781   unsigned NumElts = VT.getVectorNumElements();
4782
4783   struct ShuffleSourceInfo {
4784     SDValue Vec;
4785     unsigned MinElt;
4786     unsigned MaxElt;
4787
4788     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4789     // be compatible with the shuffle we intend to construct. As a result
4790     // ShuffleVec will be some sliding window into the original Vec.
4791     SDValue ShuffleVec;
4792
4793     // Code should guarantee that element i in Vec starts at element "WindowBase
4794     // + i * WindowScale in ShuffleVec".
4795     int WindowBase;
4796     int WindowScale;
4797
4798     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4799     ShuffleSourceInfo(SDValue Vec)
4800         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4801           WindowScale(1) {}
4802   };
4803
4804   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4805   // node.
4806   SmallVector<ShuffleSourceInfo, 2> Sources;
4807   for (unsigned i = 0; i < NumElts; ++i) {
4808     SDValue V = Op.getOperand(i);
4809     if (V.getOpcode() == ISD::UNDEF)
4810       continue;
4811     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4812       // A shuffle can only come from building a vector from various
4813       // elements of other vectors.
4814       return SDValue();
4815     }
4816
4817     // Add this element source to the list if it's not already there.
4818     SDValue SourceVec = V.getOperand(0);
4819     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4820     if (Source == Sources.end())
4821       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4822
4823     // Update the minimum and maximum lane number seen.
4824     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4825     Source->MinElt = std::min(Source->MinElt, EltNo);
4826     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4827   }
4828
4829   // Currently only do something sane when at most two source vectors
4830   // are involved.
4831   if (Sources.size() > 2)
4832     return SDValue();
4833
4834   // Find out the smallest element size among result and two sources, and use
4835   // it as element size to build the shuffle_vector.
4836   EVT SmallestEltTy = VT.getVectorElementType();
4837   for (auto &Source : Sources) {
4838     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4839     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4840       SmallestEltTy = SrcEltTy;
4841     }
4842   }
4843   unsigned ResMultiplier =
4844       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4845   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4846   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4847
4848   // If the source vector is too wide or too narrow, we may nevertheless be able
4849   // to construct a compatible shuffle either by concatenating it with UNDEF or
4850   // extracting a suitable range of elements.
4851   for (auto &Src : Sources) {
4852     EVT SrcVT = Src.ShuffleVec.getValueType();
4853
4854     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4855       continue;
4856
4857     // This stage of the search produces a source with the same element type as
4858     // the original, but with a total width matching the BUILD_VECTOR output.
4859     EVT EltVT = SrcVT.getVectorElementType();
4860     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4861     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4862
4863     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4864       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4865       // We can pad out the smaller vector for free, so if it's part of a
4866       // shuffle...
4867       Src.ShuffleVec =
4868           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4869                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4870       continue;
4871     }
4872
4873     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4874
4875     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4876       // Span too large for a VEXT to cope
4877       return SDValue();
4878     }
4879
4880     if (Src.MinElt >= NumSrcElts) {
4881       // The extraction can just take the second half
4882       Src.ShuffleVec =
4883           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4884                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4885       Src.WindowBase = -NumSrcElts;
4886     } else if (Src.MaxElt < NumSrcElts) {
4887       // The extraction can just take the first half
4888       Src.ShuffleVec =
4889           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4890                       DAG.getConstant(0, dl, MVT::i64));
4891     } else {
4892       // An actual VEXT is needed
4893       SDValue VEXTSrc1 =
4894           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4895                       DAG.getConstant(0, dl, MVT::i64));
4896       SDValue VEXTSrc2 =
4897           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4898                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4899       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4900
4901       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4902                                    VEXTSrc2,
4903                                    DAG.getConstant(Imm, dl, MVT::i32));
4904       Src.WindowBase = -Src.MinElt;
4905     }
4906   }
4907
4908   // Another possible incompatibility occurs from the vector element types. We
4909   // can fix this by bitcasting the source vectors to the same type we intend
4910   // for the shuffle.
4911   for (auto &Src : Sources) {
4912     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4913     if (SrcEltTy == SmallestEltTy)
4914       continue;
4915     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4916     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4917     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4918     Src.WindowBase *= Src.WindowScale;
4919   }
4920
4921   // Final sanity check before we try to actually produce a shuffle.
4922   DEBUG(
4923     for (auto Src : Sources)
4924       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4925   );
4926
4927   // The stars all align, our next step is to produce the mask for the shuffle.
4928   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4929   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4930   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4931     SDValue Entry = Op.getOperand(i);
4932     if (Entry.getOpcode() == ISD::UNDEF)
4933       continue;
4934
4935     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4936     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4937
4938     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4939     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4940     // segment.
4941     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4942     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4943                                VT.getVectorElementType().getSizeInBits());
4944     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4945
4946     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4947     // starting at the appropriate offset.
4948     int *LaneMask = &Mask[i * ResMultiplier];
4949
4950     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4951     ExtractBase += NumElts * (Src - Sources.begin());
4952     for (int j = 0; j < LanesDefined; ++j)
4953       LaneMask[j] = ExtractBase + j;
4954   }
4955
4956   // Final check before we try to produce nonsense...
4957   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4958     return SDValue();
4959
4960   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4961   for (unsigned i = 0; i < Sources.size(); ++i)
4962     ShuffleOps[i] = Sources[i].ShuffleVec;
4963
4964   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4965                                          ShuffleOps[1], &Mask[0]);
4966   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4967 }
4968
4969 // check if an EXT instruction can handle the shuffle mask when the
4970 // vector sources of the shuffle are the same.
4971 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4972   unsigned NumElts = VT.getVectorNumElements();
4973
4974   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4975   if (M[0] < 0)
4976     return false;
4977
4978   Imm = M[0];
4979
4980   // If this is a VEXT shuffle, the immediate value is the index of the first
4981   // element.  The other shuffle indices must be the successive elements after
4982   // the first one.
4983   unsigned ExpectedElt = Imm;
4984   for (unsigned i = 1; i < NumElts; ++i) {
4985     // Increment the expected index.  If it wraps around, just follow it
4986     // back to index zero and keep going.
4987     ++ExpectedElt;
4988     if (ExpectedElt == NumElts)
4989       ExpectedElt = 0;
4990
4991     if (M[i] < 0)
4992       continue; // ignore UNDEF indices
4993     if (ExpectedElt != static_cast<unsigned>(M[i]))
4994       return false;
4995   }
4996
4997   return true;
4998 }
4999
5000 // check if an EXT instruction can handle the shuffle mask when the
5001 // vector sources of the shuffle are different.
5002 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5003                       unsigned &Imm) {
5004   // Look for the first non-undef element.
5005   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5006       [](int Elt) {return Elt >= 0;});
5007
5008   // Benefit form APInt to handle overflow when calculating expected element.
5009   unsigned NumElts = VT.getVectorNumElements();
5010   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5011   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5012   // The following shuffle indices must be the successive elements after the
5013   // first real element.
5014   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5015       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5016   if (FirstWrongElt != M.end())
5017     return false;
5018
5019   // The index of an EXT is the first element if it is not UNDEF.
5020   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5021   // value of the first element.  E.g. 
5022   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5023   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5024   // ExpectedElt is the last mask index plus 1.
5025   Imm = ExpectedElt.getZExtValue();
5026
5027   // There are two difference cases requiring to reverse input vectors.
5028   // For example, for vector <4 x i32> we have the following cases,
5029   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5030   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5031   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5032   // to reverse two input vectors.
5033   if (Imm < NumElts)
5034     ReverseEXT = true;
5035   else
5036     Imm -= NumElts;
5037
5038   return true;
5039 }
5040
5041 /// isREVMask - Check if a vector shuffle corresponds to a REV
5042 /// instruction with the specified blocksize.  (The order of the elements
5043 /// within each block of the vector is reversed.)
5044 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5045   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5046          "Only possible block sizes for REV are: 16, 32, 64");
5047
5048   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5049   if (EltSz == 64)
5050     return false;
5051
5052   unsigned NumElts = VT.getVectorNumElements();
5053   unsigned BlockElts = M[0] + 1;
5054   // If the first shuffle index is UNDEF, be optimistic.
5055   if (M[0] < 0)
5056     BlockElts = BlockSize / EltSz;
5057
5058   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5059     return false;
5060
5061   for (unsigned i = 0; i < NumElts; ++i) {
5062     if (M[i] < 0)
5063       continue; // ignore UNDEF indices
5064     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5065       return false;
5066   }
5067
5068   return true;
5069 }
5070
5071 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5072   unsigned NumElts = VT.getVectorNumElements();
5073   WhichResult = (M[0] == 0 ? 0 : 1);
5074   unsigned Idx = WhichResult * NumElts / 2;
5075   for (unsigned i = 0; i != NumElts; i += 2) {
5076     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5077         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5078       return false;
5079     Idx += 1;
5080   }
5081
5082   return true;
5083 }
5084
5085 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5086   unsigned NumElts = VT.getVectorNumElements();
5087   WhichResult = (M[0] == 0 ? 0 : 1);
5088   for (unsigned i = 0; i != NumElts; ++i) {
5089     if (M[i] < 0)
5090       continue; // ignore UNDEF indices
5091     if ((unsigned)M[i] != 2 * i + WhichResult)
5092       return false;
5093   }
5094
5095   return true;
5096 }
5097
5098 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5099   unsigned NumElts = VT.getVectorNumElements();
5100   WhichResult = (M[0] == 0 ? 0 : 1);
5101   for (unsigned i = 0; i < NumElts; i += 2) {
5102     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5103         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5104       return false;
5105   }
5106   return true;
5107 }
5108
5109 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5110 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5111 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5112 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5113   unsigned NumElts = VT.getVectorNumElements();
5114   WhichResult = (M[0] == 0 ? 0 : 1);
5115   unsigned Idx = WhichResult * NumElts / 2;
5116   for (unsigned i = 0; i != NumElts; i += 2) {
5117     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5118         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5119       return false;
5120     Idx += 1;
5121   }
5122
5123   return true;
5124 }
5125
5126 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5127 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5128 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5129 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5130   unsigned Half = VT.getVectorNumElements() / 2;
5131   WhichResult = (M[0] == 0 ? 0 : 1);
5132   for (unsigned j = 0; j != 2; ++j) {
5133     unsigned Idx = WhichResult;
5134     for (unsigned i = 0; i != Half; ++i) {
5135       int MIdx = M[i + j * Half];
5136       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5137         return false;
5138       Idx += 2;
5139     }
5140   }
5141
5142   return true;
5143 }
5144
5145 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5146 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5147 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5148 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5149   unsigned NumElts = VT.getVectorNumElements();
5150   WhichResult = (M[0] == 0 ? 0 : 1);
5151   for (unsigned i = 0; i < NumElts; i += 2) {
5152     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5153         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5154       return false;
5155   }
5156   return true;
5157 }
5158
5159 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5160                       bool &DstIsLeft, int &Anomaly) {
5161   if (M.size() != static_cast<size_t>(NumInputElements))
5162     return false;
5163
5164   int NumLHSMatch = 0, NumRHSMatch = 0;
5165   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5166
5167   for (int i = 0; i < NumInputElements; ++i) {
5168     if (M[i] == -1) {
5169       ++NumLHSMatch;
5170       ++NumRHSMatch;
5171       continue;
5172     }
5173
5174     if (M[i] == i)
5175       ++NumLHSMatch;
5176     else
5177       LastLHSMismatch = i;
5178
5179     if (M[i] == i + NumInputElements)
5180       ++NumRHSMatch;
5181     else
5182       LastRHSMismatch = i;
5183   }
5184
5185   if (NumLHSMatch == NumInputElements - 1) {
5186     DstIsLeft = true;
5187     Anomaly = LastLHSMismatch;
5188     return true;
5189   } else if (NumRHSMatch == NumInputElements - 1) {
5190     DstIsLeft = false;
5191     Anomaly = LastRHSMismatch;
5192     return true;
5193   }
5194
5195   return false;
5196 }
5197
5198 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5199   if (VT.getSizeInBits() != 128)
5200     return false;
5201
5202   unsigned NumElts = VT.getVectorNumElements();
5203
5204   for (int I = 0, E = NumElts / 2; I != E; I++) {
5205     if (Mask[I] != I)
5206       return false;
5207   }
5208
5209   int Offset = NumElts / 2;
5210   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5211     if (Mask[I] != I + SplitLHS * Offset)
5212       return false;
5213   }
5214
5215   return true;
5216 }
5217
5218 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5219   SDLoc DL(Op);
5220   EVT VT = Op.getValueType();
5221   SDValue V0 = Op.getOperand(0);
5222   SDValue V1 = Op.getOperand(1);
5223   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5224
5225   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5226       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5227     return SDValue();
5228
5229   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5230
5231   if (!isConcatMask(Mask, VT, SplitV0))
5232     return SDValue();
5233
5234   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5235                                 VT.getVectorNumElements() / 2);
5236   if (SplitV0) {
5237     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5238                      DAG.getConstant(0, DL, MVT::i64));
5239   }
5240   if (V1.getValueType().getSizeInBits() == 128) {
5241     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5242                      DAG.getConstant(0, DL, MVT::i64));
5243   }
5244   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5245 }
5246
5247 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5248 /// the specified operations to build the shuffle.
5249 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5250                                       SDValue RHS, SelectionDAG &DAG,
5251                                       SDLoc dl) {
5252   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5253   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5254   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5255
5256   enum {
5257     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5258     OP_VREV,
5259     OP_VDUP0,
5260     OP_VDUP1,
5261     OP_VDUP2,
5262     OP_VDUP3,
5263     OP_VEXT1,
5264     OP_VEXT2,
5265     OP_VEXT3,
5266     OP_VUZPL, // VUZP, left result
5267     OP_VUZPR, // VUZP, right result
5268     OP_VZIPL, // VZIP, left result
5269     OP_VZIPR, // VZIP, right result
5270     OP_VTRNL, // VTRN, left result
5271     OP_VTRNR  // VTRN, right result
5272   };
5273
5274   if (OpNum == OP_COPY) {
5275     if (LHSID == (1 * 9 + 2) * 9 + 3)
5276       return LHS;
5277     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5278     return RHS;
5279   }
5280
5281   SDValue OpLHS, OpRHS;
5282   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5283   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5284   EVT VT = OpLHS.getValueType();
5285
5286   switch (OpNum) {
5287   default:
5288     llvm_unreachable("Unknown shuffle opcode!");
5289   case OP_VREV:
5290     // VREV divides the vector in half and swaps within the half.
5291     if (VT.getVectorElementType() == MVT::i32 ||
5292         VT.getVectorElementType() == MVT::f32)
5293       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5294     // vrev <4 x i16> -> REV32
5295     if (VT.getVectorElementType() == MVT::i16 ||
5296         VT.getVectorElementType() == MVT::f16)
5297       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5298     // vrev <4 x i8> -> REV16
5299     assert(VT.getVectorElementType() == MVT::i8);
5300     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5301   case OP_VDUP0:
5302   case OP_VDUP1:
5303   case OP_VDUP2:
5304   case OP_VDUP3: {
5305     EVT EltTy = VT.getVectorElementType();
5306     unsigned Opcode;
5307     if (EltTy == MVT::i8)
5308       Opcode = AArch64ISD::DUPLANE8;
5309     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5310       Opcode = AArch64ISD::DUPLANE16;
5311     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5312       Opcode = AArch64ISD::DUPLANE32;
5313     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5314       Opcode = AArch64ISD::DUPLANE64;
5315     else
5316       llvm_unreachable("Invalid vector element type?");
5317
5318     if (VT.getSizeInBits() == 64)
5319       OpLHS = WidenVector(OpLHS, DAG);
5320     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5321     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5322   }
5323   case OP_VEXT1:
5324   case OP_VEXT2:
5325   case OP_VEXT3: {
5326     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5327     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5328                        DAG.getConstant(Imm, dl, MVT::i32));
5329   }
5330   case OP_VUZPL:
5331     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5332                        OpRHS);
5333   case OP_VUZPR:
5334     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5335                        OpRHS);
5336   case OP_VZIPL:
5337     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5338                        OpRHS);
5339   case OP_VZIPR:
5340     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5341                        OpRHS);
5342   case OP_VTRNL:
5343     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5344                        OpRHS);
5345   case OP_VTRNR:
5346     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5347                        OpRHS);
5348   }
5349 }
5350
5351 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5352                            SelectionDAG &DAG) {
5353   // Check to see if we can use the TBL instruction.
5354   SDValue V1 = Op.getOperand(0);
5355   SDValue V2 = Op.getOperand(1);
5356   SDLoc DL(Op);
5357
5358   EVT EltVT = Op.getValueType().getVectorElementType();
5359   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5360
5361   SmallVector<SDValue, 8> TBLMask;
5362   for (int Val : ShuffleMask) {
5363     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5364       unsigned Offset = Byte + Val * BytesPerElt;
5365       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5366     }
5367   }
5368
5369   MVT IndexVT = MVT::v8i8;
5370   unsigned IndexLen = 8;
5371   if (Op.getValueType().getSizeInBits() == 128) {
5372     IndexVT = MVT::v16i8;
5373     IndexLen = 16;
5374   }
5375
5376   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5377   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5378
5379   SDValue Shuffle;
5380   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5381     if (IndexLen == 8)
5382       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5383     Shuffle = DAG.getNode(
5384         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5385         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5386         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5387                     makeArrayRef(TBLMask.data(), IndexLen)));
5388   } else {
5389     if (IndexLen == 8) {
5390       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5391       Shuffle = DAG.getNode(
5392           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5393           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5394           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5395                       makeArrayRef(TBLMask.data(), IndexLen)));
5396     } else {
5397       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5398       // cannot currently represent the register constraints on the input
5399       // table registers.
5400       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5401       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5402       //                               &TBLMask[0], IndexLen));
5403       Shuffle = DAG.getNode(
5404           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5405           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5406           V1Cst, V2Cst,
5407           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5408                       makeArrayRef(TBLMask.data(), IndexLen)));
5409     }
5410   }
5411   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5412 }
5413
5414 static unsigned getDUPLANEOp(EVT EltType) {
5415   if (EltType == MVT::i8)
5416     return AArch64ISD::DUPLANE8;
5417   if (EltType == MVT::i16 || EltType == MVT::f16)
5418     return AArch64ISD::DUPLANE16;
5419   if (EltType == MVT::i32 || EltType == MVT::f32)
5420     return AArch64ISD::DUPLANE32;
5421   if (EltType == MVT::i64 || EltType == MVT::f64)
5422     return AArch64ISD::DUPLANE64;
5423
5424   llvm_unreachable("Invalid vector element type?");
5425 }
5426
5427 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5428                                                    SelectionDAG &DAG) const {
5429   SDLoc dl(Op);
5430   EVT VT = Op.getValueType();
5431
5432   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5433
5434   // Convert shuffles that are directly supported on NEON to target-specific
5435   // DAG nodes, instead of keeping them as shuffles and matching them again
5436   // during code selection.  This is more efficient and avoids the possibility
5437   // of inconsistencies between legalization and selection.
5438   ArrayRef<int> ShuffleMask = SVN->getMask();
5439
5440   SDValue V1 = Op.getOperand(0);
5441   SDValue V2 = Op.getOperand(1);
5442
5443   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5444                                        V1.getValueType().getSimpleVT())) {
5445     int Lane = SVN->getSplatIndex();
5446     // If this is undef splat, generate it via "just" vdup, if possible.
5447     if (Lane == -1)
5448       Lane = 0;
5449
5450     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5451       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5452                          V1.getOperand(0));
5453     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5454     // constant. If so, we can just reference the lane's definition directly.
5455     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5456         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5457       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5458
5459     // Otherwise, duplicate from the lane of the input vector.
5460     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5461
5462     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5463     // to make a vector of the same size as this SHUFFLE. We can ignore the
5464     // extract entirely, and canonicalise the concat using WidenVector.
5465     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5466       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5467       V1 = V1.getOperand(0);
5468     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5469       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5470       Lane -= Idx * VT.getVectorNumElements() / 2;
5471       V1 = WidenVector(V1.getOperand(Idx), DAG);
5472     } else if (VT.getSizeInBits() == 64)
5473       V1 = WidenVector(V1, DAG);
5474
5475     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5476   }
5477
5478   if (isREVMask(ShuffleMask, VT, 64))
5479     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5480   if (isREVMask(ShuffleMask, VT, 32))
5481     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5482   if (isREVMask(ShuffleMask, VT, 16))
5483     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5484
5485   bool ReverseEXT = false;
5486   unsigned Imm;
5487   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5488     if (ReverseEXT)
5489       std::swap(V1, V2);
5490     Imm *= getExtFactor(V1);
5491     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5492                        DAG.getConstant(Imm, dl, MVT::i32));
5493   } else if (V2->getOpcode() == ISD::UNDEF &&
5494              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5495     Imm *= getExtFactor(V1);
5496     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5497                        DAG.getConstant(Imm, dl, MVT::i32));
5498   }
5499
5500   unsigned WhichResult;
5501   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5502     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5503     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5504   }
5505   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5506     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5507     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5508   }
5509   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5510     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5511     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5512   }
5513
5514   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5515     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5516     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5517   }
5518   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5519     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5520     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5521   }
5522   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5523     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5524     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5525   }
5526
5527   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5528   if (Concat.getNode())
5529     return Concat;
5530
5531   bool DstIsLeft;
5532   int Anomaly;
5533   int NumInputElements = V1.getValueType().getVectorNumElements();
5534   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5535     SDValue DstVec = DstIsLeft ? V1 : V2;
5536     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5537
5538     SDValue SrcVec = V1;
5539     int SrcLane = ShuffleMask[Anomaly];
5540     if (SrcLane >= NumInputElements) {
5541       SrcVec = V2;
5542       SrcLane -= VT.getVectorNumElements();
5543     }
5544     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5545
5546     EVT ScalarVT = VT.getVectorElementType();
5547
5548     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5549       ScalarVT = MVT::i32;
5550
5551     return DAG.getNode(
5552         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5553         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5554         DstLaneV);
5555   }
5556
5557   // If the shuffle is not directly supported and it has 4 elements, use
5558   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5559   unsigned NumElts = VT.getVectorNumElements();
5560   if (NumElts == 4) {
5561     unsigned PFIndexes[4];
5562     for (unsigned i = 0; i != 4; ++i) {
5563       if (ShuffleMask[i] < 0)
5564         PFIndexes[i] = 8;
5565       else
5566         PFIndexes[i] = ShuffleMask[i];
5567     }
5568
5569     // Compute the index in the perfect shuffle table.
5570     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5571                             PFIndexes[2] * 9 + PFIndexes[3];
5572     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5573     unsigned Cost = (PFEntry >> 30);
5574
5575     if (Cost <= 4)
5576       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5577   }
5578
5579   return GenerateTBL(Op, ShuffleMask, DAG);
5580 }
5581
5582 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5583                                APInt &UndefBits) {
5584   EVT VT = BVN->getValueType(0);
5585   APInt SplatBits, SplatUndef;
5586   unsigned SplatBitSize;
5587   bool HasAnyUndefs;
5588   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5589     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5590
5591     for (unsigned i = 0; i < NumSplats; ++i) {
5592       CnstBits <<= SplatBitSize;
5593       UndefBits <<= SplatBitSize;
5594       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5595       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5596     }
5597
5598     return true;
5599   }
5600
5601   return false;
5602 }
5603
5604 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5605                                               SelectionDAG &DAG) const {
5606   BuildVectorSDNode *BVN =
5607       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5608   SDValue LHS = Op.getOperand(0);
5609   SDLoc dl(Op);
5610   EVT VT = Op.getValueType();
5611
5612   if (!BVN)
5613     return Op;
5614
5615   APInt CnstBits(VT.getSizeInBits(), 0);
5616   APInt UndefBits(VT.getSizeInBits(), 0);
5617   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5618     // We only have BIC vector immediate instruction, which is and-not.
5619     CnstBits = ~CnstBits;
5620
5621     // We make use of a little bit of goto ickiness in order to avoid having to
5622     // duplicate the immediate matching logic for the undef toggled case.
5623     bool SecondTry = false;
5624   AttemptModImm:
5625
5626     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5627       CnstBits = CnstBits.zextOrTrunc(64);
5628       uint64_t CnstVal = CnstBits.getZExtValue();
5629
5630       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5631         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5632         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5633         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5634                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5635                                   DAG.getConstant(0, dl, MVT::i32));
5636         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5637       }
5638
5639       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5640         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5641         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5642         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5643                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5644                                   DAG.getConstant(8, dl, MVT::i32));
5645         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5646       }
5647
5648       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5649         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(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(16, dl, MVT::i32));
5654         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5655       }
5656
5657       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5658         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(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(24, dl, MVT::i32));
5663         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5664       }
5665
5666       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5667         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5668         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5669         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5670                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5671                                   DAG.getConstant(0, dl, MVT::i32));
5672         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5673       }
5674
5675       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5676         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5677         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5678         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5679                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5680                                   DAG.getConstant(8, dl, MVT::i32));
5681         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5682       }
5683     }
5684
5685     if (SecondTry)
5686       goto FailedModImm;
5687     SecondTry = true;
5688     CnstBits = ~UndefBits;
5689     goto AttemptModImm;
5690   }
5691
5692 // We can always fall back to a non-immediate AND.
5693 FailedModImm:
5694   return Op;
5695 }
5696
5697 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5698 // consists of only the same constant int value, returned in reference arg
5699 // ConstVal
5700 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5701                                      uint64_t &ConstVal) {
5702   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5703   if (!Bvec)
5704     return false;
5705   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5706   if (!FirstElt)
5707     return false;
5708   EVT VT = Bvec->getValueType(0);
5709   unsigned NumElts = VT.getVectorNumElements();
5710   for (unsigned i = 1; i < NumElts; ++i)
5711     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5712       return false;
5713   ConstVal = FirstElt->getZExtValue();
5714   return true;
5715 }
5716
5717 static unsigned getIntrinsicID(const SDNode *N) {
5718   unsigned Opcode = N->getOpcode();
5719   switch (Opcode) {
5720   default:
5721     return Intrinsic::not_intrinsic;
5722   case ISD::INTRINSIC_WO_CHAIN: {
5723     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5724     if (IID < Intrinsic::num_intrinsics)
5725       return IID;
5726     return Intrinsic::not_intrinsic;
5727   }
5728   }
5729 }
5730
5731 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5732 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5733 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5734 // Also, logical shift right -> sri, with the same structure.
5735 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5736   EVT VT = N->getValueType(0);
5737
5738   if (!VT.isVector())
5739     return SDValue();
5740
5741   SDLoc DL(N);
5742
5743   // Is the first op an AND?
5744   const SDValue And = N->getOperand(0);
5745   if (And.getOpcode() != ISD::AND)
5746     return SDValue();
5747
5748   // Is the second op an shl or lshr?
5749   SDValue Shift = N->getOperand(1);
5750   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5751   // or AArch64ISD::VLSHR vector, #shift
5752   unsigned ShiftOpc = Shift.getOpcode();
5753   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5754     return SDValue();
5755   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5756
5757   // Is the shift amount constant?
5758   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5759   if (!C2node)
5760     return SDValue();
5761
5762   // Is the and mask vector all constant?
5763   uint64_t C1;
5764   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5765     return SDValue();
5766
5767   // Is C1 == ~C2, taking into account how much one can shift elements of a
5768   // particular size?
5769   uint64_t C2 = C2node->getZExtValue();
5770   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5771   if (C2 > ElemSizeInBits)
5772     return SDValue();
5773   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5774   if ((C1 & ElemMask) != (~C2 & ElemMask))
5775     return SDValue();
5776
5777   SDValue X = And.getOperand(0);
5778   SDValue Y = Shift.getOperand(0);
5779
5780   unsigned Intrin =
5781       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5782   SDValue ResultSLI =
5783       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5784                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5785                   Shift.getOperand(1));
5786
5787   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5788   DEBUG(N->dump(&DAG));
5789   DEBUG(dbgs() << "into: \n");
5790   DEBUG(ResultSLI->dump(&DAG));
5791
5792   ++NumShiftInserts;
5793   return ResultSLI;
5794 }
5795
5796 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5797                                              SelectionDAG &DAG) const {
5798   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5799   if (EnableAArch64SlrGeneration) {
5800     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5801     if (Res.getNode())
5802       return Res;
5803   }
5804
5805   BuildVectorSDNode *BVN =
5806       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5807   SDValue LHS = Op.getOperand(1);
5808   SDLoc dl(Op);
5809   EVT VT = Op.getValueType();
5810
5811   // OR commutes, so try swapping the operands.
5812   if (!BVN) {
5813     LHS = Op.getOperand(0);
5814     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5815   }
5816   if (!BVN)
5817     return Op;
5818
5819   APInt CnstBits(VT.getSizeInBits(), 0);
5820   APInt UndefBits(VT.getSizeInBits(), 0);
5821   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5822     // We make use of a little bit of goto ickiness in order to avoid having to
5823     // duplicate the immediate matching logic for the undef toggled case.
5824     bool SecondTry = false;
5825   AttemptModImm:
5826
5827     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5828       CnstBits = CnstBits.zextOrTrunc(64);
5829       uint64_t CnstVal = CnstBits.getZExtValue();
5830
5831       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5832         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5833         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5834         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5835                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5836                                   DAG.getConstant(0, dl, MVT::i32));
5837         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5838       }
5839
5840       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5841         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5842         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5843         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5844                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5845                                   DAG.getConstant(8, dl, MVT::i32));
5846         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5847       }
5848
5849       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5850         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(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(16, dl, MVT::i32));
5855         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5856       }
5857
5858       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5859         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(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(24, dl, MVT::i32));
5864         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5865       }
5866
5867       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5868         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5869         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5870         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5871                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5872                                   DAG.getConstant(0, dl, MVT::i32));
5873         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5874       }
5875
5876       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5877         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5878         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5879         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5880                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5881                                   DAG.getConstant(8, dl, MVT::i32));
5882         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5883       }
5884     }
5885
5886     if (SecondTry)
5887       goto FailedModImm;
5888     SecondTry = true;
5889     CnstBits = UndefBits;
5890     goto AttemptModImm;
5891   }
5892
5893 // We can always fall back to a non-immediate OR.
5894 FailedModImm:
5895   return Op;
5896 }
5897
5898 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5899 // be truncated to fit element width.
5900 static SDValue NormalizeBuildVector(SDValue Op,
5901                                     SelectionDAG &DAG) {
5902   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5903   SDLoc dl(Op);
5904   EVT VT = Op.getValueType();
5905   EVT EltTy= VT.getVectorElementType();
5906
5907   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5908     return Op;
5909
5910   SmallVector<SDValue, 16> Ops;
5911   for (SDValue Lane : Op->ops()) {
5912     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5913       APInt LowBits(EltTy.getSizeInBits(),
5914                     CstLane->getZExtValue());
5915       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5916     }
5917     Ops.push_back(Lane);
5918   }
5919   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5920 }
5921
5922 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5923                                                  SelectionDAG &DAG) const {
5924   SDLoc dl(Op);
5925   EVT VT = Op.getValueType();
5926   Op = NormalizeBuildVector(Op, DAG);
5927   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5928
5929   APInt CnstBits(VT.getSizeInBits(), 0);
5930   APInt UndefBits(VT.getSizeInBits(), 0);
5931   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5932     // We make use of a little bit of goto ickiness in order to avoid having to
5933     // duplicate the immediate matching logic for the undef toggled case.
5934     bool SecondTry = false;
5935   AttemptModImm:
5936
5937     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5938       CnstBits = CnstBits.zextOrTrunc(64);
5939       uint64_t CnstVal = CnstBits.getZExtValue();
5940
5941       // Certain magic vector constants (used to express things like NOT
5942       // and NEG) are passed through unmodified.  This allows codegen patterns
5943       // for these operations to match.  Special-purpose patterns will lower
5944       // these immediates to MOVIs if it proves necessary.
5945       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5946         return Op;
5947
5948       // The many faces of MOVI...
5949       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5950         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5951         if (VT.getSizeInBits() == 128) {
5952           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5953                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5954           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5955         }
5956
5957         // Support the V64 version via subregister insertion.
5958         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5959                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5960         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5961       }
5962
5963       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5964         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5965         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5966         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5967                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5968                                   DAG.getConstant(0, dl, MVT::i32));
5969         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5970       }
5971
5972       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5973         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5974         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5975         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5976                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5977                                   DAG.getConstant(8, dl, MVT::i32));
5978         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5979       }
5980
5981       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5982         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(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(16, dl, MVT::i32));
5987         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5988       }
5989
5990       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5991         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(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(24, dl, MVT::i32));
5996         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5997       }
5998
5999       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6000         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6001         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6002         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6003                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6004                                   DAG.getConstant(0, dl, MVT::i32));
6005         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6006       }
6007
6008       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6009         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6010         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6011         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6012                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6013                                   DAG.getConstant(8, dl, MVT::i32));
6014         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6015       }
6016
6017       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6018         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6019         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6020         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6021                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6022                                   DAG.getConstant(264, dl, MVT::i32));
6023         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6024       }
6025
6026       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6027         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6028         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6029         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6030                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6031                                   DAG.getConstant(272, dl, MVT::i32));
6032         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6033       }
6034
6035       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6036         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6037         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6038         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6039                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6040         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6041       }
6042
6043       // The few faces of FMOV...
6044       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6045         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6046         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6047         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6048                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6049         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6050       }
6051
6052       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6053           VT.getSizeInBits() == 128) {
6054         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6055         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6056                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6057         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6058       }
6059
6060       // The many faces of MVNI...
6061       CnstVal = ~CnstVal;
6062       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6063         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6064         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6065         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6066                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6067                                   DAG.getConstant(0, dl, MVT::i32));
6068         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6069       }
6070
6071       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6072         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6073         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6074         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6075                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6076                                   DAG.getConstant(8, dl, MVT::i32));
6077         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6078       }
6079
6080       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6081         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(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(16, dl, MVT::i32));
6086         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6087       }
6088
6089       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6090         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(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(24, dl, MVT::i32));
6095         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6096       }
6097
6098       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6099         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6100         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6101         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6102                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6103                                   DAG.getConstant(0, dl, MVT::i32));
6104         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6105       }
6106
6107       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6108         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6109         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6110         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6111                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6112                                   DAG.getConstant(8, dl, MVT::i32));
6113         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6114       }
6115
6116       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6117         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6118         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6119         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6120                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6121                                   DAG.getConstant(264, dl, MVT::i32));
6122         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6123       }
6124
6125       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6126         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6127         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6128         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6129                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6130                                   DAG.getConstant(272, dl, MVT::i32));
6131         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6132       }
6133     }
6134
6135     if (SecondTry)
6136       goto FailedModImm;
6137     SecondTry = true;
6138     CnstBits = UndefBits;
6139     goto AttemptModImm;
6140   }
6141 FailedModImm:
6142
6143   // Scan through the operands to find some interesting properties we can
6144   // exploit:
6145   //   1) If only one value is used, we can use a DUP, or
6146   //   2) if only the low element is not undef, we can just insert that, or
6147   //   3) if only one constant value is used (w/ some non-constant lanes),
6148   //      we can splat the constant value into the whole vector then fill
6149   //      in the non-constant lanes.
6150   //   4) FIXME: If different constant values are used, but we can intelligently
6151   //             select the values we'll be overwriting for the non-constant
6152   //             lanes such that we can directly materialize the vector
6153   //             some other way (MOVI, e.g.), we can be sneaky.
6154   unsigned NumElts = VT.getVectorNumElements();
6155   bool isOnlyLowElement = true;
6156   bool usesOnlyOneValue = true;
6157   bool usesOnlyOneConstantValue = true;
6158   bool isConstant = true;
6159   unsigned NumConstantLanes = 0;
6160   SDValue Value;
6161   SDValue ConstantValue;
6162   for (unsigned i = 0; i < NumElts; ++i) {
6163     SDValue V = Op.getOperand(i);
6164     if (V.getOpcode() == ISD::UNDEF)
6165       continue;
6166     if (i > 0)
6167       isOnlyLowElement = false;
6168     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6169       isConstant = false;
6170
6171     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6172       ++NumConstantLanes;
6173       if (!ConstantValue.getNode())
6174         ConstantValue = V;
6175       else if (ConstantValue != V)
6176         usesOnlyOneConstantValue = false;
6177     }
6178
6179     if (!Value.getNode())
6180       Value = V;
6181     else if (V != Value)
6182       usesOnlyOneValue = false;
6183   }
6184
6185   if (!Value.getNode())
6186     return DAG.getUNDEF(VT);
6187
6188   if (isOnlyLowElement)
6189     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6190
6191   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6192   // i32 and try again.
6193   if (usesOnlyOneValue) {
6194     if (!isConstant) {
6195       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6196           Value.getValueType() != VT)
6197         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6198
6199       // This is actually a DUPLANExx operation, which keeps everything vectory.
6200
6201       // DUPLANE works on 128-bit vectors, widen it if necessary.
6202       SDValue Lane = Value.getOperand(1);
6203       Value = Value.getOperand(0);
6204       if (Value.getValueType().getSizeInBits() == 64)
6205         Value = WidenVector(Value, DAG);
6206
6207       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6208       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6209     }
6210
6211     if (VT.getVectorElementType().isFloatingPoint()) {
6212       SmallVector<SDValue, 8> Ops;
6213       EVT EltTy = VT.getVectorElementType();
6214       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6215               "Unsupported floating-point vector type");
6216       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6217       for (unsigned i = 0; i < NumElts; ++i)
6218         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6219       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6220       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6221       Val = LowerBUILD_VECTOR(Val, DAG);
6222       if (Val.getNode())
6223         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6224     }
6225   }
6226
6227   // If there was only one constant value used and for more than one lane,
6228   // start by splatting that value, then replace the non-constant lanes. This
6229   // is better than the default, which will perform a separate initialization
6230   // for each lane.
6231   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6232     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6233     // Now insert the non-constant lanes.
6234     for (unsigned i = 0; i < NumElts; ++i) {
6235       SDValue V = Op.getOperand(i);
6236       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6237       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6238         // Note that type legalization likely mucked about with the VT of the
6239         // source operand, so we may have to convert it here before inserting.
6240         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6241       }
6242     }
6243     return Val;
6244   }
6245
6246   // If all elements are constants and the case above didn't get hit, fall back
6247   // to the default expansion, which will generate a load from the constant
6248   // pool.
6249   if (isConstant)
6250     return SDValue();
6251
6252   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6253   if (NumElts >= 4) {
6254     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6255       return shuffle;
6256   }
6257
6258   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6259   // know the default expansion would otherwise fall back on something even
6260   // worse. For a vector with one or two non-undef values, that's
6261   // scalar_to_vector for the elements followed by a shuffle (provided the
6262   // shuffle is valid for the target) and materialization element by element
6263   // on the stack followed by a load for everything else.
6264   if (!isConstant && !usesOnlyOneValue) {
6265     SDValue Vec = DAG.getUNDEF(VT);
6266     SDValue Op0 = Op.getOperand(0);
6267     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6268     unsigned i = 0;
6269     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6270     // a) Avoid a RMW dependency on the full vector register, and
6271     // b) Allow the register coalescer to fold away the copy if the
6272     //    value is already in an S or D register.
6273     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6274     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6275     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6276         (ElemSize == 32 || ElemSize == 64)) {
6277       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6278       MachineSDNode *N =
6279           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6280                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6281       Vec = SDValue(N, 0);
6282       ++i;
6283     }
6284     for (; i < NumElts; ++i) {
6285       SDValue V = Op.getOperand(i);
6286       if (V.getOpcode() == ISD::UNDEF)
6287         continue;
6288       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6289       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6290     }
6291     return Vec;
6292   }
6293
6294   // Just use the default expansion. We failed to find a better alternative.
6295   return SDValue();
6296 }
6297
6298 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6299                                                       SelectionDAG &DAG) const {
6300   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6301
6302   // Check for non-constant or out of range lane.
6303   EVT VT = Op.getOperand(0).getValueType();
6304   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6305   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6306     return SDValue();
6307
6308
6309   // Insertion/extraction are legal for V128 types.
6310   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6311       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6312       VT == MVT::v8f16)
6313     return Op;
6314
6315   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6316       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6317     return SDValue();
6318
6319   // For V64 types, we perform insertion by expanding the value
6320   // to a V128 type and perform the insertion on that.
6321   SDLoc DL(Op);
6322   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6323   EVT WideTy = WideVec.getValueType();
6324
6325   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6326                              Op.getOperand(1), Op.getOperand(2));
6327   // Re-narrow the resultant vector.
6328   return NarrowVector(Node, DAG);
6329 }
6330
6331 SDValue
6332 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6333                                                SelectionDAG &DAG) const {
6334   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6335
6336   // Check for non-constant or out of range lane.
6337   EVT VT = Op.getOperand(0).getValueType();
6338   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6339   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6340     return SDValue();
6341
6342
6343   // Insertion/extraction are legal for V128 types.
6344   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6345       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6346       VT == MVT::v8f16)
6347     return Op;
6348
6349   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6350       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6351     return SDValue();
6352
6353   // For V64 types, we perform extraction by expanding the value
6354   // to a V128 type and perform the extraction on that.
6355   SDLoc DL(Op);
6356   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6357   EVT WideTy = WideVec.getValueType();
6358
6359   EVT ExtrTy = WideTy.getVectorElementType();
6360   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6361     ExtrTy = MVT::i32;
6362
6363   // For extractions, we just return the result directly.
6364   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6365                      Op.getOperand(1));
6366 }
6367
6368 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6369                                                       SelectionDAG &DAG) const {
6370   EVT VT = Op.getOperand(0).getValueType();
6371   SDLoc dl(Op);
6372   // Just in case...
6373   if (!VT.isVector())
6374     return SDValue();
6375
6376   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6377   if (!Cst)
6378     return SDValue();
6379   unsigned Val = Cst->getZExtValue();
6380
6381   unsigned Size = Op.getValueType().getSizeInBits();
6382   if (Val == 0) {
6383     switch (Size) {
6384     case 8:
6385       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6386                                         Op.getOperand(0));
6387     case 16:
6388       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6389                                         Op.getOperand(0));
6390     case 32:
6391       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6392                                         Op.getOperand(0));
6393     case 64:
6394       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6395                                         Op.getOperand(0));
6396     default:
6397       llvm_unreachable("Unexpected vector type in extract_subvector!");
6398     }
6399   }
6400   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6401   // that directly.
6402   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6403     return Op;
6404
6405   return SDValue();
6406 }
6407
6408 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6409                                                EVT VT) const {
6410   if (VT.getVectorNumElements() == 4 &&
6411       (VT.is128BitVector() || VT.is64BitVector())) {
6412     unsigned PFIndexes[4];
6413     for (unsigned i = 0; i != 4; ++i) {
6414       if (M[i] < 0)
6415         PFIndexes[i] = 8;
6416       else
6417         PFIndexes[i] = M[i];
6418     }
6419
6420     // Compute the index in the perfect shuffle table.
6421     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6422                             PFIndexes[2] * 9 + PFIndexes[3];
6423     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6424     unsigned Cost = (PFEntry >> 30);
6425
6426     if (Cost <= 4)
6427       return true;
6428   }
6429
6430   bool DummyBool;
6431   int DummyInt;
6432   unsigned DummyUnsigned;
6433
6434   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6435           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6436           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6437           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6438           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6439           isZIPMask(M, VT, DummyUnsigned) ||
6440           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6441           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6442           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6443           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6444           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6445 }
6446
6447 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6448 /// operand of a vector shift operation, where all the elements of the
6449 /// build_vector must have the same constant integer value.
6450 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6451   // Ignore bit_converts.
6452   while (Op.getOpcode() == ISD::BITCAST)
6453     Op = Op.getOperand(0);
6454   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6455   APInt SplatBits, SplatUndef;
6456   unsigned SplatBitSize;
6457   bool HasAnyUndefs;
6458   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6459                                     HasAnyUndefs, ElementBits) ||
6460       SplatBitSize > ElementBits)
6461     return false;
6462   Cnt = SplatBits.getSExtValue();
6463   return true;
6464 }
6465
6466 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6467 /// operand of a vector shift left operation.  That value must be in the range:
6468 ///   0 <= Value < ElementBits for a left shift; or
6469 ///   0 <= Value <= ElementBits for a long left shift.
6470 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6471   assert(VT.isVector() && "vector shift count is not a vector type");
6472   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6473   if (!getVShiftImm(Op, ElementBits, Cnt))
6474     return false;
6475   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6476 }
6477
6478 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6479 /// operand of a vector shift right operation. The value must be in the range:
6480 ///   1 <= Value <= ElementBits for a right shift; or
6481 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6482   assert(VT.isVector() && "vector shift count is not a vector type");
6483   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6484   if (!getVShiftImm(Op, ElementBits, Cnt))
6485     return false;
6486   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6487 }
6488
6489 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6490                                                       SelectionDAG &DAG) const {
6491   EVT VT = Op.getValueType();
6492   SDLoc DL(Op);
6493   int64_t Cnt;
6494
6495   if (!Op.getOperand(1).getValueType().isVector())
6496     return Op;
6497   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6498
6499   switch (Op.getOpcode()) {
6500   default:
6501     llvm_unreachable("unexpected shift opcode");
6502
6503   case ISD::SHL:
6504     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6505       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6506                          DAG.getConstant(Cnt, DL, MVT::i32));
6507     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6508                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6509                                        MVT::i32),
6510                        Op.getOperand(0), Op.getOperand(1));
6511   case ISD::SRA:
6512   case ISD::SRL:
6513     // Right shift immediate
6514     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6515       unsigned Opc =
6516           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6517       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6518                          DAG.getConstant(Cnt, DL, MVT::i32));
6519     }
6520
6521     // Right shift register.  Note, there is not a shift right register
6522     // instruction, but the shift left register instruction takes a signed
6523     // value, where negative numbers specify a right shift.
6524     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6525                                                 : Intrinsic::aarch64_neon_ushl;
6526     // negate the shift amount
6527     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6528     SDValue NegShiftLeft =
6529         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6530                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6531                     NegShift);
6532     return NegShiftLeft;
6533   }
6534
6535   return SDValue();
6536 }
6537
6538 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6539                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6540                                     SDLoc dl, SelectionDAG &DAG) {
6541   EVT SrcVT = LHS.getValueType();
6542   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6543          "function only supposed to emit natural comparisons");
6544
6545   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6546   APInt CnstBits(VT.getSizeInBits(), 0);
6547   APInt UndefBits(VT.getSizeInBits(), 0);
6548   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6549   bool IsZero = IsCnst && (CnstBits == 0);
6550
6551   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6552     switch (CC) {
6553     default:
6554       return SDValue();
6555     case AArch64CC::NE: {
6556       SDValue Fcmeq;
6557       if (IsZero)
6558         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6559       else
6560         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6561       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6562     }
6563     case AArch64CC::EQ:
6564       if (IsZero)
6565         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6566       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6567     case AArch64CC::GE:
6568       if (IsZero)
6569         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6570       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6571     case AArch64CC::GT:
6572       if (IsZero)
6573         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6574       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6575     case AArch64CC::LS:
6576       if (IsZero)
6577         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6578       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6579     case AArch64CC::LT:
6580       if (!NoNans)
6581         return SDValue();
6582     // If we ignore NaNs then we can use to the MI implementation.
6583     // Fallthrough.
6584     case AArch64CC::MI:
6585       if (IsZero)
6586         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6587       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6588     }
6589   }
6590
6591   switch (CC) {
6592   default:
6593     return SDValue();
6594   case AArch64CC::NE: {
6595     SDValue Cmeq;
6596     if (IsZero)
6597       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6598     else
6599       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6600     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6601   }
6602   case AArch64CC::EQ:
6603     if (IsZero)
6604       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6605     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6606   case AArch64CC::GE:
6607     if (IsZero)
6608       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6609     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6610   case AArch64CC::GT:
6611     if (IsZero)
6612       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6613     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6614   case AArch64CC::LE:
6615     if (IsZero)
6616       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6617     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6618   case AArch64CC::LS:
6619     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6620   case AArch64CC::LO:
6621     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6622   case AArch64CC::LT:
6623     if (IsZero)
6624       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6625     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6626   case AArch64CC::HI:
6627     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6628   case AArch64CC::HS:
6629     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6630   }
6631 }
6632
6633 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6634                                            SelectionDAG &DAG) const {
6635   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6636   SDValue LHS = Op.getOperand(0);
6637   SDValue RHS = Op.getOperand(1);
6638   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6639   SDLoc dl(Op);
6640
6641   if (LHS.getValueType().getVectorElementType().isInteger()) {
6642     assert(LHS.getValueType() == RHS.getValueType());
6643     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6644     SDValue Cmp =
6645         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6646     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6647   }
6648
6649   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6650          LHS.getValueType().getVectorElementType() == MVT::f64);
6651
6652   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6653   // clean.  Some of them require two branches to implement.
6654   AArch64CC::CondCode CC1, CC2;
6655   bool ShouldInvert;
6656   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6657
6658   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6659   SDValue Cmp =
6660       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6661   if (!Cmp.getNode())
6662     return SDValue();
6663
6664   if (CC2 != AArch64CC::AL) {
6665     SDValue Cmp2 =
6666         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6667     if (!Cmp2.getNode())
6668       return SDValue();
6669
6670     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6671   }
6672
6673   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6674
6675   if (ShouldInvert)
6676     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6677
6678   return Cmp;
6679 }
6680
6681 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6682 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6683 /// specified in the intrinsic calls.
6684 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6685                                                const CallInst &I,
6686                                                unsigned Intrinsic) const {
6687   auto &DL = I.getModule()->getDataLayout();
6688   switch (Intrinsic) {
6689   case Intrinsic::aarch64_neon_ld2:
6690   case Intrinsic::aarch64_neon_ld3:
6691   case Intrinsic::aarch64_neon_ld4:
6692   case Intrinsic::aarch64_neon_ld1x2:
6693   case Intrinsic::aarch64_neon_ld1x3:
6694   case Intrinsic::aarch64_neon_ld1x4:
6695   case Intrinsic::aarch64_neon_ld2lane:
6696   case Intrinsic::aarch64_neon_ld3lane:
6697   case Intrinsic::aarch64_neon_ld4lane:
6698   case Intrinsic::aarch64_neon_ld2r:
6699   case Intrinsic::aarch64_neon_ld3r:
6700   case Intrinsic::aarch64_neon_ld4r: {
6701     Info.opc = ISD::INTRINSIC_W_CHAIN;
6702     // Conservatively set memVT to the entire set of vectors loaded.
6703     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6704     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6705     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6706     Info.offset = 0;
6707     Info.align = 0;
6708     Info.vol = false; // volatile loads with NEON intrinsics not supported
6709     Info.readMem = true;
6710     Info.writeMem = false;
6711     return true;
6712   }
6713   case Intrinsic::aarch64_neon_st2:
6714   case Intrinsic::aarch64_neon_st3:
6715   case Intrinsic::aarch64_neon_st4:
6716   case Intrinsic::aarch64_neon_st1x2:
6717   case Intrinsic::aarch64_neon_st1x3:
6718   case Intrinsic::aarch64_neon_st1x4:
6719   case Intrinsic::aarch64_neon_st2lane:
6720   case Intrinsic::aarch64_neon_st3lane:
6721   case Intrinsic::aarch64_neon_st4lane: {
6722     Info.opc = ISD::INTRINSIC_VOID;
6723     // Conservatively set memVT to the entire set of vectors stored.
6724     unsigned NumElts = 0;
6725     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6726       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6727       if (!ArgTy->isVectorTy())
6728         break;
6729       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6730     }
6731     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6732     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6733     Info.offset = 0;
6734     Info.align = 0;
6735     Info.vol = false; // volatile stores with NEON intrinsics not supported
6736     Info.readMem = false;
6737     Info.writeMem = true;
6738     return true;
6739   }
6740   case Intrinsic::aarch64_ldaxr:
6741   case Intrinsic::aarch64_ldxr: {
6742     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6743     Info.opc = ISD::INTRINSIC_W_CHAIN;
6744     Info.memVT = MVT::getVT(PtrTy->getElementType());
6745     Info.ptrVal = I.getArgOperand(0);
6746     Info.offset = 0;
6747     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6748     Info.vol = true;
6749     Info.readMem = true;
6750     Info.writeMem = false;
6751     return true;
6752   }
6753   case Intrinsic::aarch64_stlxr:
6754   case Intrinsic::aarch64_stxr: {
6755     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6756     Info.opc = ISD::INTRINSIC_W_CHAIN;
6757     Info.memVT = MVT::getVT(PtrTy->getElementType());
6758     Info.ptrVal = I.getArgOperand(1);
6759     Info.offset = 0;
6760     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6761     Info.vol = true;
6762     Info.readMem = false;
6763     Info.writeMem = true;
6764     return true;
6765   }
6766   case Intrinsic::aarch64_ldaxp:
6767   case Intrinsic::aarch64_ldxp: {
6768     Info.opc = ISD::INTRINSIC_W_CHAIN;
6769     Info.memVT = MVT::i128;
6770     Info.ptrVal = I.getArgOperand(0);
6771     Info.offset = 0;
6772     Info.align = 16;
6773     Info.vol = true;
6774     Info.readMem = true;
6775     Info.writeMem = false;
6776     return true;
6777   }
6778   case Intrinsic::aarch64_stlxp:
6779   case Intrinsic::aarch64_stxp: {
6780     Info.opc = ISD::INTRINSIC_W_CHAIN;
6781     Info.memVT = MVT::i128;
6782     Info.ptrVal = I.getArgOperand(2);
6783     Info.offset = 0;
6784     Info.align = 16;
6785     Info.vol = true;
6786     Info.readMem = false;
6787     Info.writeMem = true;
6788     return true;
6789   }
6790   default:
6791     break;
6792   }
6793
6794   return false;
6795 }
6796
6797 // Truncations from 64-bit GPR to 32-bit GPR is free.
6798 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6799   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6800     return false;
6801   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6802   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6803   return NumBits1 > NumBits2;
6804 }
6805 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6806   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6807     return false;
6808   unsigned NumBits1 = VT1.getSizeInBits();
6809   unsigned NumBits2 = VT2.getSizeInBits();
6810   return NumBits1 > NumBits2;
6811 }
6812
6813 /// Check if it is profitable to hoist instruction in then/else to if.
6814 /// Not profitable if I and it's user can form a FMA instruction
6815 /// because we prefer FMSUB/FMADD.
6816 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6817   if (I->getOpcode() != Instruction::FMul)
6818     return true;
6819
6820   if (I->getNumUses() != 1)
6821     return true;
6822
6823   Instruction *User = I->user_back();
6824
6825   if (User &&
6826       !(User->getOpcode() == Instruction::FSub ||
6827         User->getOpcode() == Instruction::FAdd))
6828     return true;
6829
6830   const TargetOptions &Options = getTargetMachine().Options;
6831   const DataLayout &DL = I->getModule()->getDataLayout();
6832   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6833
6834   if (isFMAFasterThanFMulAndFAdd(VT) &&
6835       isOperationLegalOrCustom(ISD::FMA, VT) &&
6836       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6837     return false;
6838
6839   return true;
6840 }
6841
6842 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6843 // 64-bit GPR.
6844 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6845   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6846     return false;
6847   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6848   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6849   return NumBits1 == 32 && NumBits2 == 64;
6850 }
6851 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6852   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6853     return false;
6854   unsigned NumBits1 = VT1.getSizeInBits();
6855   unsigned NumBits2 = VT2.getSizeInBits();
6856   return NumBits1 == 32 && NumBits2 == 64;
6857 }
6858
6859 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6860   EVT VT1 = Val.getValueType();
6861   if (isZExtFree(VT1, VT2)) {
6862     return true;
6863   }
6864
6865   if (Val.getOpcode() != ISD::LOAD)
6866     return false;
6867
6868   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6869   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6870           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6871           VT1.getSizeInBits() <= 32);
6872 }
6873
6874 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6875   if (isa<FPExtInst>(Ext))
6876     return false;
6877
6878   // Vector types are next free.
6879   if (Ext->getType()->isVectorTy())
6880     return false;
6881
6882   for (const Use &U : Ext->uses()) {
6883     // The extension is free if we can fold it with a left shift in an
6884     // addressing mode or an arithmetic operation: add, sub, and cmp.
6885
6886     // Is there a shift?
6887     const Instruction *Instr = cast<Instruction>(U.getUser());
6888
6889     // Is this a constant shift?
6890     switch (Instr->getOpcode()) {
6891     case Instruction::Shl:
6892       if (!isa<ConstantInt>(Instr->getOperand(1)))
6893         return false;
6894       break;
6895     case Instruction::GetElementPtr: {
6896       gep_type_iterator GTI = gep_type_begin(Instr);
6897       auto &DL = Ext->getModule()->getDataLayout();
6898       std::advance(GTI, U.getOperandNo());
6899       Type *IdxTy = *GTI;
6900       // This extension will end up with a shift because of the scaling factor.
6901       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6902       // Get the shift amount based on the scaling factor:
6903       // log2(sizeof(IdxTy)) - log2(8).
6904       uint64_t ShiftAmt =
6905           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6906       // Is the constant foldable in the shift of the addressing mode?
6907       // I.e., shift amount is between 1 and 4 inclusive.
6908       if (ShiftAmt == 0 || ShiftAmt > 4)
6909         return false;
6910       break;
6911     }
6912     case Instruction::Trunc:
6913       // Check if this is a noop.
6914       // trunc(sext ty1 to ty2) to ty1.
6915       if (Instr->getType() == Ext->getOperand(0)->getType())
6916         continue;
6917     // FALL THROUGH.
6918     default:
6919       return false;
6920     }
6921
6922     // At this point we can use the bfm family, so this extension is free
6923     // for that use.
6924   }
6925   return true;
6926 }
6927
6928 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6929                                           unsigned &RequiredAligment) const {
6930   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6931     return false;
6932   // Cyclone supports unaligned accesses.
6933   RequiredAligment = 0;
6934   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6935   return NumBits == 32 || NumBits == 64;
6936 }
6937
6938 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6939                                           unsigned &RequiredAligment) const {
6940   if (!LoadedType.isSimple() ||
6941       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6942     return false;
6943   // Cyclone supports unaligned accesses.
6944   RequiredAligment = 0;
6945   unsigned NumBits = LoadedType.getSizeInBits();
6946   return NumBits == 32 || NumBits == 64;
6947 }
6948
6949 /// \brief Lower an interleaved load into a ldN intrinsic.
6950 ///
6951 /// E.g. Lower an interleaved load (Factor = 2):
6952 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6953 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6954 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6955 ///
6956 ///      Into:
6957 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6958 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6959 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6960 bool AArch64TargetLowering::lowerInterleavedLoad(
6961     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6962     ArrayRef<unsigned> Indices, unsigned Factor) const {
6963   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6964          "Invalid interleave factor");
6965   assert(!Shuffles.empty() && "Empty shufflevector input");
6966   assert(Shuffles.size() == Indices.size() &&
6967          "Unmatched number of shufflevectors and indices");
6968
6969   const DataLayout &DL = LI->getModule()->getDataLayout();
6970
6971   VectorType *VecTy = Shuffles[0]->getType();
6972   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6973
6974   // Skip illegal vector types.
6975   if (VecSize != 64 && VecSize != 128)
6976     return false;
6977
6978   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6979   // load integer vectors first and then convert to pointer vectors.
6980   Type *EltTy = VecTy->getVectorElementType();
6981   if (EltTy->isPointerTy())
6982     VecTy =
6983         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6984
6985   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6986   Type *Tys[2] = {VecTy, PtrTy};
6987   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6988                                             Intrinsic::aarch64_neon_ld3,
6989                                             Intrinsic::aarch64_neon_ld4};
6990   Function *LdNFunc =
6991       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6992
6993   IRBuilder<> Builder(LI);
6994   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6995
6996   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6997
6998   // Replace uses of each shufflevector with the corresponding vector loaded
6999   // by ldN.
7000   for (unsigned i = 0; i < Shuffles.size(); i++) {
7001     ShuffleVectorInst *SVI = Shuffles[i];
7002     unsigned Index = Indices[i];
7003
7004     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7005
7006     // Convert the integer vector to pointer vector if the element is pointer.
7007     if (EltTy->isPointerTy())
7008       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7009
7010     SVI->replaceAllUsesWith(SubVec);
7011   }
7012
7013   return true;
7014 }
7015
7016 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7017 ///
7018 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7019 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7020                                    unsigned NumElts) {
7021   SmallVector<Constant *, 16> Mask;
7022   for (unsigned i = 0; i < NumElts; i++)
7023     Mask.push_back(Builder.getInt32(Start + i));
7024
7025   return ConstantVector::get(Mask);
7026 }
7027
7028 /// \brief Lower an interleaved store into a stN intrinsic.
7029 ///
7030 /// E.g. Lower an interleaved store (Factor = 3):
7031 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7032 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7033 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7034 ///
7035 ///      Into:
7036 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7037 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7038 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7039 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7040 ///
7041 /// Note that the new shufflevectors will be removed and we'll only generate one
7042 /// st3 instruction in CodeGen.
7043 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7044                                                   ShuffleVectorInst *SVI,
7045                                                   unsigned Factor) const {
7046   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7047          "Invalid interleave factor");
7048
7049   VectorType *VecTy = SVI->getType();
7050   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7051          "Invalid interleaved store");
7052
7053   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7054   Type *EltTy = VecTy->getVectorElementType();
7055   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7056
7057   const DataLayout &DL = SI->getModule()->getDataLayout();
7058   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7059
7060   // Skip illegal vector types.
7061   if (SubVecSize != 64 && SubVecSize != 128)
7062     return false;
7063
7064   Value *Op0 = SVI->getOperand(0);
7065   Value *Op1 = SVI->getOperand(1);
7066   IRBuilder<> Builder(SI);
7067
7068   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7069   // vectors to integer vectors.
7070   if (EltTy->isPointerTy()) {
7071     Type *IntTy = DL.getIntPtrType(EltTy);
7072     unsigned NumOpElts =
7073         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7074
7075     // Convert to the corresponding integer vector.
7076     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7077     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7078     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7079
7080     SubVecTy = VectorType::get(IntTy, NumSubElts);
7081   }
7082
7083   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7084   Type *Tys[2] = {SubVecTy, PtrTy};
7085   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7086                                              Intrinsic::aarch64_neon_st3,
7087                                              Intrinsic::aarch64_neon_st4};
7088   Function *StNFunc =
7089       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7090
7091   SmallVector<Value *, 5> Ops;
7092
7093   // Split the shufflevector operands into sub vectors for the new stN call.
7094   for (unsigned i = 0; i < Factor; i++)
7095     Ops.push_back(Builder.CreateShuffleVector(
7096         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7097
7098   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7099   Builder.CreateCall(StNFunc, Ops);
7100   return true;
7101 }
7102
7103 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7104                        unsigned AlignCheck) {
7105   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7106           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7107 }
7108
7109 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7110                                                unsigned SrcAlign, bool IsMemset,
7111                                                bool ZeroMemset,
7112                                                bool MemcpyStrSrc,
7113                                                MachineFunction &MF) const {
7114   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7115   // instruction to materialize the v2i64 zero and one store (with restrictive
7116   // addressing mode). Just do two i64 store of zero-registers.
7117   bool Fast;
7118   const Function *F = MF.getFunction();
7119   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7120       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7121       (memOpAlign(SrcAlign, DstAlign, 16) ||
7122        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7123     return MVT::f128;
7124
7125   if (Size >= 8 &&
7126       (memOpAlign(SrcAlign, DstAlign, 8) ||
7127        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7128     return MVT::i64;
7129
7130   if (Size >= 4 &&
7131       (memOpAlign(SrcAlign, DstAlign, 4) ||
7132        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7133     return MVT::i32;
7134
7135   return MVT::Other;
7136 }
7137
7138 // 12-bit optionally shifted immediates are legal for adds.
7139 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7140   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7141     return true;
7142   return false;
7143 }
7144
7145 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7146 // immediates is the same as for an add or a sub.
7147 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7148   if (Immed < 0)
7149     Immed *= -1;
7150   return isLegalAddImmediate(Immed);
7151 }
7152
7153 /// isLegalAddressingMode - Return true if the addressing mode represented
7154 /// by AM is legal for this target, for a load/store of the specified type.
7155 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7156                                                   const AddrMode &AM, Type *Ty,
7157                                                   unsigned AS) const {
7158   // AArch64 has five basic addressing modes:
7159   //  reg
7160   //  reg + 9-bit signed offset
7161   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7162   //  reg1 + reg2
7163   //  reg + SIZE_IN_BYTES * reg
7164
7165   // No global is ever allowed as a base.
7166   if (AM.BaseGV)
7167     return false;
7168
7169   // No reg+reg+imm addressing.
7170   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7171     return false;
7172
7173   // check reg + imm case:
7174   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7175   uint64_t NumBytes = 0;
7176   if (Ty->isSized()) {
7177     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7178     NumBytes = NumBits / 8;
7179     if (!isPowerOf2_64(NumBits))
7180       NumBytes = 0;
7181   }
7182
7183   if (!AM.Scale) {
7184     int64_t Offset = AM.BaseOffs;
7185
7186     // 9-bit signed offset
7187     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7188       return true;
7189
7190     // 12-bit unsigned offset
7191     unsigned shift = Log2_64(NumBytes);
7192     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7193         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7194         (Offset >> shift) << shift == Offset)
7195       return true;
7196     return false;
7197   }
7198
7199   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7200
7201   if (!AM.Scale || AM.Scale == 1 ||
7202       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7203     return true;
7204   return false;
7205 }
7206
7207 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7208                                                 const AddrMode &AM, Type *Ty,
7209                                                 unsigned AS) const {
7210   // Scaling factors are not free at all.
7211   // Operands                     | Rt Latency
7212   // -------------------------------------------
7213   // Rt, [Xn, Xm]                 | 4
7214   // -------------------------------------------
7215   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7216   // Rt, [Xn, Wm, <extend> #imm]  |
7217   if (isLegalAddressingMode(DL, AM, Ty, AS))
7218     // Scale represents reg2 * scale, thus account for 1 if
7219     // it is not equal to 0 or 1.
7220     return AM.Scale != 0 && AM.Scale != 1;
7221   return -1;
7222 }
7223
7224 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7225   VT = VT.getScalarType();
7226
7227   if (!VT.isSimple())
7228     return false;
7229
7230   switch (VT.getSimpleVT().SimpleTy) {
7231   case MVT::f32:
7232   case MVT::f64:
7233     return true;
7234   default:
7235     break;
7236   }
7237
7238   return false;
7239 }
7240
7241 const MCPhysReg *
7242 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7243   // LR is a callee-save register, but we must treat it as clobbered by any call
7244   // site. Hence we include LR in the scratch registers, which are in turn added
7245   // as implicit-defs for stackmaps and patchpoints.
7246   static const MCPhysReg ScratchRegs[] = {
7247     AArch64::X16, AArch64::X17, AArch64::LR, 0
7248   };
7249   return ScratchRegs;
7250 }
7251
7252 bool
7253 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7254   EVT VT = N->getValueType(0);
7255     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7256     // it with shift to let it be lowered to UBFX.
7257   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7258       isa<ConstantSDNode>(N->getOperand(1))) {
7259     uint64_t TruncMask = N->getConstantOperandVal(1);
7260     if (isMask_64(TruncMask) &&
7261       N->getOperand(0).getOpcode() == ISD::SRL &&
7262       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7263       return false;
7264   }
7265   return true;
7266 }
7267
7268 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7269                                                               Type *Ty) const {
7270   assert(Ty->isIntegerTy());
7271
7272   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7273   if (BitSize == 0)
7274     return false;
7275
7276   int64_t Val = Imm.getSExtValue();
7277   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7278     return true;
7279
7280   if ((int64_t)Val < 0)
7281     Val = ~Val;
7282   if (BitSize == 32)
7283     Val &= (1LL << 32) - 1;
7284
7285   unsigned LZ = countLeadingZeros((uint64_t)Val);
7286   unsigned Shift = (63 - LZ) / 16;
7287   // MOVZ is free so return true for one or fewer MOVK.
7288   return Shift < 3;
7289 }
7290
7291 // Generate SUBS and CSEL for integer abs.
7292 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7293   EVT VT = N->getValueType(0);
7294
7295   SDValue N0 = N->getOperand(0);
7296   SDValue N1 = N->getOperand(1);
7297   SDLoc DL(N);
7298
7299   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7300   // and change it to SUB and CSEL.
7301   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7302       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7303       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7304     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7305       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7306         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7307                                   N0.getOperand(0));
7308         // Generate SUBS & CSEL.
7309         SDValue Cmp =
7310             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7311                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7312         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7313                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7314                            SDValue(Cmp.getNode(), 1));
7315       }
7316   return SDValue();
7317 }
7318
7319 // performXorCombine - Attempts to handle integer ABS.
7320 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7321                                  TargetLowering::DAGCombinerInfo &DCI,
7322                                  const AArch64Subtarget *Subtarget) {
7323   if (DCI.isBeforeLegalizeOps())
7324     return SDValue();
7325
7326   return performIntegerAbsCombine(N, DAG);
7327 }
7328
7329 SDValue
7330 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7331                                      SelectionDAG &DAG,
7332                                      std::vector<SDNode *> *Created) const {
7333   // fold (sdiv X, pow2)
7334   EVT VT = N->getValueType(0);
7335   if ((VT != MVT::i32 && VT != MVT::i64) ||
7336       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7337     return SDValue();
7338
7339   SDLoc DL(N);
7340   SDValue N0 = N->getOperand(0);
7341   unsigned Lg2 = Divisor.countTrailingZeros();
7342   SDValue Zero = DAG.getConstant(0, DL, VT);
7343   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7344
7345   // Add (N0 < 0) ? Pow2 - 1 : 0;
7346   SDValue CCVal;
7347   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7348   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7349   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7350
7351   if (Created) {
7352     Created->push_back(Cmp.getNode());
7353     Created->push_back(Add.getNode());
7354     Created->push_back(CSel.getNode());
7355   }
7356
7357   // Divide by pow2.
7358   SDValue SRA =
7359       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7360
7361   // If we're dividing by a positive value, we're done.  Otherwise, we must
7362   // negate the result.
7363   if (Divisor.isNonNegative())
7364     return SRA;
7365
7366   if (Created)
7367     Created->push_back(SRA.getNode());
7368   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7369 }
7370
7371 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7372                                  TargetLowering::DAGCombinerInfo &DCI,
7373                                  const AArch64Subtarget *Subtarget) {
7374   if (DCI.isBeforeLegalizeOps())
7375     return SDValue();
7376
7377   // Multiplication of a power of two plus/minus one can be done more
7378   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7379   // future CPUs have a cheaper MADD instruction, this may need to be
7380   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7381   // 64-bit is 5 cycles, so this is always a win.
7382   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7383     APInt Value = C->getAPIntValue();
7384     EVT VT = N->getValueType(0);
7385     SDLoc DL(N);
7386     if (Value.isNonNegative()) {
7387       // (mul x, 2^N + 1) => (add (shl x, N), x)
7388       APInt VM1 = Value - 1;
7389       if (VM1.isPowerOf2()) {
7390         SDValue ShiftedVal =
7391             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7392                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7393         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7394                            N->getOperand(0));
7395       }
7396       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7397       APInt VP1 = Value + 1;
7398       if (VP1.isPowerOf2()) {
7399         SDValue ShiftedVal =
7400             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7401                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7402         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7403                            N->getOperand(0));
7404       }
7405     } else {
7406       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7407       APInt VNP1 = -Value + 1;
7408       if (VNP1.isPowerOf2()) {
7409         SDValue ShiftedVal =
7410             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7411                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7412         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7413                            ShiftedVal);
7414       }
7415       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7416       APInt VNM1 = -Value - 1;
7417       if (VNM1.isPowerOf2()) {
7418         SDValue ShiftedVal =
7419             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7420                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7421         SDValue Add =
7422             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7423         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7424       }
7425     }
7426   }
7427   return SDValue();
7428 }
7429
7430 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7431                                                          SelectionDAG &DAG) {
7432   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7433   // optimize away operation when it's from a constant.
7434   //
7435   // The general transformation is:
7436   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7437   //       AND(VECTOR_CMP(x,y), constant2)
7438   //    constant2 = UNARYOP(constant)
7439
7440   // Early exit if this isn't a vector operation, the operand of the
7441   // unary operation isn't a bitwise AND, or if the sizes of the operations
7442   // aren't the same.
7443   EVT VT = N->getValueType(0);
7444   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7445       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7446       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7447     return SDValue();
7448
7449   // Now check that the other operand of the AND is a constant. We could
7450   // make the transformation for non-constant splats as well, but it's unclear
7451   // that would be a benefit as it would not eliminate any operations, just
7452   // perform one more step in scalar code before moving to the vector unit.
7453   if (BuildVectorSDNode *BV =
7454           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7455     // Bail out if the vector isn't a constant.
7456     if (!BV->isConstant())
7457       return SDValue();
7458
7459     // Everything checks out. Build up the new and improved node.
7460     SDLoc DL(N);
7461     EVT IntVT = BV->getValueType(0);
7462     // Create a new constant of the appropriate type for the transformed
7463     // DAG.
7464     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7465     // The AND node needs bitcasts to/from an integer vector type around it.
7466     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7467     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7468                                  N->getOperand(0)->getOperand(0), MaskConst);
7469     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7470     return Res;
7471   }
7472
7473   return SDValue();
7474 }
7475
7476 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7477                                      const AArch64Subtarget *Subtarget) {
7478   // First try to optimize away the conversion when it's conditionally from
7479   // a constant. Vectors only.
7480   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7481     return Res;
7482
7483   EVT VT = N->getValueType(0);
7484   if (VT != MVT::f32 && VT != MVT::f64)
7485     return SDValue();
7486
7487   // Only optimize when the source and destination types have the same width.
7488   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7489     return SDValue();
7490
7491   // If the result of an integer load is only used by an integer-to-float
7492   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7493   // This eliminates an "integer-to-vector-move UOP and improve throughput.
7494   SDValue N0 = N->getOperand(0);
7495   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7496       // Do not change the width of a volatile load.
7497       !cast<LoadSDNode>(N0)->isVolatile()) {
7498     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7499     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7500                                LN0->getPointerInfo(), LN0->isVolatile(),
7501                                LN0->isNonTemporal(), LN0->isInvariant(),
7502                                LN0->getAlignment());
7503
7504     // Make sure successors of the original load stay after it by updating them
7505     // to use the new Chain.
7506     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7507
7508     unsigned Opcode =
7509         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7510     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7511   }
7512
7513   return SDValue();
7514 }
7515
7516 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7517 /// searches for and classifies those shifts.
7518 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7519                          bool &FromHi) {
7520   if (N.getOpcode() == ISD::SHL)
7521     FromHi = false;
7522   else if (N.getOpcode() == ISD::SRL)
7523     FromHi = true;
7524   else
7525     return false;
7526
7527   if (!isa<ConstantSDNode>(N.getOperand(1)))
7528     return false;
7529
7530   ShiftAmount = N->getConstantOperandVal(1);
7531   Src = N->getOperand(0);
7532   return true;
7533 }
7534
7535 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7536 /// registers viewed as a high/low pair. This function looks for the pattern:
7537 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7538 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7539 /// independent.
7540 static SDValue tryCombineToEXTR(SDNode *N,
7541                                 TargetLowering::DAGCombinerInfo &DCI) {
7542   SelectionDAG &DAG = DCI.DAG;
7543   SDLoc DL(N);
7544   EVT VT = N->getValueType(0);
7545
7546   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7547
7548   if (VT != MVT::i32 && VT != MVT::i64)
7549     return SDValue();
7550
7551   SDValue LHS;
7552   uint32_t ShiftLHS = 0;
7553   bool LHSFromHi = 0;
7554   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7555     return SDValue();
7556
7557   SDValue RHS;
7558   uint32_t ShiftRHS = 0;
7559   bool RHSFromHi = 0;
7560   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7561     return SDValue();
7562
7563   // If they're both trying to come from the high part of the register, they're
7564   // not really an EXTR.
7565   if (LHSFromHi == RHSFromHi)
7566     return SDValue();
7567
7568   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7569     return SDValue();
7570
7571   if (LHSFromHi) {
7572     std::swap(LHS, RHS);
7573     std::swap(ShiftLHS, ShiftRHS);
7574   }
7575
7576   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7577                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7578 }
7579
7580 static SDValue tryCombineToBSL(SDNode *N,
7581                                 TargetLowering::DAGCombinerInfo &DCI) {
7582   EVT VT = N->getValueType(0);
7583   SelectionDAG &DAG = DCI.DAG;
7584   SDLoc DL(N);
7585
7586   if (!VT.isVector())
7587     return SDValue();
7588
7589   SDValue N0 = N->getOperand(0);
7590   if (N0.getOpcode() != ISD::AND)
7591     return SDValue();
7592
7593   SDValue N1 = N->getOperand(1);
7594   if (N1.getOpcode() != ISD::AND)
7595     return SDValue();
7596
7597   // We only have to look for constant vectors here since the general, variable
7598   // case can be handled in TableGen.
7599   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7600   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7601   for (int i = 1; i >= 0; --i)
7602     for (int j = 1; j >= 0; --j) {
7603       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7604       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7605       if (!BVN0 || !BVN1)
7606         continue;
7607
7608       bool FoundMatch = true;
7609       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7610         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7611         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7612         if (!CN0 || !CN1 ||
7613             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7614           FoundMatch = false;
7615           break;
7616         }
7617       }
7618
7619       if (FoundMatch)
7620         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7621                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7622     }
7623
7624   return SDValue();
7625 }
7626
7627 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7628                                 const AArch64Subtarget *Subtarget) {
7629   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7630   if (!EnableAArch64ExtrGeneration)
7631     return SDValue();
7632   SelectionDAG &DAG = DCI.DAG;
7633   EVT VT = N->getValueType(0);
7634
7635   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7636     return SDValue();
7637
7638   SDValue Res = tryCombineToEXTR(N, DCI);
7639   if (Res.getNode())
7640     return Res;
7641
7642   Res = tryCombineToBSL(N, DCI);
7643   if (Res.getNode())
7644     return Res;
7645
7646   return SDValue();
7647 }
7648
7649 static SDValue performBitcastCombine(SDNode *N,
7650                                      TargetLowering::DAGCombinerInfo &DCI,
7651                                      SelectionDAG &DAG) {
7652   // Wait 'til after everything is legalized to try this. That way we have
7653   // legal vector types and such.
7654   if (DCI.isBeforeLegalizeOps())
7655     return SDValue();
7656
7657   // Remove extraneous bitcasts around an extract_subvector.
7658   // For example,
7659   //    (v4i16 (bitconvert
7660   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7661   //  becomes
7662   //    (extract_subvector ((v8i16 ...), (i64 4)))
7663
7664   // Only interested in 64-bit vectors as the ultimate result.
7665   EVT VT = N->getValueType(0);
7666   if (!VT.isVector())
7667     return SDValue();
7668   if (VT.getSimpleVT().getSizeInBits() != 64)
7669     return SDValue();
7670   // Is the operand an extract_subvector starting at the beginning or halfway
7671   // point of the vector? A low half may also come through as an
7672   // EXTRACT_SUBREG, so look for that, too.
7673   SDValue Op0 = N->getOperand(0);
7674   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7675       !(Op0->isMachineOpcode() &&
7676         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7677     return SDValue();
7678   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7679   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7680     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7681       return SDValue();
7682   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7683     if (idx != AArch64::dsub)
7684       return SDValue();
7685     // The dsub reference is equivalent to a lane zero subvector reference.
7686     idx = 0;
7687   }
7688   // Look through the bitcast of the input to the extract.
7689   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7690     return SDValue();
7691   SDValue Source = Op0->getOperand(0)->getOperand(0);
7692   // If the source type has twice the number of elements as our destination
7693   // type, we know this is an extract of the high or low half of the vector.
7694   EVT SVT = Source->getValueType(0);
7695   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7696     return SDValue();
7697
7698   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7699
7700   // Create the simplified form to just extract the low or high half of the
7701   // vector directly rather than bothering with the bitcasts.
7702   SDLoc dl(N);
7703   unsigned NumElements = VT.getVectorNumElements();
7704   if (idx) {
7705     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7706     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7707   } else {
7708     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7709     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7710                                       Source, SubReg),
7711                    0);
7712   }
7713 }
7714
7715 static SDValue performConcatVectorsCombine(SDNode *N,
7716                                            TargetLowering::DAGCombinerInfo &DCI,
7717                                            SelectionDAG &DAG) {
7718   SDLoc dl(N);
7719   EVT VT = N->getValueType(0);
7720   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7721
7722   // Optimize concat_vectors of truncated vectors, where the intermediate
7723   // type is illegal, to avoid said illegality,  e.g.,
7724   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7725   //                          (v2i16 (truncate (v2i64)))))
7726   // ->
7727   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7728   //                                    (v4i32 (bitcast (v2i64))),
7729   //                                    <0, 2, 4, 6>)))
7730   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7731   // on both input and result type, so we might generate worse code.
7732   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7733   if (N->getNumOperands() == 2 &&
7734       N0->getOpcode() == ISD::TRUNCATE &&
7735       N1->getOpcode() == ISD::TRUNCATE) {
7736     SDValue N00 = N0->getOperand(0);
7737     SDValue N10 = N1->getOperand(0);
7738     EVT N00VT = N00.getValueType();
7739
7740     if (N00VT == N10.getValueType() &&
7741         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7742         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7743       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7744       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7745       for (size_t i = 0; i < Mask.size(); ++i)
7746         Mask[i] = i * 2;
7747       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7748                          DAG.getVectorShuffle(
7749                              MidVT, dl,
7750                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7751                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7752     }
7753   }
7754
7755   // Wait 'til after everything is legalized to try this. That way we have
7756   // legal vector types and such.
7757   if (DCI.isBeforeLegalizeOps())
7758     return SDValue();
7759
7760   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7761   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7762   // canonicalise to that.
7763   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7764     assert(VT.getVectorElementType().getSizeInBits() == 64);
7765     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7766                        DAG.getConstant(0, dl, MVT::i64));
7767   }
7768
7769   // Canonicalise concat_vectors so that the right-hand vector has as few
7770   // bit-casts as possible before its real operation. The primary matching
7771   // destination for these operations will be the narrowing "2" instructions,
7772   // which depend on the operation being performed on this right-hand vector.
7773   // For example,
7774   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7775   // becomes
7776   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7777
7778   if (N1->getOpcode() != ISD::BITCAST)
7779     return SDValue();
7780   SDValue RHS = N1->getOperand(0);
7781   MVT RHSTy = RHS.getValueType().getSimpleVT();
7782   // If the RHS is not a vector, this is not the pattern we're looking for.
7783   if (!RHSTy.isVector())
7784     return SDValue();
7785
7786   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7787
7788   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7789                                   RHSTy.getVectorNumElements() * 2);
7790   return DAG.getNode(ISD::BITCAST, dl, VT,
7791                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7792                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7793                                  RHS));
7794 }
7795
7796 static SDValue tryCombineFixedPointConvert(SDNode *N,
7797                                            TargetLowering::DAGCombinerInfo &DCI,
7798                                            SelectionDAG &DAG) {
7799   // Wait 'til after everything is legalized to try this. That way we have
7800   // legal vector types and such.
7801   if (DCI.isBeforeLegalizeOps())
7802     return SDValue();
7803   // Transform a scalar conversion of a value from a lane extract into a
7804   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7805   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7806   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7807   //
7808   // The second form interacts better with instruction selection and the
7809   // register allocator to avoid cross-class register copies that aren't
7810   // coalescable due to a lane reference.
7811
7812   // Check the operand and see if it originates from a lane extract.
7813   SDValue Op1 = N->getOperand(1);
7814   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7815     // Yep, no additional predication needed. Perform the transform.
7816     SDValue IID = N->getOperand(0);
7817     SDValue Shift = N->getOperand(2);
7818     SDValue Vec = Op1.getOperand(0);
7819     SDValue Lane = Op1.getOperand(1);
7820     EVT ResTy = N->getValueType(0);
7821     EVT VecResTy;
7822     SDLoc DL(N);
7823
7824     // The vector width should be 128 bits by the time we get here, even
7825     // if it started as 64 bits (the extract_vector handling will have
7826     // done so).
7827     assert(Vec.getValueType().getSizeInBits() == 128 &&
7828            "unexpected vector size on extract_vector_elt!");
7829     if (Vec.getValueType() == MVT::v4i32)
7830       VecResTy = MVT::v4f32;
7831     else if (Vec.getValueType() == MVT::v2i64)
7832       VecResTy = MVT::v2f64;
7833     else
7834       llvm_unreachable("unexpected vector type!");
7835
7836     SDValue Convert =
7837         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7838     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7839   }
7840   return SDValue();
7841 }
7842
7843 // AArch64 high-vector "long" operations are formed by performing the non-high
7844 // version on an extract_subvector of each operand which gets the high half:
7845 //
7846 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7847 //
7848 // However, there are cases which don't have an extract_high explicitly, but
7849 // have another operation that can be made compatible with one for free. For
7850 // example:
7851 //
7852 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7853 //
7854 // This routine does the actual conversion of such DUPs, once outer routines
7855 // have determined that everything else is in order.
7856 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7857 // similarly here.
7858 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7859   switch (N.getOpcode()) {
7860   case AArch64ISD::DUP:
7861   case AArch64ISD::DUPLANE8:
7862   case AArch64ISD::DUPLANE16:
7863   case AArch64ISD::DUPLANE32:
7864   case AArch64ISD::DUPLANE64:
7865   case AArch64ISD::MOVI:
7866   case AArch64ISD::MOVIshift:
7867   case AArch64ISD::MOVIedit:
7868   case AArch64ISD::MOVImsl:
7869   case AArch64ISD::MVNIshift:
7870   case AArch64ISD::MVNImsl:
7871     break;
7872   default:
7873     // FMOV could be supported, but isn't very useful, as it would only occur
7874     // if you passed a bitcast' floating point immediate to an eligible long
7875     // integer op (addl, smull, ...).
7876     return SDValue();
7877   }
7878
7879   MVT NarrowTy = N.getSimpleValueType();
7880   if (!NarrowTy.is64BitVector())
7881     return SDValue();
7882
7883   MVT ElementTy = NarrowTy.getVectorElementType();
7884   unsigned NumElems = NarrowTy.getVectorNumElements();
7885   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7886
7887   SDLoc dl(N);
7888   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7889                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
7890                      DAG.getConstant(NumElems, dl, MVT::i64));
7891 }
7892
7893 static bool isEssentiallyExtractSubvector(SDValue N) {
7894   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7895     return true;
7896
7897   return N.getOpcode() == ISD::BITCAST &&
7898          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7899 }
7900
7901 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7902 struct GenericSetCCInfo {
7903   const SDValue *Opnd0;
7904   const SDValue *Opnd1;
7905   ISD::CondCode CC;
7906 };
7907
7908 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7909 struct AArch64SetCCInfo {
7910   const SDValue *Cmp;
7911   AArch64CC::CondCode CC;
7912 };
7913
7914 /// \brief Helper structure to keep track of SetCC information.
7915 union SetCCInfo {
7916   GenericSetCCInfo Generic;
7917   AArch64SetCCInfo AArch64;
7918 };
7919
7920 /// \brief Helper structure to be able to read SetCC information.  If set to
7921 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7922 /// GenericSetCCInfo.
7923 struct SetCCInfoAndKind {
7924   SetCCInfo Info;
7925   bool IsAArch64;
7926 };
7927
7928 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7929 /// an
7930 /// AArch64 lowered one.
7931 /// \p SetCCInfo is filled accordingly.
7932 /// \post SetCCInfo is meanginfull only when this function returns true.
7933 /// \return True when Op is a kind of SET_CC operation.
7934 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7935   // If this is a setcc, this is straight forward.
7936   if (Op.getOpcode() == ISD::SETCC) {
7937     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7938     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7939     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7940     SetCCInfo.IsAArch64 = false;
7941     return true;
7942   }
7943   // Otherwise, check if this is a matching csel instruction.
7944   // In other words:
7945   // - csel 1, 0, cc
7946   // - csel 0, 1, !cc
7947   if (Op.getOpcode() != AArch64ISD::CSEL)
7948     return false;
7949   // Set the information about the operands.
7950   // TODO: we want the operands of the Cmp not the csel
7951   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7952   SetCCInfo.IsAArch64 = true;
7953   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7954       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7955
7956   // Check that the operands matches the constraints:
7957   // (1) Both operands must be constants.
7958   // (2) One must be 1 and the other must be 0.
7959   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7960   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7961
7962   // Check (1).
7963   if (!TValue || !FValue)
7964     return false;
7965
7966   // Check (2).
7967   if (!TValue->isOne()) {
7968     // Update the comparison when we are interested in !cc.
7969     std::swap(TValue, FValue);
7970     SetCCInfo.Info.AArch64.CC =
7971         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7972   }
7973   return TValue->isOne() && FValue->isNullValue();
7974 }
7975
7976 // Returns true if Op is setcc or zext of setcc.
7977 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7978   if (isSetCC(Op, Info))
7979     return true;
7980   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7981     isSetCC(Op->getOperand(0), Info));
7982 }
7983
7984 // The folding we want to perform is:
7985 // (add x, [zext] (setcc cc ...) )
7986 //   -->
7987 // (csel x, (add x, 1), !cc ...)
7988 //
7989 // The latter will get matched to a CSINC instruction.
7990 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7991   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7992   SDValue LHS = Op->getOperand(0);
7993   SDValue RHS = Op->getOperand(1);
7994   SetCCInfoAndKind InfoAndKind;
7995
7996   // If neither operand is a SET_CC, give up.
7997   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7998     std::swap(LHS, RHS);
7999     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8000       return SDValue();
8001   }
8002
8003   // FIXME: This could be generatized to work for FP comparisons.
8004   EVT CmpVT = InfoAndKind.IsAArch64
8005                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8006                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8007   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8008     return SDValue();
8009
8010   SDValue CCVal;
8011   SDValue Cmp;
8012   SDLoc dl(Op);
8013   if (InfoAndKind.IsAArch64) {
8014     CCVal = DAG.getConstant(
8015         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8016         MVT::i32);
8017     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8018   } else
8019     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8020                       *InfoAndKind.Info.Generic.Opnd1,
8021                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8022                       CCVal, DAG, dl);
8023
8024   EVT VT = Op->getValueType(0);
8025   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8026   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8027 }
8028
8029 // The basic add/sub long vector instructions have variants with "2" on the end
8030 // which act on the high-half of their inputs. They are normally matched by
8031 // patterns like:
8032 //
8033 // (add (zeroext (extract_high LHS)),
8034 //      (zeroext (extract_high RHS)))
8035 // -> uaddl2 vD, vN, vM
8036 //
8037 // However, if one of the extracts is something like a duplicate, this
8038 // instruction can still be used profitably. This function puts the DAG into a
8039 // more appropriate form for those patterns to trigger.
8040 static SDValue performAddSubLongCombine(SDNode *N,
8041                                         TargetLowering::DAGCombinerInfo &DCI,
8042                                         SelectionDAG &DAG) {
8043   if (DCI.isBeforeLegalizeOps())
8044     return SDValue();
8045
8046   MVT VT = N->getSimpleValueType(0);
8047   if (!VT.is128BitVector()) {
8048     if (N->getOpcode() == ISD::ADD)
8049       return performSetccAddFolding(N, DAG);
8050     return SDValue();
8051   }
8052
8053   // Make sure both branches are extended in the same way.
8054   SDValue LHS = N->getOperand(0);
8055   SDValue RHS = N->getOperand(1);
8056   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8057        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8058       LHS.getOpcode() != RHS.getOpcode())
8059     return SDValue();
8060
8061   unsigned ExtType = LHS.getOpcode();
8062
8063   // It's not worth doing if at least one of the inputs isn't already an
8064   // extract, but we don't know which it'll be so we have to try both.
8065   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8066     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8067     if (!RHS.getNode())
8068       return SDValue();
8069
8070     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8071   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8072     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8073     if (!LHS.getNode())
8074       return SDValue();
8075
8076     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8077   }
8078
8079   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8080 }
8081
8082 // Massage DAGs which we can use the high-half "long" operations on into
8083 // something isel will recognize better. E.g.
8084 //
8085 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8086 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8087 //                     (extract_high (v2i64 (dup128 scalar)))))
8088 //
8089 static SDValue tryCombineLongOpWithDup(SDNode *N,
8090                                        TargetLowering::DAGCombinerInfo &DCI,
8091                                        SelectionDAG &DAG) {
8092   if (DCI.isBeforeLegalizeOps())
8093     return SDValue();
8094
8095   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8096   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8097   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8098   assert(LHS.getValueType().is64BitVector() &&
8099          RHS.getValueType().is64BitVector() &&
8100          "unexpected shape for long operation");
8101
8102   // Either node could be a DUP, but it's not worth doing both of them (you'd
8103   // just as well use the non-high version) so look for a corresponding extract
8104   // operation on the other "wing".
8105   if (isEssentiallyExtractSubvector(LHS)) {
8106     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8107     if (!RHS.getNode())
8108       return SDValue();
8109   } else if (isEssentiallyExtractSubvector(RHS)) {
8110     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8111     if (!LHS.getNode())
8112       return SDValue();
8113   }
8114
8115   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8116   if (IsIntrinsic)
8117     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8118                        N->getOperand(0), LHS, RHS);
8119   else
8120     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8121                        LHS, RHS);
8122 }
8123
8124 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8125   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8126   unsigned ElemBits = ElemTy.getSizeInBits();
8127
8128   int64_t ShiftAmount;
8129   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8130     APInt SplatValue, SplatUndef;
8131     unsigned SplatBitSize;
8132     bool HasAnyUndefs;
8133     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8134                               HasAnyUndefs, ElemBits) ||
8135         SplatBitSize != ElemBits)
8136       return SDValue();
8137
8138     ShiftAmount = SplatValue.getSExtValue();
8139   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8140     ShiftAmount = CVN->getSExtValue();
8141   } else
8142     return SDValue();
8143
8144   unsigned Opcode;
8145   bool IsRightShift;
8146   switch (IID) {
8147   default:
8148     llvm_unreachable("Unknown shift intrinsic");
8149   case Intrinsic::aarch64_neon_sqshl:
8150     Opcode = AArch64ISD::SQSHL_I;
8151     IsRightShift = false;
8152     break;
8153   case Intrinsic::aarch64_neon_uqshl:
8154     Opcode = AArch64ISD::UQSHL_I;
8155     IsRightShift = false;
8156     break;
8157   case Intrinsic::aarch64_neon_srshl:
8158     Opcode = AArch64ISD::SRSHR_I;
8159     IsRightShift = true;
8160     break;
8161   case Intrinsic::aarch64_neon_urshl:
8162     Opcode = AArch64ISD::URSHR_I;
8163     IsRightShift = true;
8164     break;
8165   case Intrinsic::aarch64_neon_sqshlu:
8166     Opcode = AArch64ISD::SQSHLU_I;
8167     IsRightShift = false;
8168     break;
8169   }
8170
8171   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8172     SDLoc dl(N);
8173     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8174                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8175   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8176     SDLoc dl(N);
8177     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8178                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8179   }
8180
8181   return SDValue();
8182 }
8183
8184 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8185 // the intrinsics must be legal and take an i32, this means there's almost
8186 // certainly going to be a zext in the DAG which we can eliminate.
8187 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8188   SDValue AndN = N->getOperand(2);
8189   if (AndN.getOpcode() != ISD::AND)
8190     return SDValue();
8191
8192   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8193   if (!CMask || CMask->getZExtValue() != Mask)
8194     return SDValue();
8195
8196   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8197                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8198 }
8199
8200 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8201                                            SelectionDAG &DAG) {
8202   SDLoc dl(N);
8203   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8204                      DAG.getNode(Opc, dl,
8205                                  N->getOperand(1).getSimpleValueType(),
8206                                  N->getOperand(1)),
8207                      DAG.getConstant(0, dl, MVT::i64));
8208 }
8209
8210 static SDValue performIntrinsicCombine(SDNode *N,
8211                                        TargetLowering::DAGCombinerInfo &DCI,
8212                                        const AArch64Subtarget *Subtarget) {
8213   SelectionDAG &DAG = DCI.DAG;
8214   unsigned IID = getIntrinsicID(N);
8215   switch (IID) {
8216   default:
8217     break;
8218   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8219   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8220     return tryCombineFixedPointConvert(N, DCI, DAG);
8221   case Intrinsic::aarch64_neon_saddv:
8222     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8223   case Intrinsic::aarch64_neon_uaddv:
8224     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8225   case Intrinsic::aarch64_neon_sminv:
8226     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8227   case Intrinsic::aarch64_neon_uminv:
8228     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8229   case Intrinsic::aarch64_neon_smaxv:
8230     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8231   case Intrinsic::aarch64_neon_umaxv:
8232     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8233   case Intrinsic::aarch64_neon_fmax:
8234     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8235                        N->getOperand(1), N->getOperand(2));
8236   case Intrinsic::aarch64_neon_fmin:
8237     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8238                        N->getOperand(1), N->getOperand(2));
8239   case Intrinsic::aarch64_neon_sabd:
8240     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8241                        N->getOperand(1), N->getOperand(2));
8242   case Intrinsic::aarch64_neon_uabd:
8243     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8244                        N->getOperand(1), N->getOperand(2));
8245   case Intrinsic::aarch64_neon_fmaxnm:
8246     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8247                        N->getOperand(1), N->getOperand(2));
8248   case Intrinsic::aarch64_neon_fminnm:
8249     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8250                        N->getOperand(1), N->getOperand(2));
8251   case Intrinsic::aarch64_neon_smull:
8252   case Intrinsic::aarch64_neon_umull:
8253   case Intrinsic::aarch64_neon_pmull:
8254   case Intrinsic::aarch64_neon_sqdmull:
8255     return tryCombineLongOpWithDup(N, DCI, DAG);
8256   case Intrinsic::aarch64_neon_sqshl:
8257   case Intrinsic::aarch64_neon_uqshl:
8258   case Intrinsic::aarch64_neon_sqshlu:
8259   case Intrinsic::aarch64_neon_srshl:
8260   case Intrinsic::aarch64_neon_urshl:
8261     return tryCombineShiftImm(IID, N, DAG);
8262   case Intrinsic::aarch64_crc32b:
8263   case Intrinsic::aarch64_crc32cb:
8264     return tryCombineCRC32(0xff, N, DAG);
8265   case Intrinsic::aarch64_crc32h:
8266   case Intrinsic::aarch64_crc32ch:
8267     return tryCombineCRC32(0xffff, N, DAG);
8268   }
8269   return SDValue();
8270 }
8271
8272 static SDValue performExtendCombine(SDNode *N,
8273                                     TargetLowering::DAGCombinerInfo &DCI,
8274                                     SelectionDAG &DAG) {
8275   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8276   // we can convert that DUP into another extract_high (of a bigger DUP), which
8277   // helps the backend to decide that an sabdl2 would be useful, saving a real
8278   // extract_high operation.
8279   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8280       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8281        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8282     SDNode *ABDNode = N->getOperand(0).getNode();
8283     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8284     if (!NewABD.getNode())
8285       return SDValue();
8286
8287     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8288                        NewABD);
8289   }
8290
8291   // This is effectively a custom type legalization for AArch64.
8292   //
8293   // Type legalization will split an extend of a small, legal, type to a larger
8294   // illegal type by first splitting the destination type, often creating
8295   // illegal source types, which then get legalized in isel-confusing ways,
8296   // leading to really terrible codegen. E.g.,
8297   //   %result = v8i32 sext v8i8 %value
8298   // becomes
8299   //   %losrc = extract_subreg %value, ...
8300   //   %hisrc = extract_subreg %value, ...
8301   //   %lo = v4i32 sext v4i8 %losrc
8302   //   %hi = v4i32 sext v4i8 %hisrc
8303   // Things go rapidly downhill from there.
8304   //
8305   // For AArch64, the [sz]ext vector instructions can only go up one element
8306   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8307   // take two instructions.
8308   //
8309   // This implies that the most efficient way to do the extend from v8i8
8310   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8311   // the normal splitting to happen for the v8i16->v8i32.
8312
8313   // This is pre-legalization to catch some cases where the default
8314   // type legalization will create ill-tempered code.
8315   if (!DCI.isBeforeLegalizeOps())
8316     return SDValue();
8317
8318   // We're only interested in cleaning things up for non-legal vector types
8319   // here. If both the source and destination are legal, things will just
8320   // work naturally without any fiddling.
8321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8322   EVT ResVT = N->getValueType(0);
8323   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8324     return SDValue();
8325   // If the vector type isn't a simple VT, it's beyond the scope of what
8326   // we're  worried about here. Let legalization do its thing and hope for
8327   // the best.
8328   SDValue Src = N->getOperand(0);
8329   EVT SrcVT = Src->getValueType(0);
8330   if (!ResVT.isSimple() || !SrcVT.isSimple())
8331     return SDValue();
8332
8333   // If the source VT is a 64-bit vector, we can play games and get the
8334   // better results we want.
8335   if (SrcVT.getSizeInBits() != 64)
8336     return SDValue();
8337
8338   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8339   unsigned ElementCount = SrcVT.getVectorNumElements();
8340   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8341   SDLoc DL(N);
8342   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8343
8344   // Now split the rest of the operation into two halves, each with a 64
8345   // bit source.
8346   EVT LoVT, HiVT;
8347   SDValue Lo, Hi;
8348   unsigned NumElements = ResVT.getVectorNumElements();
8349   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8350   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8351                                  ResVT.getVectorElementType(), NumElements / 2);
8352
8353   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8354                                LoVT.getVectorNumElements());
8355   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8356                    DAG.getConstant(0, DL, MVT::i64));
8357   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8358                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8359   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8360   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8361
8362   // Now combine the parts back together so we still have a single result
8363   // like the combiner expects.
8364   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8365 }
8366
8367 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8368 /// value. The load store optimizer pass will merge them to store pair stores.
8369 /// This has better performance than a splat of the scalar followed by a split
8370 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8371 /// followed by an ext.b and two stores.
8372 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8373   SDValue StVal = St->getValue();
8374   EVT VT = StVal.getValueType();
8375
8376   // Don't replace floating point stores, they possibly won't be transformed to
8377   // stp because of the store pair suppress pass.
8378   if (VT.isFloatingPoint())
8379     return SDValue();
8380
8381   // Check for insert vector elements.
8382   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8383     return SDValue();
8384
8385   // We can express a splat as store pair(s) for 2 or 4 elements.
8386   unsigned NumVecElts = VT.getVectorNumElements();
8387   if (NumVecElts != 4 && NumVecElts != 2)
8388     return SDValue();
8389   SDValue SplatVal = StVal.getOperand(1);
8390   unsigned RemainInsertElts = NumVecElts - 1;
8391
8392   // Check that this is a splat.
8393   while (--RemainInsertElts) {
8394     SDValue NextInsertElt = StVal.getOperand(0);
8395     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8396       return SDValue();
8397     if (NextInsertElt.getOperand(1) != SplatVal)
8398       return SDValue();
8399     StVal = NextInsertElt;
8400   }
8401   unsigned OrigAlignment = St->getAlignment();
8402   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8403   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8404
8405   // Create scalar stores. This is at least as good as the code sequence for a
8406   // split unaligned store which is a dup.s, ext.b, and two stores.
8407   // Most of the time the three stores should be replaced by store pair
8408   // instructions (stp).
8409   SDLoc DL(St);
8410   SDValue BasePtr = St->getBasePtr();
8411   SDValue NewST1 =
8412       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8413                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8414
8415   unsigned Offset = EltOffset;
8416   while (--NumVecElts) {
8417     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8418                                     DAG.getConstant(Offset, DL, MVT::i64));
8419     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8420                           St->getPointerInfo(), St->isVolatile(),
8421                           St->isNonTemporal(), Alignment);
8422     Offset += EltOffset;
8423   }
8424   return NewST1;
8425 }
8426
8427 static SDValue performSTORECombine(SDNode *N,
8428                                    TargetLowering::DAGCombinerInfo &DCI,
8429                                    SelectionDAG &DAG,
8430                                    const AArch64Subtarget *Subtarget) {
8431   if (!DCI.isBeforeLegalize())
8432     return SDValue();
8433
8434   StoreSDNode *S = cast<StoreSDNode>(N);
8435   if (S->isVolatile())
8436     return SDValue();
8437
8438   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8439   // page boundaries. We want to split such stores.
8440   if (!Subtarget->isCyclone())
8441     return SDValue();
8442
8443   // Don't split at -Oz.
8444   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8445     return SDValue();
8446
8447   SDValue StVal = S->getValue();
8448   EVT VT = StVal.getValueType();
8449
8450   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8451   // those up regresses performance on micro-benchmarks and olden/bh.
8452   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8453     return SDValue();
8454
8455   // Split unaligned 16B stores. They are terrible for performance.
8456   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8457   // extensions can use this to mark that it does not want splitting to happen
8458   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8459   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8460   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8461       S->getAlignment() <= 2)
8462     return SDValue();
8463
8464   // If we get a splat of a scalar convert this vector store to a store of
8465   // scalars. They will be merged into store pairs thereby removing two
8466   // instructions.
8467   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8468     return ReplacedSplat;
8469
8470   SDLoc DL(S);
8471   unsigned NumElts = VT.getVectorNumElements() / 2;
8472   // Split VT into two.
8473   EVT HalfVT =
8474       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8475   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8476                                    DAG.getConstant(0, DL, MVT::i64));
8477   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8478                                    DAG.getConstant(NumElts, DL, MVT::i64));
8479   SDValue BasePtr = S->getBasePtr();
8480   SDValue NewST1 =
8481       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8482                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8483   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8484                                   DAG.getConstant(8, DL, MVT::i64));
8485   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8486                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8487                       S->getAlignment());
8488 }
8489
8490 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8491 /// post-increment LD1R.
8492 static SDValue performPostLD1Combine(SDNode *N,
8493                                      TargetLowering::DAGCombinerInfo &DCI,
8494                                      bool IsLaneOp) {
8495   if (DCI.isBeforeLegalizeOps())
8496     return SDValue();
8497
8498   SelectionDAG &DAG = DCI.DAG;
8499   EVT VT = N->getValueType(0);
8500
8501   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8502   SDNode *LD = N->getOperand(LoadIdx).getNode();
8503   // If it is not LOAD, can not do such combine.
8504   if (LD->getOpcode() != ISD::LOAD)
8505     return SDValue();
8506
8507   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8508   EVT MemVT = LoadSDN->getMemoryVT();
8509   // Check if memory operand is the same type as the vector element.
8510   if (MemVT != VT.getVectorElementType())
8511     return SDValue();
8512
8513   // Check if there are other uses. If so, do not combine as it will introduce
8514   // an extra load.
8515   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8516        ++UI) {
8517     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8518       continue;
8519     if (*UI != N)
8520       return SDValue();
8521   }
8522
8523   SDValue Addr = LD->getOperand(1);
8524   SDValue Vector = N->getOperand(0);
8525   // Search for a use of the address operand that is an increment.
8526   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8527        Addr.getNode()->use_end(); UI != UE; ++UI) {
8528     SDNode *User = *UI;
8529     if (User->getOpcode() != ISD::ADD
8530         || UI.getUse().getResNo() != Addr.getResNo())
8531       continue;
8532
8533     // Check that the add is independent of the load.  Otherwise, folding it
8534     // would create a cycle.
8535     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8536       continue;
8537     // Also check that add is not used in the vector operand.  This would also
8538     // create a cycle.
8539     if (User->isPredecessorOf(Vector.getNode()))
8540       continue;
8541
8542     // If the increment is a constant, it must match the memory ref size.
8543     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8544     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8545       uint32_t IncVal = CInc->getZExtValue();
8546       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8547       if (IncVal != NumBytes)
8548         continue;
8549       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8550     }
8551
8552     // Finally, check that the vector doesn't depend on the load.
8553     // Again, this would create a cycle.
8554     // The load depending on the vector is fine, as that's the case for the
8555     // LD1*post we'll eventually generate anyway.
8556     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8557       continue;
8558
8559     SmallVector<SDValue, 8> Ops;
8560     Ops.push_back(LD->getOperand(0));  // Chain
8561     if (IsLaneOp) {
8562       Ops.push_back(Vector);           // The vector to be inserted
8563       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8564     }
8565     Ops.push_back(Addr);
8566     Ops.push_back(Inc);
8567
8568     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8569     SDVTList SDTys = DAG.getVTList(Tys);
8570     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8571     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8572                                            MemVT,
8573                                            LoadSDN->getMemOperand());
8574
8575     // Update the uses.
8576     SmallVector<SDValue, 2> NewResults;
8577     NewResults.push_back(SDValue(LD, 0));             // The result of load
8578     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8579     DCI.CombineTo(LD, NewResults);
8580     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8581     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8582
8583     break;
8584   }
8585   return SDValue();
8586 }
8587
8588 /// Target-specific DAG combine for the across vector reduction.
8589 /// This function specifically handles the final clean-up step of a vector
8590 /// reduction produced by the LoopVectorizer. It is the log2-shuffle pattern,
8591 /// consisting of log2(NumVectorElements) steps and, in each step, 2^(s)
8592 /// elements are reduced, where s is an induction variable from 0
8593 /// to log2(NumVectorElements).
8594 /// For example,
8595 ///   %1 = vector_shuffle %0, <2,3,u,u>
8596 ///   %2 = add %0, %1
8597 ///   %3 = vector_shuffle %2, <1,u,u,u>
8598 ///   %4 = add %2, %3
8599 ///   %5 = extract_vector_elt %4, 0
8600 /// becomes :
8601 ///   %0 = uaddv %0
8602 ///   %1 = extract_vector_elt %0, 0
8603 ///
8604 /// FIXME: Currently this function is implemented and tested specifically
8605 /// for the add reduction. We could also support other types of across lane
8606 /// reduction available in AArch64, including SMAXV, SMINV, UMAXV, UMINV,
8607 /// SADDLV, UADDLV, FMAXNMV, FMAXV, FMINNMV, FMINV.
8608 static SDValue
8609 performAcrossLaneReductionCombine(SDNode *N, SelectionDAG &DAG,
8610                                   const AArch64Subtarget *Subtarget) {
8611   if (!Subtarget->hasNEON())
8612     return SDValue();
8613   SDValue N0 = N->getOperand(0);
8614   SDValue N1 = N->getOperand(1);
8615
8616   // Check if the input vector is fed by the operator we want to handle.
8617   // We specifically check only ADD for now.
8618   if (N0->getOpcode() != ISD::ADD)
8619     return SDValue();
8620
8621   // The vector extract idx must constant zero because we only expect the final
8622   // result of the reduction is placed in lane 0.
8623   if (!isa<ConstantSDNode>(N1) || cast<ConstantSDNode>(N1)->getZExtValue())
8624     return SDValue();
8625
8626   EVT EltTy = N0.getValueType().getVectorElementType();
8627   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8628     return SDValue();
8629
8630   int NumVecElts = N0.getValueType().getVectorNumElements();
8631   if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8632     return SDValue();
8633
8634   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8635   SDValue PreOp = N0;
8636   // Iterate over each step of the across vector reduction.
8637   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8638     // We specifically check ADD for now.
8639     if (PreOp.getOpcode() != ISD::ADD)
8640       return SDValue();
8641     SDValue CurOp = PreOp.getOperand(0);
8642     SDValue Shuffle = PreOp.getOperand(1);
8643     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8644       // Try to swap the 1st and 2nd operand as add is commutative.
8645       CurOp = PreOp.getOperand(1);
8646       Shuffle = PreOp.getOperand(0);
8647       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8648         return SDValue();
8649     }
8650     // Check if it forms one step of the across vector reduction.
8651     // E.g.,
8652     //   %cur = add %1, %0
8653     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8654     //   %pre = add %cur, %shuffle
8655     if (Shuffle.getOperand(0) != CurOp)
8656       return SDValue();
8657
8658     int NumMaskElts = 1 << CurStep;
8659     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8660     // Check mask values in each step.
8661     // We expect the shuffle mask in each step follows a specific pattern
8662     // denoted here by the <M, U> form, where M is a sequence of integers
8663     // starting from NumMaskElts, increasing by 1, and the number integers
8664     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8665     // of undef in U should be NumVecElts - NumMaskElts.
8666     // E.g., for <8 x i16>, mask values in each step should be :
8667     //   step 0 : <1,u,u,u,u,u,u,u>
8668     //   step 1 : <2,3,u,u,u,u,u,u>
8669     //   step 2 : <4,5,6,7,u,u,u,u>
8670     for (int i = 0; i < NumVecElts; ++i)
8671       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8672           (i >= NumMaskElts && !(Mask[i] < 0)))
8673         return SDValue();
8674
8675     PreOp = CurOp;
8676   }
8677   SDLoc DL(N);
8678   return DAG.getNode(
8679       ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8680       DAG.getNode(AArch64ISD::UADDV, DL, PreOp.getSimpleValueType(), PreOp),
8681       DAG.getConstant(0, DL, MVT::i64));
8682 }
8683
8684 /// Target-specific DAG combine function for NEON load/store intrinsics
8685 /// to merge base address updates.
8686 static SDValue performNEONPostLDSTCombine(SDNode *N,
8687                                           TargetLowering::DAGCombinerInfo &DCI,
8688                                           SelectionDAG &DAG) {
8689   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8690     return SDValue();
8691
8692   unsigned AddrOpIdx = N->getNumOperands() - 1;
8693   SDValue Addr = N->getOperand(AddrOpIdx);
8694
8695   // Search for a use of the address operand that is an increment.
8696   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8697        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8698     SDNode *User = *UI;
8699     if (User->getOpcode() != ISD::ADD ||
8700         UI.getUse().getResNo() != Addr.getResNo())
8701       continue;
8702
8703     // Check that the add is independent of the load/store.  Otherwise, folding
8704     // it would create a cycle.
8705     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8706       continue;
8707
8708     // Find the new opcode for the updating load/store.
8709     bool IsStore = false;
8710     bool IsLaneOp = false;
8711     bool IsDupOp = false;
8712     unsigned NewOpc = 0;
8713     unsigned NumVecs = 0;
8714     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8715     switch (IntNo) {
8716     default: llvm_unreachable("unexpected intrinsic for Neon base update");
8717     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
8718       NumVecs = 2; break;
8719     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
8720       NumVecs = 3; break;
8721     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
8722       NumVecs = 4; break;
8723     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
8724       NumVecs = 2; IsStore = true; break;
8725     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
8726       NumVecs = 3; IsStore = true; break;
8727     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
8728       NumVecs = 4; IsStore = true; break;
8729     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
8730       NumVecs = 2; break;
8731     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
8732       NumVecs = 3; break;
8733     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
8734       NumVecs = 4; break;
8735     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
8736       NumVecs = 2; IsStore = true; break;
8737     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
8738       NumVecs = 3; IsStore = true; break;
8739     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
8740       NumVecs = 4; IsStore = true; break;
8741     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
8742       NumVecs = 2; IsDupOp = true; break;
8743     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
8744       NumVecs = 3; IsDupOp = true; break;
8745     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
8746       NumVecs = 4; IsDupOp = true; break;
8747     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
8748       NumVecs = 2; IsLaneOp = true; break;
8749     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
8750       NumVecs = 3; IsLaneOp = true; break;
8751     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
8752       NumVecs = 4; IsLaneOp = true; break;
8753     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
8754       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8755     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
8756       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8757     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
8758       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8759     }
8760
8761     EVT VecTy;
8762     if (IsStore)
8763       VecTy = N->getOperand(2).getValueType();
8764     else
8765       VecTy = N->getValueType(0);
8766
8767     // If the increment is a constant, it must match the memory ref size.
8768     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8769     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8770       uint32_t IncVal = CInc->getZExtValue();
8771       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8772       if (IsLaneOp || IsDupOp)
8773         NumBytes /= VecTy.getVectorNumElements();
8774       if (IncVal != NumBytes)
8775         continue;
8776       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8777     }
8778     SmallVector<SDValue, 8> Ops;
8779     Ops.push_back(N->getOperand(0)); // Incoming chain
8780     // Load lane and store have vector list as input.
8781     if (IsLaneOp || IsStore)
8782       for (unsigned i = 2; i < AddrOpIdx; ++i)
8783         Ops.push_back(N->getOperand(i));
8784     Ops.push_back(Addr); // Base register
8785     Ops.push_back(Inc);
8786
8787     // Return Types.
8788     EVT Tys[6];
8789     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8790     unsigned n;
8791     for (n = 0; n < NumResultVecs; ++n)
8792       Tys[n] = VecTy;
8793     Tys[n++] = MVT::i64;  // Type of write back register
8794     Tys[n] = MVT::Other;  // Type of the chain
8795     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8796
8797     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8798     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8799                                            MemInt->getMemoryVT(),
8800                                            MemInt->getMemOperand());
8801
8802     // Update the uses.
8803     std::vector<SDValue> NewResults;
8804     for (unsigned i = 0; i < NumResultVecs; ++i) {
8805       NewResults.push_back(SDValue(UpdN.getNode(), i));
8806     }
8807     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8808     DCI.CombineTo(N, NewResults);
8809     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8810
8811     break;
8812   }
8813   return SDValue();
8814 }
8815
8816 // Checks to see if the value is the prescribed width and returns information
8817 // about its extension mode.
8818 static
8819 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8820   ExtType = ISD::NON_EXTLOAD;
8821   switch(V.getNode()->getOpcode()) {
8822   default:
8823     return false;
8824   case ISD::LOAD: {
8825     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8826     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8827        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8828       ExtType = LoadNode->getExtensionType();
8829       return true;
8830     }
8831     return false;
8832   }
8833   case ISD::AssertSext: {
8834     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8835     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8836        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8837       ExtType = ISD::SEXTLOAD;
8838       return true;
8839     }
8840     return false;
8841   }
8842   case ISD::AssertZext: {
8843     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8844     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8845        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8846       ExtType = ISD::ZEXTLOAD;
8847       return true;
8848     }
8849     return false;
8850   }
8851   case ISD::Constant:
8852   case ISD::TargetConstant: {
8853     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8854         1LL << (width - 1))
8855       return true;
8856     return false;
8857   }
8858   }
8859
8860   return true;
8861 }
8862
8863 // This function does a whole lot of voodoo to determine if the tests are
8864 // equivalent without and with a mask. Essentially what happens is that given a
8865 // DAG resembling:
8866 //
8867 //  +-------------+ +-------------+ +-------------+ +-------------+
8868 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
8869 //  +-------------+ +-------------+ +-------------+ +-------------+
8870 //           |           |           |               |
8871 //           V           V           |    +----------+
8872 //          +-------------+  +----+  |    |
8873 //          |     ADD     |  |0xff|  |    |
8874 //          +-------------+  +----+  |    |
8875 //                  |           |    |    |
8876 //                  V           V    |    |
8877 //                 +-------------+   |    |
8878 //                 |     AND     |   |    |
8879 //                 +-------------+   |    |
8880 //                      |            |    |
8881 //                      +-----+      |    |
8882 //                            |      |    |
8883 //                            V      V    V
8884 //                           +-------------+
8885 //                           |     CMP     |
8886 //                           +-------------+
8887 //
8888 // The AND node may be safely removed for some combinations of inputs. In
8889 // particular we need to take into account the extension type of the Input,
8890 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8891 // width of the input (this can work for any width inputs, the above graph is
8892 // specific to 8 bits.
8893 //
8894 // The specific equations were worked out by generating output tables for each
8895 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8896 // problem was simplified by working with 4 bit inputs, which means we only
8897 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8898 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8899 // patterns present in both extensions (0,7). For every distinct set of
8900 // AddConstant and CompConstants bit patterns we can consider the masked and
8901 // unmasked versions to be equivalent if the result of this function is true for
8902 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8903 //
8904 //   sub      w8, w0, w1
8905 //   and      w10, w8, #0x0f
8906 //   cmp      w8, w2
8907 //   cset     w9, AArch64CC
8908 //   cmp      w10, w2
8909 //   cset     w11, AArch64CC
8910 //   cmp      w9, w11
8911 //   cset     w0, eq
8912 //   ret
8913 //
8914 // Since the above function shows when the outputs are equivalent it defines
8915 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8916 // would be expensive to run during compiles. The equations below were written
8917 // in a test harness that confirmed they gave equivalent outputs to the above
8918 // for all inputs function, so they can be used determine if the removal is
8919 // legal instead.
8920 //
8921 // isEquivalentMaskless() is the code for testing if the AND can be removed
8922 // factored out of the DAG recognition as the DAG can take several forms.
8923
8924 static
8925 bool isEquivalentMaskless(unsigned CC, unsigned width,
8926                           ISD::LoadExtType ExtType, signed AddConstant,
8927                           signed CompConstant) {
8928   // By being careful about our equations and only writing the in term
8929   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8930   // make them generally applicable to all bit widths.
8931   signed MaxUInt = (1 << width);
8932
8933   // For the purposes of these comparisons sign extending the type is
8934   // equivalent to zero extending the add and displacing it by half the integer
8935   // width. Provided we are careful and make sure our equations are valid over
8936   // the whole range we can just adjust the input and avoid writing equations
8937   // for sign extended inputs.
8938   if (ExtType == ISD::SEXTLOAD)
8939     AddConstant -= (1 << (width-1));
8940
8941   switch(CC) {
8942   case AArch64CC::LE:
8943   case AArch64CC::GT: {
8944     if ((AddConstant == 0) ||
8945         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8946         (AddConstant >= 0 && CompConstant < 0) ||
8947         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8948       return true;
8949   } break;
8950   case AArch64CC::LT:
8951   case AArch64CC::GE: {
8952     if ((AddConstant == 0) ||
8953         (AddConstant >= 0 && CompConstant <= 0) ||
8954         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8955       return true;
8956   } break;
8957   case AArch64CC::HI:
8958   case AArch64CC::LS: {
8959     if ((AddConstant >= 0 && CompConstant < 0) ||
8960        (AddConstant <= 0 && CompConstant >= -1 &&
8961         CompConstant < AddConstant + MaxUInt))
8962       return true;
8963   } break;
8964   case AArch64CC::PL:
8965   case AArch64CC::MI: {
8966     if ((AddConstant == 0) ||
8967         (AddConstant > 0 && CompConstant <= 0) ||
8968         (AddConstant < 0 && CompConstant <= AddConstant))
8969       return true;
8970   } break;
8971   case AArch64CC::LO:
8972   case AArch64CC::HS: {
8973     if ((AddConstant >= 0 && CompConstant <= 0) ||
8974         (AddConstant <= 0 && CompConstant >= 0 &&
8975          CompConstant <= AddConstant + MaxUInt))
8976       return true;
8977   } break;
8978   case AArch64CC::EQ:
8979   case AArch64CC::NE: {
8980     if ((AddConstant > 0 && CompConstant < 0) ||
8981         (AddConstant < 0 && CompConstant >= 0 &&
8982          CompConstant < AddConstant + MaxUInt) ||
8983         (AddConstant >= 0 && CompConstant >= 0 &&
8984          CompConstant >= AddConstant) ||
8985         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8986
8987       return true;
8988   } break;
8989   case AArch64CC::VS:
8990   case AArch64CC::VC:
8991   case AArch64CC::AL:
8992   case AArch64CC::NV:
8993     return true;
8994   case AArch64CC::Invalid:
8995     break;
8996   }
8997
8998   return false;
8999 }
9000
9001 static
9002 SDValue performCONDCombine(SDNode *N,
9003                            TargetLowering::DAGCombinerInfo &DCI,
9004                            SelectionDAG &DAG, unsigned CCIndex,
9005                            unsigned CmpIndex) {
9006   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9007   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9008   unsigned CondOpcode = SubsNode->getOpcode();
9009
9010   if (CondOpcode != AArch64ISD::SUBS)
9011     return SDValue();
9012
9013   // There is a SUBS feeding this condition. Is it fed by a mask we can
9014   // use?
9015
9016   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9017   unsigned MaskBits = 0;
9018
9019   if (AndNode->getOpcode() != ISD::AND)
9020     return SDValue();
9021
9022   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9023     uint32_t CNV = CN->getZExtValue();
9024     if (CNV == 255)
9025       MaskBits = 8;
9026     else if (CNV == 65535)
9027       MaskBits = 16;
9028   }
9029
9030   if (!MaskBits)
9031     return SDValue();
9032
9033   SDValue AddValue = AndNode->getOperand(0);
9034
9035   if (AddValue.getOpcode() != ISD::ADD)
9036     return SDValue();
9037
9038   // The basic dag structure is correct, grab the inputs and validate them.
9039
9040   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9041   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9042   SDValue SubsInputValue = SubsNode->getOperand(1);
9043
9044   // The mask is present and the provenance of all the values is a smaller type,
9045   // lets see if the mask is superfluous.
9046
9047   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9048       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9049     return SDValue();
9050
9051   ISD::LoadExtType ExtType;
9052
9053   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9054       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9055       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9056     return SDValue();
9057
9058   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9059                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9060                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9061     return SDValue();
9062
9063   // The AND is not necessary, remove it.
9064
9065   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9066                                SubsNode->getValueType(1));
9067   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9068
9069   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9070   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9071
9072   return SDValue(N, 0);
9073 }
9074
9075 // Optimize compare with zero and branch.
9076 static SDValue performBRCONDCombine(SDNode *N,
9077                                     TargetLowering::DAGCombinerInfo &DCI,
9078                                     SelectionDAG &DAG) {
9079   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9080   if (NV.getNode())
9081     N = NV.getNode();
9082   SDValue Chain = N->getOperand(0);
9083   SDValue Dest = N->getOperand(1);
9084   SDValue CCVal = N->getOperand(2);
9085   SDValue Cmp = N->getOperand(3);
9086
9087   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9088   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9089   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9090     return SDValue();
9091
9092   unsigned CmpOpc = Cmp.getOpcode();
9093   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9094     return SDValue();
9095
9096   // Only attempt folding if there is only one use of the flag and no use of the
9097   // value.
9098   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9099     return SDValue();
9100
9101   SDValue LHS = Cmp.getOperand(0);
9102   SDValue RHS = Cmp.getOperand(1);
9103
9104   assert(LHS.getValueType() == RHS.getValueType() &&
9105          "Expected the value type to be the same for both operands!");
9106   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9107     return SDValue();
9108
9109   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9110     std::swap(LHS, RHS);
9111
9112   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9113     return SDValue();
9114
9115   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9116       LHS.getOpcode() == ISD::SRL)
9117     return SDValue();
9118
9119   // Fold the compare into the branch instruction.
9120   SDValue BR;
9121   if (CC == AArch64CC::EQ)
9122     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9123   else
9124     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9125
9126   // Do not add new nodes to DAG combiner worklist.
9127   DCI.CombineTo(N, BR, false);
9128
9129   return SDValue();
9130 }
9131
9132 // vselect (v1i1 setcc) ->
9133 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9134 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9135 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9136 // such VSELECT.
9137 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9138   SDValue N0 = N->getOperand(0);
9139   EVT CCVT = N0.getValueType();
9140
9141   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9142       CCVT.getVectorElementType() != MVT::i1)
9143     return SDValue();
9144
9145   EVT ResVT = N->getValueType(0);
9146   EVT CmpVT = N0.getOperand(0).getValueType();
9147   // Only combine when the result type is of the same size as the compared
9148   // operands.
9149   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9150     return SDValue();
9151
9152   SDValue IfTrue = N->getOperand(1);
9153   SDValue IfFalse = N->getOperand(2);
9154   SDValue SetCC =
9155       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9156                    N0.getOperand(0), N0.getOperand(1),
9157                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9158   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9159                      IfTrue, IfFalse);
9160 }
9161
9162 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9163 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9164 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9165 /// with a vector one followed by a DUP shuffle on the result.
9166 static SDValue performSelectCombine(SDNode *N,
9167                                     TargetLowering::DAGCombinerInfo &DCI) {
9168   SelectionDAG &DAG = DCI.DAG;
9169   SDValue N0 = N->getOperand(0);
9170   EVT ResVT = N->getValueType(0);
9171
9172   if (N0.getOpcode() != ISD::SETCC)
9173     return SDValue();
9174
9175   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9176   // scalar SetCCResultType. We also don't expect vectors, because we assume
9177   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9178   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9179          "Scalar-SETCC feeding SELECT has unexpected result type!");
9180
9181   // If NumMaskElts == 0, the comparison is larger than select result. The
9182   // largest real NEON comparison is 64-bits per lane, which means the result is
9183   // at most 32-bits and an illegal vector. Just bail out for now.
9184   EVT SrcVT = N0.getOperand(0).getValueType();
9185
9186   // Don't try to do this optimization when the setcc itself has i1 operands.
9187   // There are no legal vectors of i1, so this would be pointless.
9188   if (SrcVT == MVT::i1)
9189     return SDValue();
9190
9191   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9192   if (!ResVT.isVector() || NumMaskElts == 0)
9193     return SDValue();
9194
9195   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9196   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9197
9198   // Also bail out if the vector CCVT isn't the same size as ResVT.
9199   // This can happen if the SETCC operand size doesn't divide the ResVT size
9200   // (e.g., f64 vs v3f32).
9201   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9202     return SDValue();
9203
9204   // Make sure we didn't create illegal types, if we're not supposed to.
9205   assert(DCI.isBeforeLegalize() ||
9206          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9207
9208   // First perform a vector comparison, where lane 0 is the one we're interested
9209   // in.
9210   SDLoc DL(N0);
9211   SDValue LHS =
9212       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9213   SDValue RHS =
9214       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9215   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9216
9217   // Now duplicate the comparison mask we want across all other lanes.
9218   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9219   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9220   Mask = DAG.getNode(ISD::BITCAST, DL,
9221                      ResVT.changeVectorElementTypeToInteger(), Mask);
9222
9223   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9224 }
9225
9226 /// Get rid of unnecessary NVCASTs (that don't change the type).
9227 static SDValue performNVCASTCombine(SDNode *N) {
9228   if (N->getValueType(0) == N->getOperand(0).getValueType())
9229     return N->getOperand(0);
9230
9231   return SDValue();
9232 }
9233
9234 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9235                                                  DAGCombinerInfo &DCI) const {
9236   SelectionDAG &DAG = DCI.DAG;
9237   switch (N->getOpcode()) {
9238   default:
9239     break;
9240   case ISD::ADD:
9241   case ISD::SUB:
9242     return performAddSubLongCombine(N, DCI, DAG);
9243   case ISD::XOR:
9244     return performXorCombine(N, DAG, DCI, Subtarget);
9245   case ISD::MUL:
9246     return performMulCombine(N, DAG, DCI, Subtarget);
9247   case ISD::SINT_TO_FP:
9248   case ISD::UINT_TO_FP:
9249     return performIntToFpCombine(N, DAG, Subtarget);
9250   case ISD::OR:
9251     return performORCombine(N, DCI, Subtarget);
9252   case ISD::INTRINSIC_WO_CHAIN:
9253     return performIntrinsicCombine(N, DCI, Subtarget);
9254   case ISD::ANY_EXTEND:
9255   case ISD::ZERO_EXTEND:
9256   case ISD::SIGN_EXTEND:
9257     return performExtendCombine(N, DCI, DAG);
9258   case ISD::BITCAST:
9259     return performBitcastCombine(N, DCI, DAG);
9260   case ISD::CONCAT_VECTORS:
9261     return performConcatVectorsCombine(N, DCI, DAG);
9262   case ISD::SELECT:
9263     return performSelectCombine(N, DCI);
9264   case ISD::VSELECT:
9265     return performVSelectCombine(N, DCI.DAG);
9266   case ISD::STORE:
9267     return performSTORECombine(N, DCI, DAG, Subtarget);
9268   case AArch64ISD::BRCOND:
9269     return performBRCONDCombine(N, DCI, DAG);
9270   case AArch64ISD::CSEL:
9271     return performCONDCombine(N, DCI, DAG, 2, 3);
9272   case AArch64ISD::DUP:
9273     return performPostLD1Combine(N, DCI, false);
9274   case AArch64ISD::NVCAST:
9275     return performNVCASTCombine(N);
9276   case ISD::INSERT_VECTOR_ELT:
9277     return performPostLD1Combine(N, DCI, true);
9278   case ISD::EXTRACT_VECTOR_ELT:
9279     return performAcrossLaneReductionCombine(N, DAG, Subtarget);
9280   case ISD::INTRINSIC_VOID:
9281   case ISD::INTRINSIC_W_CHAIN:
9282     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9283     case Intrinsic::aarch64_neon_ld2:
9284     case Intrinsic::aarch64_neon_ld3:
9285     case Intrinsic::aarch64_neon_ld4:
9286     case Intrinsic::aarch64_neon_ld1x2:
9287     case Intrinsic::aarch64_neon_ld1x3:
9288     case Intrinsic::aarch64_neon_ld1x4:
9289     case Intrinsic::aarch64_neon_ld2lane:
9290     case Intrinsic::aarch64_neon_ld3lane:
9291     case Intrinsic::aarch64_neon_ld4lane:
9292     case Intrinsic::aarch64_neon_ld2r:
9293     case Intrinsic::aarch64_neon_ld3r:
9294     case Intrinsic::aarch64_neon_ld4r:
9295     case Intrinsic::aarch64_neon_st2:
9296     case Intrinsic::aarch64_neon_st3:
9297     case Intrinsic::aarch64_neon_st4:
9298     case Intrinsic::aarch64_neon_st1x2:
9299     case Intrinsic::aarch64_neon_st1x3:
9300     case Intrinsic::aarch64_neon_st1x4:
9301     case Intrinsic::aarch64_neon_st2lane:
9302     case Intrinsic::aarch64_neon_st3lane:
9303     case Intrinsic::aarch64_neon_st4lane:
9304       return performNEONPostLDSTCombine(N, DCI, DAG);
9305     default:
9306       break;
9307     }
9308   }
9309   return SDValue();
9310 }
9311
9312 // Check if the return value is used as only a return value, as otherwise
9313 // we can't perform a tail-call. In particular, we need to check for
9314 // target ISD nodes that are returns and any other "odd" constructs
9315 // that the generic analysis code won't necessarily catch.
9316 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9317                                                SDValue &Chain) const {
9318   if (N->getNumValues() != 1)
9319     return false;
9320   if (!N->hasNUsesOfValue(1, 0))
9321     return false;
9322
9323   SDValue TCChain = Chain;
9324   SDNode *Copy = *N->use_begin();
9325   if (Copy->getOpcode() == ISD::CopyToReg) {
9326     // If the copy has a glue operand, we conservatively assume it isn't safe to
9327     // perform a tail call.
9328     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9329         MVT::Glue)
9330       return false;
9331     TCChain = Copy->getOperand(0);
9332   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9333     return false;
9334
9335   bool HasRet = false;
9336   for (SDNode *Node : Copy->uses()) {
9337     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9338       return false;
9339     HasRet = true;
9340   }
9341
9342   if (!HasRet)
9343     return false;
9344
9345   Chain = TCChain;
9346   return true;
9347 }
9348
9349 // Return whether the an instruction can potentially be optimized to a tail
9350 // call. This will cause the optimizers to attempt to move, or duplicate,
9351 // return instructions to help enable tail call optimizations for this
9352 // instruction.
9353 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9354   if (!CI->isTailCall())
9355     return false;
9356
9357   return true;
9358 }
9359
9360 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9361                                                    SDValue &Offset,
9362                                                    ISD::MemIndexedMode &AM,
9363                                                    bool &IsInc,
9364                                                    SelectionDAG &DAG) const {
9365   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9366     return false;
9367
9368   Base = Op->getOperand(0);
9369   // All of the indexed addressing mode instructions take a signed
9370   // 9 bit immediate offset.
9371   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9372     int64_t RHSC = (int64_t)RHS->getZExtValue();
9373     if (RHSC >= 256 || RHSC <= -256)
9374       return false;
9375     IsInc = (Op->getOpcode() == ISD::ADD);
9376     Offset = Op->getOperand(1);
9377     return true;
9378   }
9379   return false;
9380 }
9381
9382 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9383                                                       SDValue &Offset,
9384                                                       ISD::MemIndexedMode &AM,
9385                                                       SelectionDAG &DAG) const {
9386   EVT VT;
9387   SDValue Ptr;
9388   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9389     VT = LD->getMemoryVT();
9390     Ptr = LD->getBasePtr();
9391   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9392     VT = ST->getMemoryVT();
9393     Ptr = ST->getBasePtr();
9394   } else
9395     return false;
9396
9397   bool IsInc;
9398   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9399     return false;
9400   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9401   return true;
9402 }
9403
9404 bool AArch64TargetLowering::getPostIndexedAddressParts(
9405     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9406     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9407   EVT VT;
9408   SDValue Ptr;
9409   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9410     VT = LD->getMemoryVT();
9411     Ptr = LD->getBasePtr();
9412   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9413     VT = ST->getMemoryVT();
9414     Ptr = ST->getBasePtr();
9415   } else
9416     return false;
9417
9418   bool IsInc;
9419   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9420     return false;
9421   // Post-indexing updates the base, so it's not a valid transform
9422   // if that's not the same as the load's pointer.
9423   if (Ptr != Base)
9424     return false;
9425   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9426   return true;
9427 }
9428
9429 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9430                                   SelectionDAG &DAG) {
9431   SDLoc DL(N);
9432   SDValue Op = N->getOperand(0);
9433
9434   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9435     return;
9436
9437   Op = SDValue(
9438       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9439                          DAG.getUNDEF(MVT::i32), Op,
9440                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9441       0);
9442   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9443   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9444 }
9445
9446 void AArch64TargetLowering::ReplaceNodeResults(
9447     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9448   switch (N->getOpcode()) {
9449   default:
9450     llvm_unreachable("Don't know how to custom expand this");
9451   case ISD::BITCAST:
9452     ReplaceBITCASTResults(N, Results, DAG);
9453     return;
9454   case ISD::FP_TO_UINT:
9455   case ISD::FP_TO_SINT:
9456     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9457     // Let normal code take care of it by not adding anything to Results.
9458     return;
9459   }
9460 }
9461
9462 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9463   return true;
9464 }
9465
9466 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9467   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9468   // reciprocal if there are three or more FDIVs.
9469   return 3;
9470 }
9471
9472 TargetLoweringBase::LegalizeTypeAction
9473 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9474   MVT SVT = VT.getSimpleVT();
9475   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9476   // v4i16, v2i32 instead of to promote.
9477   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9478       || SVT == MVT::v1f32)
9479     return TypeWidenVector;
9480
9481   return TargetLoweringBase::getPreferredVectorAction(VT);
9482 }
9483
9484 // Loads and stores less than 128-bits are already atomic; ones above that
9485 // are doomed anyway, so defer to the default libcall and blame the OS when
9486 // things go wrong.
9487 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9488   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9489   return Size == 128;
9490 }
9491
9492 // Loads and stores less than 128-bits are already atomic; ones above that
9493 // are doomed anyway, so defer to the default libcall and blame the OS when
9494 // things go wrong.
9495 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9496   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9497   return Size == 128;
9498 }
9499
9500 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9501 TargetLoweringBase::AtomicRMWExpansionKind
9502 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9503   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9504   return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9505                      : AtomicRMWExpansionKind::None;
9506 }
9507
9508 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9509   return true;
9510 }
9511
9512 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9513                                              AtomicOrdering Ord) const {
9514   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9515   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9516   bool IsAcquire = isAtLeastAcquire(Ord);
9517
9518   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9519   // intrinsic must return {i64, i64} and we have to recombine them into a
9520   // single i128 here.
9521   if (ValTy->getPrimitiveSizeInBits() == 128) {
9522     Intrinsic::ID Int =
9523         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9524     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9525
9526     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9527     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9528
9529     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9530     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9531     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9532     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9533     return Builder.CreateOr(
9534         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9535   }
9536
9537   Type *Tys[] = { Addr->getType() };
9538   Intrinsic::ID Int =
9539       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9540   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9541
9542   return Builder.CreateTruncOrBitCast(
9543       Builder.CreateCall(Ldxr, Addr),
9544       cast<PointerType>(Addr->getType())->getElementType());
9545 }
9546
9547 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9548                                                    Value *Val, Value *Addr,
9549                                                    AtomicOrdering Ord) const {
9550   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9551   bool IsRelease = isAtLeastRelease(Ord);
9552
9553   // Since the intrinsics must have legal type, the i128 intrinsics take two
9554   // parameters: "i64, i64". We must marshal Val into the appropriate form
9555   // before the call.
9556   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9557     Intrinsic::ID Int =
9558         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9559     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9560     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9561
9562     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9563     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9564     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9565     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9566   }
9567
9568   Intrinsic::ID Int =
9569       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9570   Type *Tys[] = { Addr->getType() };
9571   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9572
9573   return Builder.CreateCall(Stxr,
9574                             {Builder.CreateZExtOrBitCast(
9575                                  Val, Stxr->getFunctionType()->getParamType(0)),
9576                              Addr});
9577 }
9578
9579 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9580     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9581   return Ty->isArrayTy();
9582 }
9583
9584 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9585                                                             EVT) const {
9586   return false;
9587 }