[safestack] Fast access to the unsafe stack pointer on AArch64/Android.
[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::FP_TO_SINT);
482   setTargetDAGCombine(ISD::FP_TO_UINT);
483   setTargetDAGCombine(ISD::FDIV);
484
485   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
486
487   setTargetDAGCombine(ISD::ANY_EXTEND);
488   setTargetDAGCombine(ISD::ZERO_EXTEND);
489   setTargetDAGCombine(ISD::SIGN_EXTEND);
490   setTargetDAGCombine(ISD::BITCAST);
491   setTargetDAGCombine(ISD::CONCAT_VECTORS);
492   setTargetDAGCombine(ISD::STORE);
493
494   setTargetDAGCombine(ISD::MUL);
495
496   setTargetDAGCombine(ISD::SELECT);
497   setTargetDAGCombine(ISD::VSELECT);
498
499   setTargetDAGCombine(ISD::INTRINSIC_VOID);
500   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
501   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
502   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
503
504   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
505   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
506   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
507
508   setStackPointerRegisterToSaveRestore(AArch64::SP);
509
510   setSchedulingPreference(Sched::Hybrid);
511
512   // Enable TBZ/TBNZ
513   MaskAndBranchFoldingIsLegal = true;
514   EnableExtLdPromotion = true;
515
516   setMinFunctionAlignment(2);
517
518   setHasExtractBitsInsn(true);
519
520   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
521
522   if (Subtarget->hasNEON()) {
523     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
524     // silliness like this:
525     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
526     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
528     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
529     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
532     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
533     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
534     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
535     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
536     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
537     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
538     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
539     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
542     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
543     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
544     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
545     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
546     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
547     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
548     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
549     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
550
551     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
552     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
553     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
554     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
555     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
556
557     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
558
559     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
560     // elements smaller than i32, so promote the input to i32 first.
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
564     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
565     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
566     // -> v8f16 conversions.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
571     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
576     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
577     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
578     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
580
581     // AArch64 doesn't have MUL.2d:
582     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
583     // Custom handling for some quad-vector types to detect MULL.
584     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
585     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
586     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
587
588     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
589     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
590     // Likewise, narrowing and extending vector loads/stores aren't handled
591     // directly.
592     for (MVT VT : MVT::vector_valuetypes()) {
593       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
594
595       setOperationAction(ISD::MULHS, VT, Expand);
596       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
597       setOperationAction(ISD::MULHU, VT, Expand);
598       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
599
600       setOperationAction(ISD::BSWAP, VT, Expand);
601
602       for (MVT InnerVT : MVT::vector_valuetypes()) {
603         setTruncStoreAction(VT, InnerVT, Expand);
604         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
607       }
608     }
609
610     // AArch64 has implementations of a lot of rounding-like FP operations.
611     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
612       setOperationAction(ISD::FFLOOR, Ty, Legal);
613       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
614       setOperationAction(ISD::FCEIL, Ty, Legal);
615       setOperationAction(ISD::FRINT, Ty, Legal);
616       setOperationAction(ISD::FTRUNC, Ty, Legal);
617       setOperationAction(ISD::FROUND, Ty, Legal);
618     }
619   }
620
621   // Prefer likely predicted branches to selects on out-of-order cores.
622   if (Subtarget->isCortexA57())
623     PredictableSelectIsExpensive = true;
624 }
625
626 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
627   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
628     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
629     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
630
631     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
632     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
633   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
634     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
635     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
636
637     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
638     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
639   }
640
641   // Mark vector float intrinsics as expand.
642   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
643     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
652
653     // But we do support custom-lowering for FCOPYSIGN.
654     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
655   }
656
657   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
669
670   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
671   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
672   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
673   for (MVT InnerVT : MVT::all_valuetypes())
674     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
675
676   // CNT supports only B element sizes.
677   if (VT != MVT::v8i8 && VT != MVT::v16i8)
678     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
679
680   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
681   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
682   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
683   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
684   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
685
686   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
687   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
688
689   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
690   // i64.
691   if (!VT.isFloatingPoint() &&
692       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
693     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
694                             ISD::SABSDIFF, ISD::UABSDIFF})
695       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
696
697   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
698   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
699     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
700                             ISD::FMINNUM, ISD::FMAXNUM})
701       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
702
703   if (Subtarget->isLittleEndian()) {
704     for (unsigned im = (unsigned)ISD::PRE_INC;
705          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
707       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
708     }
709   }
710 }
711
712 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
713   addRegisterClass(VT, &AArch64::FPR64RegClass);
714   addTypeForNEON(VT, MVT::v2i32);
715 }
716
717 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
718   addRegisterClass(VT, &AArch64::FPR128RegClass);
719   addTypeForNEON(VT, MVT::v4i32);
720 }
721
722 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
723                                               EVT VT) const {
724   if (!VT.isVector())
725     return MVT::i32;
726   return VT.changeVectorElementTypeToInteger();
727 }
728
729 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
730 /// Mask are known to be either zero or one and return them in the
731 /// KnownZero/KnownOne bitsets.
732 void AArch64TargetLowering::computeKnownBitsForTargetNode(
733     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
734     const SelectionDAG &DAG, unsigned Depth) const {
735   switch (Op.getOpcode()) {
736   default:
737     break;
738   case AArch64ISD::CSEL: {
739     APInt KnownZero2, KnownOne2;
740     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
741     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
742     KnownZero &= KnownZero2;
743     KnownOne &= KnownOne2;
744     break;
745   }
746   case ISD::INTRINSIC_W_CHAIN: {
747     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
748     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
749     switch (IntID) {
750     default: return;
751     case Intrinsic::aarch64_ldaxr:
752     case Intrinsic::aarch64_ldxr: {
753       unsigned BitWidth = KnownOne.getBitWidth();
754       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
755       unsigned MemBits = VT.getScalarType().getSizeInBits();
756       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
757       return;
758     }
759     }
760     break;
761   }
762   case ISD::INTRINSIC_WO_CHAIN:
763   case ISD::INTRINSIC_VOID: {
764     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
765     switch (IntNo) {
766     default:
767       break;
768     case Intrinsic::aarch64_neon_umaxv:
769     case Intrinsic::aarch64_neon_uminv: {
770       // Figure out the datatype of the vector operand. The UMINV instruction
771       // will zero extend the result, so we can mark as known zero all the
772       // bits larger than the element datatype. 32-bit or larget doesn't need
773       // this as those are legal types and will be handled by isel directly.
774       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
775       unsigned BitWidth = KnownZero.getBitWidth();
776       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
777         assert(BitWidth >= 8 && "Unexpected width!");
778         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
779         KnownZero |= Mask;
780       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
781         assert(BitWidth >= 16 && "Unexpected width!");
782         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
783         KnownZero |= Mask;
784       }
785       break;
786     } break;
787     }
788   }
789   }
790 }
791
792 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
793                                                   EVT) const {
794   return MVT::i64;
795 }
796
797 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
798                                                            unsigned AddrSpace,
799                                                            unsigned Align,
800                                                            bool *Fast) const {
801   if (Subtarget->requiresStrictAlign())
802     return false;
803
804   // FIXME: This is mostly true for Cyclone, but not necessarily others.
805   if (Fast) {
806     // FIXME: Define an attribute for slow unaligned accesses instead of
807     // relying on the CPU type as a proxy.
808     // On Cyclone, unaligned 128-bit stores are slow.
809     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
810             // See comments in performSTORECombine() for more details about
811             // these conditions.
812
813             // Code that uses clang vector extensions can mark that it
814             // wants unaligned accesses to be treated as fast by
815             // underspecifying alignment to be 1 or 2.
816             Align <= 2 ||
817
818             // Disregard v2i64. Memcpy lowering produces those and splitting
819             // them regresses performance on micro-benchmarks and olden/bh.
820             VT == MVT::v2i64;
821   }
822   return true;
823 }
824
825 FastISel *
826 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
827                                       const TargetLibraryInfo *libInfo) const {
828   return AArch64::createFastISel(funcInfo, libInfo);
829 }
830
831 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
832   switch ((AArch64ISD::NodeType)Opcode) {
833   case AArch64ISD::FIRST_NUMBER:      break;
834   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
835   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
836   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
837   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
838   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
839   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
840   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
841   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
842   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
843   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
844   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
845   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
846   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
847   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
848   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
849   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
850   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
851   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
852   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
853   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
854   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
855   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
856   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
857   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
858   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
859   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
860   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
861   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
862   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
863   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
864   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
865   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
866   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
867   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
868   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
869   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
870   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
871   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
872   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
873   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
874   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
875   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
876   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
877   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
878   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
879   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
880   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
881   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
882   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
883   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
884   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
885   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
886   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
887   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
888   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
889   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
890   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
891   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
892   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
893   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
894   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
895   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
896   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
897   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
898   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
899   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
900   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
901   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
902   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
903   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
904   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
905   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
906   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
907   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
908   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
909   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
910   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
911   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
912   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
913   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
914   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
915   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
916   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
917   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
918   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
919   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
920   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
921   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
922   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
923   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
924   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
925   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
926   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
927   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
928   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
929   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
930   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
931   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
932   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
933   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
934   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
935   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
936   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
937   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
938   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
939   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
940   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
941   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
942   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
943   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
944   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
945   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
946   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
947   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
948   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
949   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
950   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
951   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
952   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
953   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
954   }
955   return nullptr;
956 }
957
958 MachineBasicBlock *
959 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
960                                     MachineBasicBlock *MBB) const {
961   // We materialise the F128CSEL pseudo-instruction as some control flow and a
962   // phi node:
963
964   // OrigBB:
965   //     [... previous instrs leading to comparison ...]
966   //     b.ne TrueBB
967   //     b EndBB
968   // TrueBB:
969   //     ; Fallthrough
970   // EndBB:
971   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
972
973   MachineFunction *MF = MBB->getParent();
974   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
975   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
976   DebugLoc DL = MI->getDebugLoc();
977   MachineFunction::iterator It = ++MBB->getIterator();
978
979   unsigned DestReg = MI->getOperand(0).getReg();
980   unsigned IfTrueReg = MI->getOperand(1).getReg();
981   unsigned IfFalseReg = MI->getOperand(2).getReg();
982   unsigned CondCode = MI->getOperand(3).getImm();
983   bool NZCVKilled = MI->getOperand(4).isKill();
984
985   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
986   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
987   MF->insert(It, TrueBB);
988   MF->insert(It, EndBB);
989
990   // Transfer rest of current basic-block to EndBB
991   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
992                 MBB->end());
993   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
994
995   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
996   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
997   MBB->addSuccessor(TrueBB);
998   MBB->addSuccessor(EndBB);
999
1000   // TrueBB falls through to the end.
1001   TrueBB->addSuccessor(EndBB);
1002
1003   if (!NZCVKilled) {
1004     TrueBB->addLiveIn(AArch64::NZCV);
1005     EndBB->addLiveIn(AArch64::NZCV);
1006   }
1007
1008   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1009       .addReg(IfTrueReg)
1010       .addMBB(TrueBB)
1011       .addReg(IfFalseReg)
1012       .addMBB(MBB);
1013
1014   MI->eraseFromParent();
1015   return EndBB;
1016 }
1017
1018 MachineBasicBlock *
1019 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1020                                                  MachineBasicBlock *BB) const {
1021   switch (MI->getOpcode()) {
1022   default:
1023 #ifndef NDEBUG
1024     MI->dump();
1025 #endif
1026     llvm_unreachable("Unexpected instruction for custom inserter!");
1027
1028   case AArch64::F128CSEL:
1029     return EmitF128CSEL(MI, BB);
1030
1031   case TargetOpcode::STACKMAP:
1032   case TargetOpcode::PATCHPOINT:
1033     return emitPatchPoint(MI, BB);
1034   }
1035 }
1036
1037 //===----------------------------------------------------------------------===//
1038 // AArch64 Lowering private implementation.
1039 //===----------------------------------------------------------------------===//
1040
1041 //===----------------------------------------------------------------------===//
1042 // Lowering Code
1043 //===----------------------------------------------------------------------===//
1044
1045 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1046 /// CC
1047 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1048   switch (CC) {
1049   default:
1050     llvm_unreachable("Unknown condition code!");
1051   case ISD::SETNE:
1052     return AArch64CC::NE;
1053   case ISD::SETEQ:
1054     return AArch64CC::EQ;
1055   case ISD::SETGT:
1056     return AArch64CC::GT;
1057   case ISD::SETGE:
1058     return AArch64CC::GE;
1059   case ISD::SETLT:
1060     return AArch64CC::LT;
1061   case ISD::SETLE:
1062     return AArch64CC::LE;
1063   case ISD::SETUGT:
1064     return AArch64CC::HI;
1065   case ISD::SETUGE:
1066     return AArch64CC::HS;
1067   case ISD::SETULT:
1068     return AArch64CC::LO;
1069   case ISD::SETULE:
1070     return AArch64CC::LS;
1071   }
1072 }
1073
1074 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1075 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1076                                   AArch64CC::CondCode &CondCode,
1077                                   AArch64CC::CondCode &CondCode2) {
1078   CondCode2 = AArch64CC::AL;
1079   switch (CC) {
1080   default:
1081     llvm_unreachable("Unknown FP condition!");
1082   case ISD::SETEQ:
1083   case ISD::SETOEQ:
1084     CondCode = AArch64CC::EQ;
1085     break;
1086   case ISD::SETGT:
1087   case ISD::SETOGT:
1088     CondCode = AArch64CC::GT;
1089     break;
1090   case ISD::SETGE:
1091   case ISD::SETOGE:
1092     CondCode = AArch64CC::GE;
1093     break;
1094   case ISD::SETOLT:
1095     CondCode = AArch64CC::MI;
1096     break;
1097   case ISD::SETOLE:
1098     CondCode = AArch64CC::LS;
1099     break;
1100   case ISD::SETONE:
1101     CondCode = AArch64CC::MI;
1102     CondCode2 = AArch64CC::GT;
1103     break;
1104   case ISD::SETO:
1105     CondCode = AArch64CC::VC;
1106     break;
1107   case ISD::SETUO:
1108     CondCode = AArch64CC::VS;
1109     break;
1110   case ISD::SETUEQ:
1111     CondCode = AArch64CC::EQ;
1112     CondCode2 = AArch64CC::VS;
1113     break;
1114   case ISD::SETUGT:
1115     CondCode = AArch64CC::HI;
1116     break;
1117   case ISD::SETUGE:
1118     CondCode = AArch64CC::PL;
1119     break;
1120   case ISD::SETLT:
1121   case ISD::SETULT:
1122     CondCode = AArch64CC::LT;
1123     break;
1124   case ISD::SETLE:
1125   case ISD::SETULE:
1126     CondCode = AArch64CC::LE;
1127     break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE:
1130     CondCode = AArch64CC::NE;
1131     break;
1132   }
1133 }
1134
1135 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1136 /// CC usable with the vector instructions. Fewer operations are available
1137 /// without a real NZCV register, so we have to use less efficient combinations
1138 /// to get the same effect.
1139 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1140                                         AArch64CC::CondCode &CondCode,
1141                                         AArch64CC::CondCode &CondCode2,
1142                                         bool &Invert) {
1143   Invert = false;
1144   switch (CC) {
1145   default:
1146     // Mostly the scalar mappings work fine.
1147     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148     break;
1149   case ISD::SETUO:
1150     Invert = true; // Fallthrough
1151   case ISD::SETO:
1152     CondCode = AArch64CC::MI;
1153     CondCode2 = AArch64CC::GE;
1154     break;
1155   case ISD::SETUEQ:
1156   case ISD::SETULT:
1157   case ISD::SETULE:
1158   case ISD::SETUGT:
1159   case ISD::SETUGE:
1160     // All of the compare-mask comparisons are ordered, but we can switch
1161     // between the two by a double inversion. E.g. ULE == !OGT.
1162     Invert = true;
1163     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1164     break;
1165   }
1166 }
1167
1168 static bool isLegalArithImmed(uint64_t C) {
1169   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1170   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1171 }
1172
1173 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1174                               SDLoc dl, SelectionDAG &DAG) {
1175   EVT VT = LHS.getValueType();
1176
1177   if (VT.isFloatingPoint())
1178     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1179
1180   // The CMP instruction is just an alias for SUBS, and representing it as
1181   // SUBS means that it's possible to get CSE with subtract operations.
1182   // A later phase can perform the optimization of setting the destination
1183   // register to WZR/XZR if it ends up being unused.
1184   unsigned Opcode = AArch64ISD::SUBS;
1185
1186   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1187       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1188       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1189     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1190     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1191     // can be set differently by this operation. It comes down to whether
1192     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1193     // everything is fine. If not then the optimization is wrong. Thus general
1194     // comparisons are only valid if op2 != 0.
1195
1196     // So, finally, the only LLVM-native comparisons that don't mention C and V
1197     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1198     // the absence of information about op2.
1199     Opcode = AArch64ISD::ADDS;
1200     RHS = RHS.getOperand(1);
1201   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1202              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1203              !isUnsignedIntSetCC(CC)) {
1204     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1205     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1206     // of the signed comparisons.
1207     Opcode = AArch64ISD::ANDS;
1208     RHS = LHS.getOperand(1);
1209     LHS = LHS.getOperand(0);
1210   }
1211
1212   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1213       .getValue(1);
1214 }
1215
1216 /// \defgroup AArch64CCMP CMP;CCMP matching
1217 ///
1218 /// These functions deal with the formation of CMP;CCMP;... sequences.
1219 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1220 /// a comparison. They set the NZCV flags to a predefined value if their
1221 /// predicate is false. This allows to express arbitrary conjunctions, for
1222 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1223 /// expressed as:
1224 ///   cmp A
1225 ///   ccmp B, inv(CB), CA
1226 ///   check for CB flags
1227 ///
1228 /// In general we can create code for arbitrary "... (and (and A B) C)"
1229 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1230 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1231 /// negation operations:
1232 /// We can negate the results of a single comparison by inverting the flags
1233 /// used when the predicate fails and inverting the flags tested in the next
1234 /// instruction; We can also negate the results of the whole previous
1235 /// conditional compare sequence by inverting the flags tested in the next
1236 /// instruction. However there is no way to negate the result of a partial
1237 /// sequence.
1238 ///
1239 /// Therefore on encountering an "or" expression we can negate the subtree on
1240 /// one side and have to be able to push the negate to the leafs of the subtree
1241 /// on the other side (see also the comments in code). As complete example:
1242 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1243 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1244 /// is transformed to
1245 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1246 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1247 /// and implemented as:
1248 ///   cmp C
1249 ///   ccmp D, inv(CD), CC
1250 ///   ccmp A, CA, inv(CD)
1251 ///   ccmp B, CB, inv(CA)
1252 ///   check for CB flags
1253 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1254 /// by conditional compare sequences.
1255 /// @{
1256
1257 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1258 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1259                                          ISD::CondCode CC, SDValue CCOp,
1260                                          SDValue Condition, unsigned NZCV,
1261                                          SDLoc DL, SelectionDAG &DAG) {
1262   unsigned Opcode = 0;
1263   if (LHS.getValueType().isFloatingPoint())
1264     Opcode = AArch64ISD::FCCMP;
1265   else if (RHS.getOpcode() == ISD::SUB) {
1266     SDValue SubOp0 = RHS.getOperand(0);
1267     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1268       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1269         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1270         Opcode = AArch64ISD::CCMN;
1271         RHS = RHS.getOperand(1);
1272       }
1273   }
1274   if (Opcode == 0)
1275     Opcode = AArch64ISD::CCMP;
1276
1277   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1278   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1279 }
1280
1281 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1282 /// CanPushNegate is set to true if we can push a negate operation through
1283 /// the tree in a was that we are left with AND operations and negate operations
1284 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1285 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1286 /// brought into such a form.
1287 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1288                                          unsigned Depth = 0) {
1289   if (!Val.hasOneUse())
1290     return false;
1291   unsigned Opcode = Val->getOpcode();
1292   if (Opcode == ISD::SETCC) {
1293     CanPushNegate = true;
1294     return true;
1295   }
1296   // Protect against stack overflow.
1297   if (Depth > 15)
1298     return false;
1299   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1300     SDValue O0 = Val->getOperand(0);
1301     SDValue O1 = Val->getOperand(1);
1302     bool CanPushNegateL;
1303     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1304       return false;
1305     bool CanPushNegateR;
1306     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1307       return false;
1308     // We cannot push a negate through an AND operation (it would become an OR),
1309     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1310     // push the negate through the x/y subtrees.
1311     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1312     return true;
1313   }
1314   return false;
1315 }
1316
1317 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1318 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1319 /// Tries to transform the given i1 producing node @p Val to a series compare
1320 /// and conditional compare operations. @returns an NZCV flags producing node
1321 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1322 /// transformation was not possible.
1323 /// On recursive invocations @p PushNegate may be set to true to have negation
1324 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1325 /// for the comparisons in the current subtree; @p Depth limits the search
1326 /// depth to avoid stack overflow.
1327 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1328     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1329     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1330     unsigned Depth = 0) {
1331   // We're at a tree leaf, produce a conditional comparison operation.
1332   unsigned Opcode = Val->getOpcode();
1333   if (Opcode == ISD::SETCC) {
1334     SDValue LHS = Val->getOperand(0);
1335     SDValue RHS = Val->getOperand(1);
1336     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1337     bool isInteger = LHS.getValueType().isInteger();
1338     if (PushNegate)
1339       CC = getSetCCInverse(CC, isInteger);
1340     SDLoc DL(Val);
1341     // Determine OutCC and handle FP special case.
1342     if (isInteger) {
1343       OutCC = changeIntCCToAArch64CC(CC);
1344     } else {
1345       assert(LHS.getValueType().isFloatingPoint());
1346       AArch64CC::CondCode ExtraCC;
1347       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1348       // Surpisingly some floating point conditions can't be tested with a
1349       // single condition code. Construct an additional comparison in this case.
1350       // See comment below on how we deal with OR conditions.
1351       if (ExtraCC != AArch64CC::AL) {
1352         SDValue ExtraCmp;
1353         if (!CCOp.getNode())
1354           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1355         else {
1356           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1357           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1358           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1359           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1360                                                NZCV, DL, DAG);
1361         }
1362         CCOp = ExtraCmp;
1363         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1364         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1365       }
1366     }
1367
1368     // Produce a normal comparison if we are first in the chain
1369     if (!CCOp.getNode())
1370       return emitComparison(LHS, RHS, CC, DL, DAG);
1371     // Otherwise produce a ccmp.
1372     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1373     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1374     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1375     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1376                                      DAG);
1377   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1378     return SDValue();
1379
1380   assert((Opcode == ISD::OR || !PushNegate)
1381          && "Can only push negate through OR operation");
1382
1383   // Check if both sides can be transformed.
1384   SDValue LHS = Val->getOperand(0);
1385   SDValue RHS = Val->getOperand(1);
1386   bool CanPushNegateL;
1387   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1388     return SDValue();
1389   bool CanPushNegateR;
1390   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1391     return SDValue();
1392
1393   // Do we need to negate our operands?
1394   bool NegateOperands = Opcode == ISD::OR;
1395   // We can negate the results of all previous operations by inverting the
1396   // predicate flags giving us a free negation for one side. For the other side
1397   // we need to be able to push the negation to the leafs of the tree.
1398   if (NegateOperands) {
1399     if (!CanPushNegateL && !CanPushNegateR)
1400       return SDValue();
1401     // Order the side where we can push the negate through to LHS.
1402     if (!CanPushNegateL && CanPushNegateR)
1403       std::swap(LHS, RHS);
1404   } else {
1405     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1406     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1407     if (NeedsNegOutL && NeedsNegOutR)
1408       return SDValue();
1409     // Order the side where we need to negate the output flags to RHS so it
1410     // gets emitted first.
1411     if (NeedsNegOutL)
1412       std::swap(LHS, RHS);
1413   }
1414
1415   // Emit RHS. If we want to negate the tree we only need to push a negate
1416   // through if we are already in a PushNegate case, otherwise we can negate
1417   // the "flags to test" afterwards.
1418   AArch64CC::CondCode RHSCC;
1419   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1420                                                 CCOp, Predicate, Depth+1);
1421   if (NegateOperands && !PushNegate)
1422     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1423   // Emit LHS. We must push the negate through if we need to negate it.
1424   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1425                                                 CmpR, RHSCC, Depth+1);
1426   // If we transformed an OR to and AND then we have to negate the result
1427   // (or absorb a PushNegate resulting in a double negation).
1428   if (Opcode == ISD::OR && !PushNegate)
1429     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1430   return CmpL;
1431 }
1432
1433 /// @}
1434
1435 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1436                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1437   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1438     EVT VT = RHS.getValueType();
1439     uint64_t C = RHSC->getZExtValue();
1440     if (!isLegalArithImmed(C)) {
1441       // Constant does not fit, try adjusting it by one?
1442       switch (CC) {
1443       default:
1444         break;
1445       case ISD::SETLT:
1446       case ISD::SETGE:
1447         if ((VT == MVT::i32 && C != 0x80000000 &&
1448              isLegalArithImmed((uint32_t)(C - 1))) ||
1449             (VT == MVT::i64 && C != 0x80000000ULL &&
1450              isLegalArithImmed(C - 1ULL))) {
1451           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1452           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1453           RHS = DAG.getConstant(C, dl, VT);
1454         }
1455         break;
1456       case ISD::SETULT:
1457       case ISD::SETUGE:
1458         if ((VT == MVT::i32 && C != 0 &&
1459              isLegalArithImmed((uint32_t)(C - 1))) ||
1460             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1461           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1462           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1463           RHS = DAG.getConstant(C, dl, VT);
1464         }
1465         break;
1466       case ISD::SETLE:
1467       case ISD::SETGT:
1468         if ((VT == MVT::i32 && C != INT32_MAX &&
1469              isLegalArithImmed((uint32_t)(C + 1))) ||
1470             (VT == MVT::i64 && C != INT64_MAX &&
1471              isLegalArithImmed(C + 1ULL))) {
1472           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1473           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1474           RHS = DAG.getConstant(C, dl, VT);
1475         }
1476         break;
1477       case ISD::SETULE:
1478       case ISD::SETUGT:
1479         if ((VT == MVT::i32 && C != UINT32_MAX &&
1480              isLegalArithImmed((uint32_t)(C + 1))) ||
1481             (VT == MVT::i64 && C != UINT64_MAX &&
1482              isLegalArithImmed(C + 1ULL))) {
1483           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1484           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1485           RHS = DAG.getConstant(C, dl, VT);
1486         }
1487         break;
1488       }
1489     }
1490   }
1491   SDValue Cmp;
1492   AArch64CC::CondCode AArch64CC;
1493   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1494     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1495
1496     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1497     // For the i8 operand, the largest immediate is 255, so this can be easily
1498     // encoded in the compare instruction. For the i16 operand, however, the
1499     // largest immediate cannot be encoded in the compare.
1500     // Therefore, use a sign extending load and cmn to avoid materializing the
1501     // -1 constant. For example,
1502     // movz w1, #65535
1503     // ldrh w0, [x0, #0]
1504     // cmp w0, w1
1505     // >
1506     // ldrsh w0, [x0, #0]
1507     // cmn w0, #1
1508     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1509     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1510     // ensure both the LHS and RHS are truly zero extended and to make sure the
1511     // transformation is profitable.
1512     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1513         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1514         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1515         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1516       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1517       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1518         SDValue SExt =
1519             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1520                         DAG.getValueType(MVT::i16));
1521         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1522                                                    RHS.getValueType()),
1523                              CC, dl, DAG);
1524         AArch64CC = changeIntCCToAArch64CC(CC);
1525       }
1526     }
1527
1528     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1529       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1530         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1531           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1532       }
1533     }
1534   }
1535
1536   if (!Cmp) {
1537     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1538     AArch64CC = changeIntCCToAArch64CC(CC);
1539   }
1540   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1541   return Cmp;
1542 }
1543
1544 static std::pair<SDValue, SDValue>
1545 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1546   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1547          "Unsupported value type");
1548   SDValue Value, Overflow;
1549   SDLoc DL(Op);
1550   SDValue LHS = Op.getOperand(0);
1551   SDValue RHS = Op.getOperand(1);
1552   unsigned Opc = 0;
1553   switch (Op.getOpcode()) {
1554   default:
1555     llvm_unreachable("Unknown overflow instruction!");
1556   case ISD::SADDO:
1557     Opc = AArch64ISD::ADDS;
1558     CC = AArch64CC::VS;
1559     break;
1560   case ISD::UADDO:
1561     Opc = AArch64ISD::ADDS;
1562     CC = AArch64CC::HS;
1563     break;
1564   case ISD::SSUBO:
1565     Opc = AArch64ISD::SUBS;
1566     CC = AArch64CC::VS;
1567     break;
1568   case ISD::USUBO:
1569     Opc = AArch64ISD::SUBS;
1570     CC = AArch64CC::LO;
1571     break;
1572   // Multiply needs a little bit extra work.
1573   case ISD::SMULO:
1574   case ISD::UMULO: {
1575     CC = AArch64CC::NE;
1576     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1577     if (Op.getValueType() == MVT::i32) {
1578       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1579       // For a 32 bit multiply with overflow check we want the instruction
1580       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1581       // need to generate the following pattern:
1582       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1583       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1584       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1585       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1586       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1587                                 DAG.getConstant(0, DL, MVT::i64));
1588       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1589       // operation. We need to clear out the upper 32 bits, because we used a
1590       // widening multiply that wrote all 64 bits. In the end this should be a
1591       // noop.
1592       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1593       if (IsSigned) {
1594         // The signed overflow check requires more than just a simple check for
1595         // any bit set in the upper 32 bits of the result. These bits could be
1596         // just the sign bits of a negative number. To perform the overflow
1597         // check we have to arithmetic shift right the 32nd bit of the result by
1598         // 31 bits. Then we compare the result to the upper 32 bits.
1599         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1600                                         DAG.getConstant(32, DL, MVT::i64));
1601         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1602         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1603                                         DAG.getConstant(31, DL, MVT::i64));
1604         // It is important that LowerBits is last, otherwise the arithmetic
1605         // shift will not be folded into the compare (SUBS).
1606         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1607         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1608                        .getValue(1);
1609       } else {
1610         // The overflow check for unsigned multiply is easy. We only need to
1611         // check if any of the upper 32 bits are set. This can be done with a
1612         // CMP (shifted register). For that we need to generate the following
1613         // pattern:
1614         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1615         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1616                                         DAG.getConstant(32, DL, MVT::i64));
1617         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1618         Overflow =
1619             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1620                         DAG.getConstant(0, DL, MVT::i64),
1621                         UpperBits).getValue(1);
1622       }
1623       break;
1624     }
1625     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1626     // For the 64 bit multiply
1627     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1628     if (IsSigned) {
1629       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1630       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1631                                       DAG.getConstant(63, DL, MVT::i64));
1632       // It is important that LowerBits is last, otherwise the arithmetic
1633       // shift will not be folded into the compare (SUBS).
1634       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1635       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1636                      .getValue(1);
1637     } else {
1638       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1639       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1640       Overflow =
1641           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1642                       DAG.getConstant(0, DL, MVT::i64),
1643                       UpperBits).getValue(1);
1644     }
1645     break;
1646   }
1647   } // switch (...)
1648
1649   if (Opc) {
1650     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1651
1652     // Emit the AArch64 operation with overflow check.
1653     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1654     Overflow = Value.getValue(1);
1655   }
1656   return std::make_pair(Value, Overflow);
1657 }
1658
1659 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1660                                              RTLIB::Libcall Call) const {
1661   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1662   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1663 }
1664
1665 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1666   SDValue Sel = Op.getOperand(0);
1667   SDValue Other = Op.getOperand(1);
1668
1669   // If neither operand is a SELECT_CC, give up.
1670   if (Sel.getOpcode() != ISD::SELECT_CC)
1671     std::swap(Sel, Other);
1672   if (Sel.getOpcode() != ISD::SELECT_CC)
1673     return Op;
1674
1675   // The folding we want to perform is:
1676   // (xor x, (select_cc a, b, cc, 0, -1) )
1677   //   -->
1678   // (csel x, (xor x, -1), cc ...)
1679   //
1680   // The latter will get matched to a CSINV instruction.
1681
1682   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1683   SDValue LHS = Sel.getOperand(0);
1684   SDValue RHS = Sel.getOperand(1);
1685   SDValue TVal = Sel.getOperand(2);
1686   SDValue FVal = Sel.getOperand(3);
1687   SDLoc dl(Sel);
1688
1689   // FIXME: This could be generalized to non-integer comparisons.
1690   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1691     return Op;
1692
1693   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1694   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1695
1696   // The values aren't constants, this isn't the pattern we're looking for.
1697   if (!CFVal || !CTVal)
1698     return Op;
1699
1700   // We can commute the SELECT_CC by inverting the condition.  This
1701   // might be needed to make this fit into a CSINV pattern.
1702   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1703     std::swap(TVal, FVal);
1704     std::swap(CTVal, CFVal);
1705     CC = ISD::getSetCCInverse(CC, true);
1706   }
1707
1708   // If the constants line up, perform the transform!
1709   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1710     SDValue CCVal;
1711     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1712
1713     FVal = Other;
1714     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1715                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1716
1717     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1718                        CCVal, Cmp);
1719   }
1720
1721   return Op;
1722 }
1723
1724 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1725   EVT VT = Op.getValueType();
1726
1727   // Let legalize expand this if it isn't a legal type yet.
1728   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1729     return SDValue();
1730
1731   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1732
1733   unsigned Opc;
1734   bool ExtraOp = false;
1735   switch (Op.getOpcode()) {
1736   default:
1737     llvm_unreachable("Invalid code");
1738   case ISD::ADDC:
1739     Opc = AArch64ISD::ADDS;
1740     break;
1741   case ISD::SUBC:
1742     Opc = AArch64ISD::SUBS;
1743     break;
1744   case ISD::ADDE:
1745     Opc = AArch64ISD::ADCS;
1746     ExtraOp = true;
1747     break;
1748   case ISD::SUBE:
1749     Opc = AArch64ISD::SBCS;
1750     ExtraOp = true;
1751     break;
1752   }
1753
1754   if (!ExtraOp)
1755     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1756   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1757                      Op.getOperand(2));
1758 }
1759
1760 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1761   // Let legalize expand this if it isn't a legal type yet.
1762   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1763     return SDValue();
1764
1765   SDLoc dl(Op);
1766   AArch64CC::CondCode CC;
1767   // The actual operation that sets the overflow or carry flag.
1768   SDValue Value, Overflow;
1769   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1770
1771   // We use 0 and 1 as false and true values.
1772   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1773   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1774
1775   // We use an inverted condition, because the conditional select is inverted
1776   // too. This will allow it to be selected to a single instruction:
1777   // CSINC Wd, WZR, WZR, invert(cond).
1778   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1779   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1780                          CCVal, Overflow);
1781
1782   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1783   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1784 }
1785
1786 // Prefetch operands are:
1787 // 1: Address to prefetch
1788 // 2: bool isWrite
1789 // 3: int locality (0 = no locality ... 3 = extreme locality)
1790 // 4: bool isDataCache
1791 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1792   SDLoc DL(Op);
1793   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1794   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1795   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1796
1797   bool IsStream = !Locality;
1798   // When the locality number is set
1799   if (Locality) {
1800     // The front-end should have filtered out the out-of-range values
1801     assert(Locality <= 3 && "Prefetch locality out-of-range");
1802     // The locality degree is the opposite of the cache speed.
1803     // Put the number the other way around.
1804     // The encoding starts at 0 for level 1
1805     Locality = 3 - Locality;
1806   }
1807
1808   // built the mask value encoding the expected behavior.
1809   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1810                    (!IsData << 3) |     // IsDataCache bit
1811                    (Locality << 1) |    // Cache level bits
1812                    (unsigned)IsStream;  // Stream bit
1813   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1814                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1815 }
1816
1817 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1818                                               SelectionDAG &DAG) const {
1819   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1820
1821   RTLIB::Libcall LC;
1822   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1823
1824   return LowerF128Call(Op, DAG, LC);
1825 }
1826
1827 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1828                                              SelectionDAG &DAG) const {
1829   if (Op.getOperand(0).getValueType() != MVT::f128) {
1830     // It's legal except when f128 is involved
1831     return Op;
1832   }
1833
1834   RTLIB::Libcall LC;
1835   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1836
1837   // FP_ROUND node has a second operand indicating whether it is known to be
1838   // precise. That doesn't take part in the LibCall so we can't directly use
1839   // LowerF128Call.
1840   SDValue SrcVal = Op.getOperand(0);
1841   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1842                      SDLoc(Op)).first;
1843 }
1844
1845 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1846   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1847   // Any additional optimization in this function should be recorded
1848   // in the cost tables.
1849   EVT InVT = Op.getOperand(0).getValueType();
1850   EVT VT = Op.getValueType();
1851
1852   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1853     SDLoc dl(Op);
1854     SDValue Cv =
1855         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1856                     Op.getOperand(0));
1857     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1858   }
1859
1860   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1861     SDLoc dl(Op);
1862     MVT ExtVT =
1863         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1864                          VT.getVectorNumElements());
1865     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1866     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1867   }
1868
1869   // Type changing conversions are illegal.
1870   return Op;
1871 }
1872
1873 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1874                                               SelectionDAG &DAG) const {
1875   if (Op.getOperand(0).getValueType().isVector())
1876     return LowerVectorFP_TO_INT(Op, DAG);
1877
1878   // f16 conversions are promoted to f32.
1879   if (Op.getOperand(0).getValueType() == MVT::f16) {
1880     SDLoc dl(Op);
1881     return DAG.getNode(
1882         Op.getOpcode(), dl, Op.getValueType(),
1883         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1884   }
1885
1886   if (Op.getOperand(0).getValueType() != MVT::f128) {
1887     // It's legal except when f128 is involved
1888     return Op;
1889   }
1890
1891   RTLIB::Libcall LC;
1892   if (Op.getOpcode() == ISD::FP_TO_SINT)
1893     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1894   else
1895     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1896
1897   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1898   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1899 }
1900
1901 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1902   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1903   // Any additional optimization in this function should be recorded
1904   // in the cost tables.
1905   EVT VT = Op.getValueType();
1906   SDLoc dl(Op);
1907   SDValue In = Op.getOperand(0);
1908   EVT InVT = In.getValueType();
1909
1910   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1911     MVT CastVT =
1912         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1913                          InVT.getVectorNumElements());
1914     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1915     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1916   }
1917
1918   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1919     unsigned CastOpc =
1920         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1921     EVT CastVT = VT.changeVectorElementTypeToInteger();
1922     In = DAG.getNode(CastOpc, dl, CastVT, In);
1923     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1924   }
1925
1926   return Op;
1927 }
1928
1929 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1930                                             SelectionDAG &DAG) const {
1931   if (Op.getValueType().isVector())
1932     return LowerVectorINT_TO_FP(Op, DAG);
1933
1934   // f16 conversions are promoted to f32.
1935   if (Op.getValueType() == MVT::f16) {
1936     SDLoc dl(Op);
1937     return DAG.getNode(
1938         ISD::FP_ROUND, dl, MVT::f16,
1939         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1940         DAG.getIntPtrConstant(0, dl));
1941   }
1942
1943   // i128 conversions are libcalls.
1944   if (Op.getOperand(0).getValueType() == MVT::i128)
1945     return SDValue();
1946
1947   // Other conversions are legal, unless it's to the completely software-based
1948   // fp128.
1949   if (Op.getValueType() != MVT::f128)
1950     return Op;
1951
1952   RTLIB::Libcall LC;
1953   if (Op.getOpcode() == ISD::SINT_TO_FP)
1954     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1955   else
1956     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1957
1958   return LowerF128Call(Op, DAG, LC);
1959 }
1960
1961 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1962                                             SelectionDAG &DAG) const {
1963   // For iOS, we want to call an alternative entry point: __sincos_stret,
1964   // which returns the values in two S / D registers.
1965   SDLoc dl(Op);
1966   SDValue Arg = Op.getOperand(0);
1967   EVT ArgVT = Arg.getValueType();
1968   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1969
1970   ArgListTy Args;
1971   ArgListEntry Entry;
1972
1973   Entry.Node = Arg;
1974   Entry.Ty = ArgTy;
1975   Entry.isSExt = false;
1976   Entry.isZExt = false;
1977   Args.push_back(Entry);
1978
1979   const char *LibcallName =
1980       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1981   SDValue Callee =
1982       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1983
1984   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1985   TargetLowering::CallLoweringInfo CLI(DAG);
1986   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1987     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1988
1989   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1990   return CallResult.first;
1991 }
1992
1993 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1994   if (Op.getValueType() != MVT::f16)
1995     return SDValue();
1996
1997   assert(Op.getOperand(0).getValueType() == MVT::i16);
1998   SDLoc DL(Op);
1999
2000   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2001   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2002   return SDValue(
2003       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2004                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2005       0);
2006 }
2007
2008 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2009   if (OrigVT.getSizeInBits() >= 64)
2010     return OrigVT;
2011
2012   assert(OrigVT.isSimple() && "Expecting a simple value type");
2013
2014   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2015   switch (OrigSimpleTy) {
2016   default: llvm_unreachable("Unexpected Vector Type");
2017   case MVT::v2i8:
2018   case MVT::v2i16:
2019      return MVT::v2i32;
2020   case MVT::v4i8:
2021     return  MVT::v4i16;
2022   }
2023 }
2024
2025 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2026                                                  const EVT &OrigTy,
2027                                                  const EVT &ExtTy,
2028                                                  unsigned ExtOpcode) {
2029   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2030   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2031   // 64-bits we need to insert a new extension so that it will be 64-bits.
2032   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2033   if (OrigTy.getSizeInBits() >= 64)
2034     return N;
2035
2036   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2037   EVT NewVT = getExtensionTo64Bits(OrigTy);
2038
2039   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2040 }
2041
2042 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2043                                    bool isSigned) {
2044   EVT VT = N->getValueType(0);
2045
2046   if (N->getOpcode() != ISD::BUILD_VECTOR)
2047     return false;
2048
2049   for (const SDValue &Elt : N->op_values()) {
2050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2051       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2052       unsigned HalfSize = EltSize / 2;
2053       if (isSigned) {
2054         if (!isIntN(HalfSize, C->getSExtValue()))
2055           return false;
2056       } else {
2057         if (!isUIntN(HalfSize, C->getZExtValue()))
2058           return false;
2059       }
2060       continue;
2061     }
2062     return false;
2063   }
2064
2065   return true;
2066 }
2067
2068 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2069   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2070     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2071                                              N->getOperand(0)->getValueType(0),
2072                                              N->getValueType(0),
2073                                              N->getOpcode());
2074
2075   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2076   EVT VT = N->getValueType(0);
2077   SDLoc dl(N);
2078   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2079   unsigned NumElts = VT.getVectorNumElements();
2080   MVT TruncVT = MVT::getIntegerVT(EltSize);
2081   SmallVector<SDValue, 8> Ops;
2082   for (unsigned i = 0; i != NumElts; ++i) {
2083     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2084     const APInt &CInt = C->getAPIntValue();
2085     // Element types smaller than 32 bits are not legal, so use i32 elements.
2086     // The values are implicitly truncated so sext vs. zext doesn't matter.
2087     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2088   }
2089   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2090                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2091 }
2092
2093 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2094   if (N->getOpcode() == ISD::SIGN_EXTEND)
2095     return true;
2096   if (isExtendedBUILD_VECTOR(N, DAG, true))
2097     return true;
2098   return false;
2099 }
2100
2101 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2102   if (N->getOpcode() == ISD::ZERO_EXTEND)
2103     return true;
2104   if (isExtendedBUILD_VECTOR(N, DAG, false))
2105     return true;
2106   return false;
2107 }
2108
2109 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2110   unsigned Opcode = N->getOpcode();
2111   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2112     SDNode *N0 = N->getOperand(0).getNode();
2113     SDNode *N1 = N->getOperand(1).getNode();
2114     return N0->hasOneUse() && N1->hasOneUse() &&
2115       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2116   }
2117   return false;
2118 }
2119
2120 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2121   unsigned Opcode = N->getOpcode();
2122   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2123     SDNode *N0 = N->getOperand(0).getNode();
2124     SDNode *N1 = N->getOperand(1).getNode();
2125     return N0->hasOneUse() && N1->hasOneUse() &&
2126       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2127   }
2128   return false;
2129 }
2130
2131 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2132   // Multiplications are only custom-lowered for 128-bit vectors so that
2133   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2134   EVT VT = Op.getValueType();
2135   assert(VT.is128BitVector() && VT.isInteger() &&
2136          "unexpected type for custom-lowering ISD::MUL");
2137   SDNode *N0 = Op.getOperand(0).getNode();
2138   SDNode *N1 = Op.getOperand(1).getNode();
2139   unsigned NewOpc = 0;
2140   bool isMLA = false;
2141   bool isN0SExt = isSignExtended(N0, DAG);
2142   bool isN1SExt = isSignExtended(N1, DAG);
2143   if (isN0SExt && isN1SExt)
2144     NewOpc = AArch64ISD::SMULL;
2145   else {
2146     bool isN0ZExt = isZeroExtended(N0, DAG);
2147     bool isN1ZExt = isZeroExtended(N1, DAG);
2148     if (isN0ZExt && isN1ZExt)
2149       NewOpc = AArch64ISD::UMULL;
2150     else if (isN1SExt || isN1ZExt) {
2151       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2152       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2153       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2154         NewOpc = AArch64ISD::SMULL;
2155         isMLA = true;
2156       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2157         NewOpc =  AArch64ISD::UMULL;
2158         isMLA = true;
2159       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2160         std::swap(N0, N1);
2161         NewOpc =  AArch64ISD::UMULL;
2162         isMLA = true;
2163       }
2164     }
2165
2166     if (!NewOpc) {
2167       if (VT == MVT::v2i64)
2168         // Fall through to expand this.  It is not legal.
2169         return SDValue();
2170       else
2171         // Other vector multiplications are legal.
2172         return Op;
2173     }
2174   }
2175
2176   // Legalize to a S/UMULL instruction
2177   SDLoc DL(Op);
2178   SDValue Op0;
2179   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2180   if (!isMLA) {
2181     Op0 = skipExtensionForVectorMULL(N0, DAG);
2182     assert(Op0.getValueType().is64BitVector() &&
2183            Op1.getValueType().is64BitVector() &&
2184            "unexpected types for extended operands to VMULL");
2185     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2186   }
2187   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2188   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2189   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2190   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2191   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2192   EVT Op1VT = Op1.getValueType();
2193   return DAG.getNode(N0->getOpcode(), DL, VT,
2194                      DAG.getNode(NewOpc, DL, VT,
2195                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2196                      DAG.getNode(NewOpc, DL, VT,
2197                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2198 }
2199
2200 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2201                                                      SelectionDAG &DAG) const {
2202   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2203   SDLoc dl(Op);
2204   switch (IntNo) {
2205   default: return SDValue();    // Don't custom lower most intrinsics.
2206   case Intrinsic::aarch64_thread_pointer: {
2207     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2208     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2209   }
2210   case Intrinsic::aarch64_neon_smax:
2211     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2212                        Op.getOperand(1), Op.getOperand(2));
2213   case Intrinsic::aarch64_neon_umax:
2214     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2215                        Op.getOperand(1), Op.getOperand(2));
2216   case Intrinsic::aarch64_neon_smin:
2217     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2218                        Op.getOperand(1), Op.getOperand(2));
2219   case Intrinsic::aarch64_neon_umin:
2220     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2221                        Op.getOperand(1), Op.getOperand(2));
2222   }
2223 }
2224
2225 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2226                                               SelectionDAG &DAG) const {
2227   switch (Op.getOpcode()) {
2228   default:
2229     llvm_unreachable("unimplemented operand");
2230     return SDValue();
2231   case ISD::BITCAST:
2232     return LowerBITCAST(Op, DAG);
2233   case ISD::GlobalAddress:
2234     return LowerGlobalAddress(Op, DAG);
2235   case ISD::GlobalTLSAddress:
2236     return LowerGlobalTLSAddress(Op, DAG);
2237   case ISD::SETCC:
2238     return LowerSETCC(Op, DAG);
2239   case ISD::BR_CC:
2240     return LowerBR_CC(Op, DAG);
2241   case ISD::SELECT:
2242     return LowerSELECT(Op, DAG);
2243   case ISD::SELECT_CC:
2244     return LowerSELECT_CC(Op, DAG);
2245   case ISD::JumpTable:
2246     return LowerJumpTable(Op, DAG);
2247   case ISD::ConstantPool:
2248     return LowerConstantPool(Op, DAG);
2249   case ISD::BlockAddress:
2250     return LowerBlockAddress(Op, DAG);
2251   case ISD::VASTART:
2252     return LowerVASTART(Op, DAG);
2253   case ISD::VACOPY:
2254     return LowerVACOPY(Op, DAG);
2255   case ISD::VAARG:
2256     return LowerVAARG(Op, DAG);
2257   case ISD::ADDC:
2258   case ISD::ADDE:
2259   case ISD::SUBC:
2260   case ISD::SUBE:
2261     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2262   case ISD::SADDO:
2263   case ISD::UADDO:
2264   case ISD::SSUBO:
2265   case ISD::USUBO:
2266   case ISD::SMULO:
2267   case ISD::UMULO:
2268     return LowerXALUO(Op, DAG);
2269   case ISD::FADD:
2270     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2271   case ISD::FSUB:
2272     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2273   case ISD::FMUL:
2274     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2275   case ISD::FDIV:
2276     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2277   case ISD::FP_ROUND:
2278     return LowerFP_ROUND(Op, DAG);
2279   case ISD::FP_EXTEND:
2280     return LowerFP_EXTEND(Op, DAG);
2281   case ISD::FRAMEADDR:
2282     return LowerFRAMEADDR(Op, DAG);
2283   case ISD::RETURNADDR:
2284     return LowerRETURNADDR(Op, DAG);
2285   case ISD::INSERT_VECTOR_ELT:
2286     return LowerINSERT_VECTOR_ELT(Op, DAG);
2287   case ISD::EXTRACT_VECTOR_ELT:
2288     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2289   case ISD::BUILD_VECTOR:
2290     return LowerBUILD_VECTOR(Op, DAG);
2291   case ISD::VECTOR_SHUFFLE:
2292     return LowerVECTOR_SHUFFLE(Op, DAG);
2293   case ISD::EXTRACT_SUBVECTOR:
2294     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2295   case ISD::SRA:
2296   case ISD::SRL:
2297   case ISD::SHL:
2298     return LowerVectorSRA_SRL_SHL(Op, DAG);
2299   case ISD::SHL_PARTS:
2300     return LowerShiftLeftParts(Op, DAG);
2301   case ISD::SRL_PARTS:
2302   case ISD::SRA_PARTS:
2303     return LowerShiftRightParts(Op, DAG);
2304   case ISD::CTPOP:
2305     return LowerCTPOP(Op, DAG);
2306   case ISD::FCOPYSIGN:
2307     return LowerFCOPYSIGN(Op, DAG);
2308   case ISD::AND:
2309     return LowerVectorAND(Op, DAG);
2310   case ISD::OR:
2311     return LowerVectorOR(Op, DAG);
2312   case ISD::XOR:
2313     return LowerXOR(Op, DAG);
2314   case ISD::PREFETCH:
2315     return LowerPREFETCH(Op, DAG);
2316   case ISD::SINT_TO_FP:
2317   case ISD::UINT_TO_FP:
2318     return LowerINT_TO_FP(Op, DAG);
2319   case ISD::FP_TO_SINT:
2320   case ISD::FP_TO_UINT:
2321     return LowerFP_TO_INT(Op, DAG);
2322   case ISD::FSINCOS:
2323     return LowerFSINCOS(Op, DAG);
2324   case ISD::MUL:
2325     return LowerMUL(Op, DAG);
2326   case ISD::INTRINSIC_WO_CHAIN:
2327     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2328   }
2329 }
2330
2331 /// getFunctionAlignment - Return the Log2 alignment of this function.
2332 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2333   return 2;
2334 }
2335
2336 //===----------------------------------------------------------------------===//
2337 //                      Calling Convention Implementation
2338 //===----------------------------------------------------------------------===//
2339
2340 #include "AArch64GenCallingConv.inc"
2341
2342 /// Selects the correct CCAssignFn for a given CallingConvention value.
2343 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2344                                                      bool IsVarArg) const {
2345   switch (CC) {
2346   default:
2347     llvm_unreachable("Unsupported calling convention.");
2348   case CallingConv::WebKit_JS:
2349     return CC_AArch64_WebKit_JS;
2350   case CallingConv::GHC:
2351     return CC_AArch64_GHC;
2352   case CallingConv::C:
2353   case CallingConv::Fast:
2354     if (!Subtarget->isTargetDarwin())
2355       return CC_AArch64_AAPCS;
2356     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2357   }
2358 }
2359
2360 SDValue AArch64TargetLowering::LowerFormalArguments(
2361     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2362     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2363     SmallVectorImpl<SDValue> &InVals) const {
2364   MachineFunction &MF = DAG.getMachineFunction();
2365   MachineFrameInfo *MFI = MF.getFrameInfo();
2366
2367   // Assign locations to all of the incoming arguments.
2368   SmallVector<CCValAssign, 16> ArgLocs;
2369   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2370                  *DAG.getContext());
2371
2372   // At this point, Ins[].VT may already be promoted to i32. To correctly
2373   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2374   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2375   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2376   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2377   // LocVT.
2378   unsigned NumArgs = Ins.size();
2379   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2380   unsigned CurArgIdx = 0;
2381   for (unsigned i = 0; i != NumArgs; ++i) {
2382     MVT ValVT = Ins[i].VT;
2383     if (Ins[i].isOrigArg()) {
2384       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2385       CurArgIdx = Ins[i].getOrigArgIndex();
2386
2387       // Get type of the original argument.
2388       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2389                                   /*AllowUnknown*/ true);
2390       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2391       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2392       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2393         ValVT = MVT::i8;
2394       else if (ActualMVT == MVT::i16)
2395         ValVT = MVT::i16;
2396     }
2397     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2398     bool Res =
2399         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2400     assert(!Res && "Call operand has unhandled type");
2401     (void)Res;
2402   }
2403   assert(ArgLocs.size() == Ins.size());
2404   SmallVector<SDValue, 16> ArgValues;
2405   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2406     CCValAssign &VA = ArgLocs[i];
2407
2408     if (Ins[i].Flags.isByVal()) {
2409       // Byval is used for HFAs in the PCS, but the system should work in a
2410       // non-compliant manner for larger structs.
2411       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2412       int Size = Ins[i].Flags.getByValSize();
2413       unsigned NumRegs = (Size + 7) / 8;
2414
2415       // FIXME: This works on big-endian for composite byvals, which are the common
2416       // case. It should also work for fundamental types too.
2417       unsigned FrameIdx =
2418         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2419       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2420       InVals.push_back(FrameIdxN);
2421
2422       continue;
2423     }
2424     
2425     if (VA.isRegLoc()) {
2426       // Arguments stored in registers.
2427       EVT RegVT = VA.getLocVT();
2428
2429       SDValue ArgValue;
2430       const TargetRegisterClass *RC;
2431
2432       if (RegVT == MVT::i32)
2433         RC = &AArch64::GPR32RegClass;
2434       else if (RegVT == MVT::i64)
2435         RC = &AArch64::GPR64RegClass;
2436       else if (RegVT == MVT::f16)
2437         RC = &AArch64::FPR16RegClass;
2438       else if (RegVT == MVT::f32)
2439         RC = &AArch64::FPR32RegClass;
2440       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2441         RC = &AArch64::FPR64RegClass;
2442       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2443         RC = &AArch64::FPR128RegClass;
2444       else
2445         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2446
2447       // Transform the arguments in physical registers into virtual ones.
2448       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2449       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2450
2451       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2452       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2453       // truncate to the right size.
2454       switch (VA.getLocInfo()) {
2455       default:
2456         llvm_unreachable("Unknown loc info!");
2457       case CCValAssign::Full:
2458         break;
2459       case CCValAssign::BCvt:
2460         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2461         break;
2462       case CCValAssign::AExt:
2463       case CCValAssign::SExt:
2464       case CCValAssign::ZExt:
2465         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2466         // nodes after our lowering.
2467         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2468         break;
2469       }
2470
2471       InVals.push_back(ArgValue);
2472
2473     } else { // VA.isRegLoc()
2474       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2475       unsigned ArgOffset = VA.getLocMemOffset();
2476       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2477
2478       uint32_t BEAlign = 0;
2479       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2480           !Ins[i].Flags.isInConsecutiveRegs())
2481         BEAlign = 8 - ArgSize;
2482
2483       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2484
2485       // Create load nodes to retrieve arguments from the stack.
2486       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2487       SDValue ArgValue;
2488
2489       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2490       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2491       MVT MemVT = VA.getValVT();
2492
2493       switch (VA.getLocInfo()) {
2494       default:
2495         break;
2496       case CCValAssign::BCvt:
2497         MemVT = VA.getLocVT();
2498         break;
2499       case CCValAssign::SExt:
2500         ExtType = ISD::SEXTLOAD;
2501         break;
2502       case CCValAssign::ZExt:
2503         ExtType = ISD::ZEXTLOAD;
2504         break;
2505       case CCValAssign::AExt:
2506         ExtType = ISD::EXTLOAD;
2507         break;
2508       }
2509
2510       ArgValue = DAG.getExtLoad(
2511           ExtType, DL, VA.getLocVT(), Chain, FIN,
2512           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2513           MemVT, false, false, false, 0);
2514
2515       InVals.push_back(ArgValue);
2516     }
2517   }
2518
2519   // varargs
2520   if (isVarArg) {
2521     if (!Subtarget->isTargetDarwin()) {
2522       // The AAPCS variadic function ABI is identical to the non-variadic
2523       // one. As a result there may be more arguments in registers and we should
2524       // save them for future reference.
2525       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2526     }
2527
2528     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2529     // This will point to the next argument passed via stack.
2530     unsigned StackOffset = CCInfo.getNextStackOffset();
2531     // We currently pass all varargs at 8-byte alignment.
2532     StackOffset = ((StackOffset + 7) & ~7);
2533     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2534   }
2535
2536   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2537   unsigned StackArgSize = CCInfo.getNextStackOffset();
2538   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2539   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2540     // This is a non-standard ABI so by fiat I say we're allowed to make full
2541     // use of the stack area to be popped, which must be aligned to 16 bytes in
2542     // any case:
2543     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2544
2545     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2546     // a multiple of 16.
2547     FuncInfo->setArgumentStackToRestore(StackArgSize);
2548
2549     // This realignment carries over to the available bytes below. Our own
2550     // callers will guarantee the space is free by giving an aligned value to
2551     // CALLSEQ_START.
2552   }
2553   // Even if we're not expected to free up the space, it's useful to know how
2554   // much is there while considering tail calls (because we can reuse it).
2555   FuncInfo->setBytesInStackArgArea(StackArgSize);
2556
2557   return Chain;
2558 }
2559
2560 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2561                                                 SelectionDAG &DAG, SDLoc DL,
2562                                                 SDValue &Chain) const {
2563   MachineFunction &MF = DAG.getMachineFunction();
2564   MachineFrameInfo *MFI = MF.getFrameInfo();
2565   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2566   auto PtrVT = getPointerTy(DAG.getDataLayout());
2567
2568   SmallVector<SDValue, 8> MemOps;
2569
2570   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2571                                           AArch64::X3, AArch64::X4, AArch64::X5,
2572                                           AArch64::X6, AArch64::X7 };
2573   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2574   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2575
2576   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2577   int GPRIdx = 0;
2578   if (GPRSaveSize != 0) {
2579     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2580
2581     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2582
2583     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2584       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2585       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2586       SDValue Store = DAG.getStore(
2587           Val.getValue(1), DL, Val, FIN,
2588           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2589           false, 0);
2590       MemOps.push_back(Store);
2591       FIN =
2592           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2593     }
2594   }
2595   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2596   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2597
2598   if (Subtarget->hasFPARMv8()) {
2599     static const MCPhysReg FPRArgRegs[] = {
2600         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2601         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2602     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2603     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2604
2605     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2606     int FPRIdx = 0;
2607     if (FPRSaveSize != 0) {
2608       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2609
2610       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2611
2612       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2613         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2614         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2615
2616         SDValue Store = DAG.getStore(
2617             Val.getValue(1), DL, Val, FIN,
2618             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2619             false, false, 0);
2620         MemOps.push_back(Store);
2621         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2622                           DAG.getConstant(16, DL, PtrVT));
2623       }
2624     }
2625     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2626     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2627   }
2628
2629   if (!MemOps.empty()) {
2630     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2631   }
2632 }
2633
2634 /// LowerCallResult - Lower the result values of a call into the
2635 /// appropriate copies out of appropriate physical registers.
2636 SDValue AArch64TargetLowering::LowerCallResult(
2637     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2638     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2639     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2640     SDValue ThisVal) const {
2641   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2642                           ? RetCC_AArch64_WebKit_JS
2643                           : RetCC_AArch64_AAPCS;
2644   // Assign locations to each value returned by this call.
2645   SmallVector<CCValAssign, 16> RVLocs;
2646   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2647                  *DAG.getContext());
2648   CCInfo.AnalyzeCallResult(Ins, RetCC);
2649
2650   // Copy all of the result registers out of their specified physreg.
2651   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2652     CCValAssign VA = RVLocs[i];
2653
2654     // Pass 'this' value directly from the argument to return value, to avoid
2655     // reg unit interference
2656     if (i == 0 && isThisReturn) {
2657       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2658              "unexpected return calling convention register assignment");
2659       InVals.push_back(ThisVal);
2660       continue;
2661     }
2662
2663     SDValue Val =
2664         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2665     Chain = Val.getValue(1);
2666     InFlag = Val.getValue(2);
2667
2668     switch (VA.getLocInfo()) {
2669     default:
2670       llvm_unreachable("Unknown loc info!");
2671     case CCValAssign::Full:
2672       break;
2673     case CCValAssign::BCvt:
2674       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2675       break;
2676     }
2677
2678     InVals.push_back(Val);
2679   }
2680
2681   return Chain;
2682 }
2683
2684 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2685     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2686     bool isCalleeStructRet, bool isCallerStructRet,
2687     const SmallVectorImpl<ISD::OutputArg> &Outs,
2688     const SmallVectorImpl<SDValue> &OutVals,
2689     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2690   // For CallingConv::C this function knows whether the ABI needs
2691   // changing. That's not true for other conventions so they will have to opt in
2692   // manually.
2693   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2694     return false;
2695
2696   const MachineFunction &MF = DAG.getMachineFunction();
2697   const Function *CallerF = MF.getFunction();
2698   CallingConv::ID CallerCC = CallerF->getCallingConv();
2699   bool CCMatch = CallerCC == CalleeCC;
2700
2701   // Byval parameters hand the function a pointer directly into the stack area
2702   // we want to reuse during a tail call. Working around this *is* possible (see
2703   // X86) but less efficient and uglier in LowerCall.
2704   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2705                                     e = CallerF->arg_end();
2706        i != e; ++i)
2707     if (i->hasByValAttr())
2708       return false;
2709
2710   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2711     if (IsTailCallConvention(CalleeCC) && CCMatch)
2712       return true;
2713     return false;
2714   }
2715
2716   // Externally-defined functions with weak linkage should not be
2717   // tail-called on AArch64 when the OS does not support dynamic
2718   // pre-emption of symbols, as the AAELF spec requires normal calls
2719   // to undefined weak functions to be replaced with a NOP or jump to the
2720   // next instruction. The behaviour of branch instructions in this
2721   // situation (as used for tail calls) is implementation-defined, so we
2722   // cannot rely on the linker replacing the tail call with a return.
2723   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2724     const GlobalValue *GV = G->getGlobal();
2725     const Triple &TT = getTargetMachine().getTargetTriple();
2726     if (GV->hasExternalWeakLinkage() &&
2727         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2728       return false;
2729   }
2730
2731   // Now we search for cases where we can use a tail call without changing the
2732   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2733   // concept.
2734
2735   // I want anyone implementing a new calling convention to think long and hard
2736   // about this assert.
2737   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2738          "Unexpected variadic calling convention");
2739
2740   if (isVarArg && !Outs.empty()) {
2741     // At least two cases here: if caller is fastcc then we can't have any
2742     // memory arguments (we'd be expected to clean up the stack afterwards). If
2743     // caller is C then we could potentially use its argument area.
2744
2745     // FIXME: for now we take the most conservative of these in both cases:
2746     // disallow all variadic memory operands.
2747     SmallVector<CCValAssign, 16> ArgLocs;
2748     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2749                    *DAG.getContext());
2750
2751     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2752     for (const CCValAssign &ArgLoc : ArgLocs)
2753       if (!ArgLoc.isRegLoc())
2754         return false;
2755   }
2756
2757   // If the calling conventions do not match, then we'd better make sure the
2758   // results are returned in the same way as what the caller expects.
2759   if (!CCMatch) {
2760     SmallVector<CCValAssign, 16> RVLocs1;
2761     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2762                     *DAG.getContext());
2763     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2764
2765     SmallVector<CCValAssign, 16> RVLocs2;
2766     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2767                     *DAG.getContext());
2768     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2769
2770     if (RVLocs1.size() != RVLocs2.size())
2771       return false;
2772     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2773       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2774         return false;
2775       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2776         return false;
2777       if (RVLocs1[i].isRegLoc()) {
2778         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2779           return false;
2780       } else {
2781         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2782           return false;
2783       }
2784     }
2785   }
2786
2787   // Nothing more to check if the callee is taking no arguments
2788   if (Outs.empty())
2789     return true;
2790
2791   SmallVector<CCValAssign, 16> ArgLocs;
2792   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2793                  *DAG.getContext());
2794
2795   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2796
2797   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2798
2799   // If the stack arguments for this call would fit into our own save area then
2800   // the call can be made tail.
2801   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2802 }
2803
2804 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2805                                                    SelectionDAG &DAG,
2806                                                    MachineFrameInfo *MFI,
2807                                                    int ClobberedFI) const {
2808   SmallVector<SDValue, 8> ArgChains;
2809   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2810   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2811
2812   // Include the original chain at the beginning of the list. When this is
2813   // used by target LowerCall hooks, this helps legalize find the
2814   // CALLSEQ_BEGIN node.
2815   ArgChains.push_back(Chain);
2816
2817   // Add a chain value for each stack argument corresponding
2818   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2819                             UE = DAG.getEntryNode().getNode()->use_end();
2820        U != UE; ++U)
2821     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2822       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2823         if (FI->getIndex() < 0) {
2824           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2825           int64_t InLastByte = InFirstByte;
2826           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2827
2828           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2829               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2830             ArgChains.push_back(SDValue(L, 1));
2831         }
2832
2833   // Build a tokenfactor for all the chains.
2834   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2835 }
2836
2837 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2838                                                    bool TailCallOpt) const {
2839   return CallCC == CallingConv::Fast && TailCallOpt;
2840 }
2841
2842 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2843   return CallCC == CallingConv::Fast;
2844 }
2845
2846 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2847 /// and add input and output parameter nodes.
2848 SDValue
2849 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2850                                  SmallVectorImpl<SDValue> &InVals) const {
2851   SelectionDAG &DAG = CLI.DAG;
2852   SDLoc &DL = CLI.DL;
2853   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2854   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2855   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2856   SDValue Chain = CLI.Chain;
2857   SDValue Callee = CLI.Callee;
2858   bool &IsTailCall = CLI.IsTailCall;
2859   CallingConv::ID CallConv = CLI.CallConv;
2860   bool IsVarArg = CLI.IsVarArg;
2861
2862   MachineFunction &MF = DAG.getMachineFunction();
2863   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2864   bool IsThisReturn = false;
2865
2866   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2867   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2868   bool IsSibCall = false;
2869
2870   if (IsTailCall) {
2871     // Check if it's really possible to do a tail call.
2872     IsTailCall = isEligibleForTailCallOptimization(
2873         Callee, CallConv, IsVarArg, IsStructRet,
2874         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2875     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2876       report_fatal_error("failed to perform tail call elimination on a call "
2877                          "site marked musttail");
2878
2879     // A sibling call is one where we're under the usual C ABI and not planning
2880     // to change that but can still do a tail call:
2881     if (!TailCallOpt && IsTailCall)
2882       IsSibCall = true;
2883
2884     if (IsTailCall)
2885       ++NumTailCalls;
2886   }
2887
2888   // Analyze operands of the call, assigning locations to each operand.
2889   SmallVector<CCValAssign, 16> ArgLocs;
2890   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2891                  *DAG.getContext());
2892
2893   if (IsVarArg) {
2894     // Handle fixed and variable vector arguments differently.
2895     // Variable vector arguments always go into memory.
2896     unsigned NumArgs = Outs.size();
2897
2898     for (unsigned i = 0; i != NumArgs; ++i) {
2899       MVT ArgVT = Outs[i].VT;
2900       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2901       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2902                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2903       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2904       assert(!Res && "Call operand has unhandled type");
2905       (void)Res;
2906     }
2907   } else {
2908     // At this point, Outs[].VT may already be promoted to i32. To correctly
2909     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2910     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2911     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2912     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2913     // LocVT.
2914     unsigned NumArgs = Outs.size();
2915     for (unsigned i = 0; i != NumArgs; ++i) {
2916       MVT ValVT = Outs[i].VT;
2917       // Get type of the original argument.
2918       EVT ActualVT = getValueType(DAG.getDataLayout(),
2919                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2920                                   /*AllowUnknown*/ true);
2921       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2922       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2923       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2924       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2925         ValVT = MVT::i8;
2926       else if (ActualMVT == MVT::i16)
2927         ValVT = MVT::i16;
2928
2929       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2930       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2931       assert(!Res && "Call operand has unhandled type");
2932       (void)Res;
2933     }
2934   }
2935
2936   // Get a count of how many bytes are to be pushed on the stack.
2937   unsigned NumBytes = CCInfo.getNextStackOffset();
2938
2939   if (IsSibCall) {
2940     // Since we're not changing the ABI to make this a tail call, the memory
2941     // operands are already available in the caller's incoming argument space.
2942     NumBytes = 0;
2943   }
2944
2945   // FPDiff is the byte offset of the call's argument area from the callee's.
2946   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2947   // by this amount for a tail call. In a sibling call it must be 0 because the
2948   // caller will deallocate the entire stack and the callee still expects its
2949   // arguments to begin at SP+0. Completely unused for non-tail calls.
2950   int FPDiff = 0;
2951
2952   if (IsTailCall && !IsSibCall) {
2953     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2954
2955     // Since callee will pop argument stack as a tail call, we must keep the
2956     // popped size 16-byte aligned.
2957     NumBytes = RoundUpToAlignment(NumBytes, 16);
2958
2959     // FPDiff will be negative if this tail call requires more space than we
2960     // would automatically have in our incoming argument space. Positive if we
2961     // can actually shrink the stack.
2962     FPDiff = NumReusableBytes - NumBytes;
2963
2964     // The stack pointer must be 16-byte aligned at all times it's used for a
2965     // memory operation, which in practice means at *all* times and in
2966     // particular across call boundaries. Therefore our own arguments started at
2967     // a 16-byte aligned SP and the delta applied for the tail call should
2968     // satisfy the same constraint.
2969     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2970   }
2971
2972   // Adjust the stack pointer for the new arguments...
2973   // These operations are automatically eliminated by the prolog/epilog pass
2974   if (!IsSibCall)
2975     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2976                                                               true),
2977                                  DL);
2978
2979   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2980                                         getPointerTy(DAG.getDataLayout()));
2981
2982   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2983   SmallVector<SDValue, 8> MemOpChains;
2984   auto PtrVT = getPointerTy(DAG.getDataLayout());
2985
2986   // Walk the register/memloc assignments, inserting copies/loads.
2987   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2988        ++i, ++realArgIdx) {
2989     CCValAssign &VA = ArgLocs[i];
2990     SDValue Arg = OutVals[realArgIdx];
2991     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2992
2993     // Promote the value if needed.
2994     switch (VA.getLocInfo()) {
2995     default:
2996       llvm_unreachable("Unknown loc info!");
2997     case CCValAssign::Full:
2998       break;
2999     case CCValAssign::SExt:
3000       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3001       break;
3002     case CCValAssign::ZExt:
3003       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3004       break;
3005     case CCValAssign::AExt:
3006       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3007         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3008         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3009         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3010       }
3011       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3012       break;
3013     case CCValAssign::BCvt:
3014       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3015       break;
3016     case CCValAssign::FPExt:
3017       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3018       break;
3019     }
3020
3021     if (VA.isRegLoc()) {
3022       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3023         assert(VA.getLocVT() == MVT::i64 &&
3024                "unexpected calling convention register assignment");
3025         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3026                "unexpected use of 'returned'");
3027         IsThisReturn = true;
3028       }
3029       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3030     } else {
3031       assert(VA.isMemLoc());
3032
3033       SDValue DstAddr;
3034       MachinePointerInfo DstInfo;
3035
3036       // FIXME: This works on big-endian for composite byvals, which are the
3037       // common case. It should also work for fundamental types too.
3038       uint32_t BEAlign = 0;
3039       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3040                                         : VA.getValVT().getSizeInBits();
3041       OpSize = (OpSize + 7) / 8;
3042       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3043           !Flags.isInConsecutiveRegs()) {
3044         if (OpSize < 8)
3045           BEAlign = 8 - OpSize;
3046       }
3047       unsigned LocMemOffset = VA.getLocMemOffset();
3048       int32_t Offset = LocMemOffset + BEAlign;
3049       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3050       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3051
3052       if (IsTailCall) {
3053         Offset = Offset + FPDiff;
3054         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3055
3056         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3057         DstInfo =
3058             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3059
3060         // Make sure any stack arguments overlapping with where we're storing
3061         // are loaded before this eventual operation. Otherwise they'll be
3062         // clobbered.
3063         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3064       } else {
3065         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3066
3067         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3068         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3069                                                LocMemOffset);
3070       }
3071
3072       if (Outs[i].Flags.isByVal()) {
3073         SDValue SizeNode =
3074             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3075         SDValue Cpy = DAG.getMemcpy(
3076             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3077             /*isVol = */ false, /*AlwaysInline = */ false,
3078             /*isTailCall = */ false,
3079             DstInfo, MachinePointerInfo());
3080
3081         MemOpChains.push_back(Cpy);
3082       } else {
3083         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3084         // promoted to a legal register type i32, we should truncate Arg back to
3085         // i1/i8/i16.
3086         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3087             VA.getValVT() == MVT::i16)
3088           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3089
3090         SDValue Store =
3091             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3092         MemOpChains.push_back(Store);
3093       }
3094     }
3095   }
3096
3097   if (!MemOpChains.empty())
3098     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3099
3100   // Build a sequence of copy-to-reg nodes chained together with token chain
3101   // and flag operands which copy the outgoing args into the appropriate regs.
3102   SDValue InFlag;
3103   for (auto &RegToPass : RegsToPass) {
3104     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3105                              RegToPass.second, InFlag);
3106     InFlag = Chain.getValue(1);
3107   }
3108
3109   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3110   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3111   // node so that legalize doesn't hack it.
3112   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3113       Subtarget->isTargetMachO()) {
3114     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3115       const GlobalValue *GV = G->getGlobal();
3116       bool InternalLinkage = GV->hasInternalLinkage();
3117       if (InternalLinkage)
3118         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3119       else {
3120         Callee =
3121             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3122         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3123       }
3124     } else if (ExternalSymbolSDNode *S =
3125                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3126       const char *Sym = S->getSymbol();
3127       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3128       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3129     }
3130   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3131     const GlobalValue *GV = G->getGlobal();
3132     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3133   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3134     const char *Sym = S->getSymbol();
3135     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3136   }
3137
3138   // We don't usually want to end the call-sequence here because we would tidy
3139   // the frame up *after* the call, however in the ABI-changing tail-call case
3140   // we've carefully laid out the parameters so that when sp is reset they'll be
3141   // in the correct location.
3142   if (IsTailCall && !IsSibCall) {
3143     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3144                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3145     InFlag = Chain.getValue(1);
3146   }
3147
3148   std::vector<SDValue> Ops;
3149   Ops.push_back(Chain);
3150   Ops.push_back(Callee);
3151
3152   if (IsTailCall) {
3153     // Each tail call may have to adjust the stack by a different amount, so
3154     // this information must travel along with the operation for eventual
3155     // consumption by emitEpilogue.
3156     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3157   }
3158
3159   // Add argument registers to the end of the list so that they are known live
3160   // into the call.
3161   for (auto &RegToPass : RegsToPass)
3162     Ops.push_back(DAG.getRegister(RegToPass.first,
3163                                   RegToPass.second.getValueType()));
3164
3165   // Add a register mask operand representing the call-preserved registers.
3166   const uint32_t *Mask;
3167   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3168   if (IsThisReturn) {
3169     // For 'this' returns, use the X0-preserving mask if applicable
3170     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3171     if (!Mask) {
3172       IsThisReturn = false;
3173       Mask = TRI->getCallPreservedMask(MF, CallConv);
3174     }
3175   } else
3176     Mask = TRI->getCallPreservedMask(MF, CallConv);
3177
3178   assert(Mask && "Missing call preserved mask for calling convention");
3179   Ops.push_back(DAG.getRegisterMask(Mask));
3180
3181   if (InFlag.getNode())
3182     Ops.push_back(InFlag);
3183
3184   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3185
3186   // If we're doing a tall call, use a TC_RETURN here rather than an
3187   // actual call instruction.
3188   if (IsTailCall) {
3189     MF.getFrameInfo()->setHasTailCall();
3190     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3191   }
3192
3193   // Returns a chain and a flag for retval copy to use.
3194   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3195   InFlag = Chain.getValue(1);
3196
3197   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3198                                 ? RoundUpToAlignment(NumBytes, 16)
3199                                 : 0;
3200
3201   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3202                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3203                              InFlag, DL);
3204   if (!Ins.empty())
3205     InFlag = Chain.getValue(1);
3206
3207   // Handle result values, copying them out of physregs into vregs that we
3208   // return.
3209   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3210                          InVals, IsThisReturn,
3211                          IsThisReturn ? OutVals[0] : SDValue());
3212 }
3213
3214 bool AArch64TargetLowering::CanLowerReturn(
3215     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3216     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3217   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3218                           ? RetCC_AArch64_WebKit_JS
3219                           : RetCC_AArch64_AAPCS;
3220   SmallVector<CCValAssign, 16> RVLocs;
3221   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3222   return CCInfo.CheckReturn(Outs, RetCC);
3223 }
3224
3225 SDValue
3226 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3227                                    bool isVarArg,
3228                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3229                                    const SmallVectorImpl<SDValue> &OutVals,
3230                                    SDLoc DL, SelectionDAG &DAG) const {
3231   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3232                           ? RetCC_AArch64_WebKit_JS
3233                           : RetCC_AArch64_AAPCS;
3234   SmallVector<CCValAssign, 16> RVLocs;
3235   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3236                  *DAG.getContext());
3237   CCInfo.AnalyzeReturn(Outs, RetCC);
3238
3239   // Copy the result values into the output registers.
3240   SDValue Flag;
3241   SmallVector<SDValue, 4> RetOps(1, Chain);
3242   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3243        ++i, ++realRVLocIdx) {
3244     CCValAssign &VA = RVLocs[i];
3245     assert(VA.isRegLoc() && "Can only return in registers!");
3246     SDValue Arg = OutVals[realRVLocIdx];
3247
3248     switch (VA.getLocInfo()) {
3249     default:
3250       llvm_unreachable("Unknown loc info!");
3251     case CCValAssign::Full:
3252       if (Outs[i].ArgVT == MVT::i1) {
3253         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3254         // value. This is strictly redundant on Darwin (which uses "zeroext
3255         // i1"), but will be optimised out before ISel.
3256         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3257         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3258       }
3259       break;
3260     case CCValAssign::BCvt:
3261       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3262       break;
3263     }
3264
3265     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3266     Flag = Chain.getValue(1);
3267     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3268   }
3269
3270   RetOps[0] = Chain; // Update chain.
3271
3272   // Add the flag if we have it.
3273   if (Flag.getNode())
3274     RetOps.push_back(Flag);
3275
3276   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3277 }
3278
3279 //===----------------------------------------------------------------------===//
3280 //  Other Lowering Code
3281 //===----------------------------------------------------------------------===//
3282
3283 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3284                                                   SelectionDAG &DAG) const {
3285   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3286   SDLoc DL(Op);
3287   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3288   const GlobalValue *GV = GN->getGlobal();
3289   unsigned char OpFlags =
3290       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3291
3292   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3293          "unexpected offset in global node");
3294
3295   // This also catched the large code model case for Darwin.
3296   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3297     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3298     // FIXME: Once remat is capable of dealing with instructions with register
3299     // operands, expand this into two nodes instead of using a wrapper node.
3300     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3301   }
3302
3303   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3304     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3305            "use of MO_CONSTPOOL only supported on small model");
3306     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3307     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3308     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3309     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3310     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3311     SDValue GlobalAddr = DAG.getLoad(
3312         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3313         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3314         /*isVolatile=*/false,
3315         /*isNonTemporal=*/true,
3316         /*isInvariant=*/true, 8);
3317     if (GN->getOffset() != 0)
3318       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3319                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3320     return GlobalAddr;
3321   }
3322
3323   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3324     const unsigned char MO_NC = AArch64II::MO_NC;
3325     return DAG.getNode(
3326         AArch64ISD::WrapperLarge, DL, PtrVT,
3327         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3328         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3329         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3330         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3331   } else {
3332     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3333     // the only correct model on Darwin.
3334     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3335                                             OpFlags | AArch64II::MO_PAGE);
3336     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3337     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3338
3339     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3340     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3341   }
3342 }
3343
3344 /// \brief Convert a TLS address reference into the correct sequence of loads
3345 /// and calls to compute the variable's address (for Darwin, currently) and
3346 /// return an SDValue containing the final node.
3347
3348 /// Darwin only has one TLS scheme which must be capable of dealing with the
3349 /// fully general situation, in the worst case. This means:
3350 ///     + "extern __thread" declaration.
3351 ///     + Defined in a possibly unknown dynamic library.
3352 ///
3353 /// The general system is that each __thread variable has a [3 x i64] descriptor
3354 /// which contains information used by the runtime to calculate the address. The
3355 /// only part of this the compiler needs to know about is the first xword, which
3356 /// contains a function pointer that must be called with the address of the
3357 /// entire descriptor in "x0".
3358 ///
3359 /// Since this descriptor may be in a different unit, in general even the
3360 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3361 /// is:
3362 ///     adrp x0, _var@TLVPPAGE
3363 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3364 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3365 ///                                      ; the function pointer
3366 ///     blr x1                           ; Uses descriptor address in x0
3367 ///     ; Address of _var is now in x0.
3368 ///
3369 /// If the address of _var's descriptor *is* known to the linker, then it can
3370 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3371 /// a slight efficiency gain.
3372 SDValue
3373 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3374                                                    SelectionDAG &DAG) const {
3375   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3376
3377   SDLoc DL(Op);
3378   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3379   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3380
3381   SDValue TLVPAddr =
3382       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3383   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3384
3385   // The first entry in the descriptor is a function pointer that we must call
3386   // to obtain the address of the variable.
3387   SDValue Chain = DAG.getEntryNode();
3388   SDValue FuncTLVGet =
3389       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3390                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3391                   true, true, 8);
3392   Chain = FuncTLVGet.getValue(1);
3393
3394   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3395   MFI->setAdjustsStack(true);
3396
3397   // TLS calls preserve all registers except those that absolutely must be
3398   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3399   // silly).
3400   const uint32_t *Mask =
3401       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3402
3403   // Finally, we can make the call. This is just a degenerate version of a
3404   // normal AArch64 call node: x0 takes the address of the descriptor, and
3405   // returns the address of the variable in this thread.
3406   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3407   Chain =
3408       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3409                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3410                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3411   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3412 }
3413
3414 /// When accessing thread-local variables under either the general-dynamic or
3415 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3416 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3417 /// is a function pointer to carry out the resolution.
3418 ///
3419 /// The sequence is:
3420 ///    adrp  x0, :tlsdesc:var
3421 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3422 ///    add   x0, x0, #:tlsdesc_lo12:var
3423 ///    .tlsdesccall var
3424 ///    blr   x1
3425 ///    (TPIDR_EL0 offset now in x0)
3426 ///
3427 ///  The above sequence must be produced unscheduled, to enable the linker to
3428 ///  optimize/relax this sequence.
3429 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3430 ///  above sequence, and expanded really late in the compilation flow, to ensure
3431 ///  the sequence is produced as per above.
3432 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3433                                                       SelectionDAG &DAG) const {
3434   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3435
3436   SDValue Chain = DAG.getEntryNode();
3437   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3438
3439   SmallVector<SDValue, 2> Ops;
3440   Ops.push_back(Chain);
3441   Ops.push_back(SymAddr);
3442
3443   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3444   SDValue Glue = Chain.getValue(1);
3445
3446   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3447 }
3448
3449 SDValue
3450 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3451                                                 SelectionDAG &DAG) const {
3452   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3453   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3454          "ELF TLS only supported in small memory model");
3455   // Different choices can be made for the maximum size of the TLS area for a
3456   // module. For the small address model, the default TLS size is 16MiB and the
3457   // maximum TLS size is 4GiB.
3458   // FIXME: add -mtls-size command line option and make it control the 16MiB
3459   // vs. 4GiB code sequence generation.
3460   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3461
3462   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3463
3464   if (DAG.getTarget().Options.EmulatedTLS)
3465     return LowerToTLSEmulatedModel(GA, DAG);
3466
3467   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3468     if (Model == TLSModel::LocalDynamic)
3469       Model = TLSModel::GeneralDynamic;
3470   }
3471
3472   SDValue TPOff;
3473   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3474   SDLoc DL(Op);
3475   const GlobalValue *GV = GA->getGlobal();
3476
3477   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3478
3479   if (Model == TLSModel::LocalExec) {
3480     SDValue HiVar = DAG.getTargetGlobalAddress(
3481         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3482     SDValue LoVar = DAG.getTargetGlobalAddress(
3483         GV, DL, PtrVT, 0,
3484         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3485
3486     SDValue TPWithOff_lo =
3487         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3488                                    HiVar,
3489                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3490                 0);
3491     SDValue TPWithOff =
3492         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3493                                    LoVar,
3494                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3495                 0);
3496     return TPWithOff;
3497   } else if (Model == TLSModel::InitialExec) {
3498     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3499     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3500   } else if (Model == TLSModel::LocalDynamic) {
3501     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3502     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3503     // the beginning of the module's TLS region, followed by a DTPREL offset
3504     // calculation.
3505
3506     // These accesses will need deduplicating if there's more than one.
3507     AArch64FunctionInfo *MFI =
3508         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3509     MFI->incNumLocalDynamicTLSAccesses();
3510
3511     // The call needs a relocation too for linker relaxation. It doesn't make
3512     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3513     // the address.
3514     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3515                                                   AArch64II::MO_TLS);
3516
3517     // Now we can calculate the offset from TPIDR_EL0 to this module's
3518     // thread-local area.
3519     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3520
3521     // Now use :dtprel_whatever: operations to calculate this variable's offset
3522     // in its thread-storage area.
3523     SDValue HiVar = DAG.getTargetGlobalAddress(
3524         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3525     SDValue LoVar = DAG.getTargetGlobalAddress(
3526         GV, DL, MVT::i64, 0,
3527         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3528
3529     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3530                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3531                     0);
3532     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3533                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3534                     0);
3535   } else if (Model == TLSModel::GeneralDynamic) {
3536     // The call needs a relocation too for linker relaxation. It doesn't make
3537     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3538     // the address.
3539     SDValue SymAddr =
3540         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3541
3542     // Finally we can make a call to calculate the offset from tpidr_el0.
3543     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3544   } else
3545     llvm_unreachable("Unsupported ELF TLS access model");
3546
3547   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3548 }
3549
3550 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3551                                                      SelectionDAG &DAG) const {
3552   if (Subtarget->isTargetDarwin())
3553     return LowerDarwinGlobalTLSAddress(Op, DAG);
3554   else if (Subtarget->isTargetELF())
3555     return LowerELFGlobalTLSAddress(Op, DAG);
3556
3557   llvm_unreachable("Unexpected platform trying to use TLS");
3558 }
3559 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3560   SDValue Chain = Op.getOperand(0);
3561   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3562   SDValue LHS = Op.getOperand(2);
3563   SDValue RHS = Op.getOperand(3);
3564   SDValue Dest = Op.getOperand(4);
3565   SDLoc dl(Op);
3566
3567   // Handle f128 first, since lowering it will result in comparing the return
3568   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3569   // is expecting to deal with.
3570   if (LHS.getValueType() == MVT::f128) {
3571     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3572
3573     // If softenSetCCOperands returned a scalar, we need to compare the result
3574     // against zero to select between true and false values.
3575     if (!RHS.getNode()) {
3576       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3577       CC = ISD::SETNE;
3578     }
3579   }
3580
3581   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3582   // instruction.
3583   unsigned Opc = LHS.getOpcode();
3584   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3585       cast<ConstantSDNode>(RHS)->isOne() &&
3586       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3587        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3588     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3589            "Unexpected condition code.");
3590     // Only lower legal XALUO ops.
3591     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3592       return SDValue();
3593
3594     // The actual operation with overflow check.
3595     AArch64CC::CondCode OFCC;
3596     SDValue Value, Overflow;
3597     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3598
3599     if (CC == ISD::SETNE)
3600       OFCC = getInvertedCondCode(OFCC);
3601     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3602
3603     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3604                        Overflow);
3605   }
3606
3607   if (LHS.getValueType().isInteger()) {
3608     assert((LHS.getValueType() == RHS.getValueType()) &&
3609            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3610
3611     // If the RHS of the comparison is zero, we can potentially fold this
3612     // to a specialized branch.
3613     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3614     if (RHSC && RHSC->getZExtValue() == 0) {
3615       if (CC == ISD::SETEQ) {
3616         // See if we can use a TBZ to fold in an AND as well.
3617         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3618         // out of bounds, a late MI-layer pass rewrites branches.
3619         // 403.gcc is an example that hits this case.
3620         if (LHS.getOpcode() == ISD::AND &&
3621             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3622             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3623           SDValue Test = LHS.getOperand(0);
3624           uint64_t Mask = LHS.getConstantOperandVal(1);
3625           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3626                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3627                              Dest);
3628         }
3629
3630         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3631       } else if (CC == ISD::SETNE) {
3632         // See if we can use a TBZ to fold in an AND as well.
3633         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3634         // out of bounds, a late MI-layer pass rewrites branches.
3635         // 403.gcc is an example that hits this case.
3636         if (LHS.getOpcode() == ISD::AND &&
3637             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3638             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3639           SDValue Test = LHS.getOperand(0);
3640           uint64_t Mask = LHS.getConstantOperandVal(1);
3641           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3642                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3643                              Dest);
3644         }
3645
3646         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3647       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3648         // Don't combine AND since emitComparison converts the AND to an ANDS
3649         // (a.k.a. TST) and the test in the test bit and branch instruction
3650         // becomes redundant.  This would also increase register pressure.
3651         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3652         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3653                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3654       }
3655     }
3656     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3657         LHS.getOpcode() != ISD::AND) {
3658       // Don't combine AND since emitComparison converts the AND to an ANDS
3659       // (a.k.a. TST) and the test in the test bit and branch instruction
3660       // becomes redundant.  This would also increase register pressure.
3661       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3662       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3663                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3664     }
3665
3666     SDValue CCVal;
3667     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3668     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3669                        Cmp);
3670   }
3671
3672   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3673
3674   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3675   // clean.  Some of them require two branches to implement.
3676   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3677   AArch64CC::CondCode CC1, CC2;
3678   changeFPCCToAArch64CC(CC, CC1, CC2);
3679   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3680   SDValue BR1 =
3681       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3682   if (CC2 != AArch64CC::AL) {
3683     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3684     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3685                        Cmp);
3686   }
3687
3688   return BR1;
3689 }
3690
3691 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3692                                               SelectionDAG &DAG) const {
3693   EVT VT = Op.getValueType();
3694   SDLoc DL(Op);
3695
3696   SDValue In1 = Op.getOperand(0);
3697   SDValue In2 = Op.getOperand(1);
3698   EVT SrcVT = In2.getValueType();
3699
3700   if (SrcVT.bitsLT(VT))
3701     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3702   else if (SrcVT.bitsGT(VT))
3703     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3704
3705   EVT VecVT;
3706   EVT EltVT;
3707   uint64_t EltMask;
3708   SDValue VecVal1, VecVal2;
3709   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3710     EltVT = MVT::i32;
3711     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3712     EltMask = 0x80000000ULL;
3713
3714     if (!VT.isVector()) {
3715       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3716                                           DAG.getUNDEF(VecVT), In1);
3717       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3718                                           DAG.getUNDEF(VecVT), In2);
3719     } else {
3720       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3721       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3722     }
3723   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3724     EltVT = MVT::i64;
3725     VecVT = MVT::v2i64;
3726
3727     // We want to materialize a mask with the high bit set, but the AdvSIMD
3728     // immediate moves cannot materialize that in a single instruction for
3729     // 64-bit elements. Instead, materialize zero and then negate it.
3730     EltMask = 0;
3731
3732     if (!VT.isVector()) {
3733       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3734                                           DAG.getUNDEF(VecVT), In1);
3735       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3736                                           DAG.getUNDEF(VecVT), In2);
3737     } else {
3738       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3739       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3740     }
3741   } else {
3742     llvm_unreachable("Invalid type for copysign!");
3743   }
3744
3745   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3746
3747   // If we couldn't materialize the mask above, then the mask vector will be
3748   // the zero vector, and we need to negate it here.
3749   if (VT == MVT::f64 || VT == MVT::v2f64) {
3750     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3751     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3752     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3753   }
3754
3755   SDValue Sel =
3756       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3757
3758   if (VT == MVT::f32)
3759     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3760   else if (VT == MVT::f64)
3761     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3762   else
3763     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3764 }
3765
3766 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3767   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3768           Attribute::NoImplicitFloat))
3769     return SDValue();
3770
3771   if (!Subtarget->hasNEON())
3772     return SDValue();
3773
3774   // While there is no integer popcount instruction, it can
3775   // be more efficiently lowered to the following sequence that uses
3776   // AdvSIMD registers/instructions as long as the copies to/from
3777   // the AdvSIMD registers are cheap.
3778   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3779   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3780   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3781   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3782   SDValue Val = Op.getOperand(0);
3783   SDLoc DL(Op);
3784   EVT VT = Op.getValueType();
3785
3786   if (VT == MVT::i32)
3787     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3788   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3789
3790   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3791   SDValue UaddLV = DAG.getNode(
3792       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3793       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3794
3795   if (VT == MVT::i64)
3796     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3797   return UaddLV;
3798 }
3799
3800 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3801
3802   if (Op.getValueType().isVector())
3803     return LowerVSETCC(Op, DAG);
3804
3805   SDValue LHS = Op.getOperand(0);
3806   SDValue RHS = Op.getOperand(1);
3807   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3808   SDLoc dl(Op);
3809
3810   // We chose ZeroOrOneBooleanContents, so use zero and one.
3811   EVT VT = Op.getValueType();
3812   SDValue TVal = DAG.getConstant(1, dl, VT);
3813   SDValue FVal = DAG.getConstant(0, dl, VT);
3814
3815   // Handle f128 first, since one possible outcome is a normal integer
3816   // comparison which gets picked up by the next if statement.
3817   if (LHS.getValueType() == MVT::f128) {
3818     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3819
3820     // If softenSetCCOperands returned a scalar, use it.
3821     if (!RHS.getNode()) {
3822       assert(LHS.getValueType() == Op.getValueType() &&
3823              "Unexpected setcc expansion!");
3824       return LHS;
3825     }
3826   }
3827
3828   if (LHS.getValueType().isInteger()) {
3829     SDValue CCVal;
3830     SDValue Cmp =
3831         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3832
3833     // Note that we inverted the condition above, so we reverse the order of
3834     // the true and false operands here.  This will allow the setcc to be
3835     // matched to a single CSINC instruction.
3836     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3837   }
3838
3839   // Now we know we're dealing with FP values.
3840   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3841
3842   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3843   // and do the comparison.
3844   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3845
3846   AArch64CC::CondCode CC1, CC2;
3847   changeFPCCToAArch64CC(CC, CC1, CC2);
3848   if (CC2 == AArch64CC::AL) {
3849     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3850     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3851
3852     // Note that we inverted the condition above, so we reverse the order of
3853     // the true and false operands here.  This will allow the setcc to be
3854     // matched to a single CSINC instruction.
3855     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3856   } else {
3857     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3858     // totally clean.  Some of them require two CSELs to implement.  As is in
3859     // this case, we emit the first CSEL and then emit a second using the output
3860     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3861
3862     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3863     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3864     SDValue CS1 =
3865         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3866
3867     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3868     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3869   }
3870 }
3871
3872 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3873                                               SDValue RHS, SDValue TVal,
3874                                               SDValue FVal, SDLoc dl,
3875                                               SelectionDAG &DAG) const {
3876   // Handle f128 first, because it will result in a comparison of some RTLIB
3877   // call result against zero.
3878   if (LHS.getValueType() == MVT::f128) {
3879     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3880
3881     // If softenSetCCOperands returned a scalar, we need to compare the result
3882     // against zero to select between true and false values.
3883     if (!RHS.getNode()) {
3884       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3885       CC = ISD::SETNE;
3886     }
3887   }
3888
3889   // Handle integers first.
3890   if (LHS.getValueType().isInteger()) {
3891     assert((LHS.getValueType() == RHS.getValueType()) &&
3892            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3893
3894     unsigned Opcode = AArch64ISD::CSEL;
3895
3896     // If both the TVal and the FVal are constants, see if we can swap them in
3897     // order to for a CSINV or CSINC out of them.
3898     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3899     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3900
3901     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3902       std::swap(TVal, FVal);
3903       std::swap(CTVal, CFVal);
3904       CC = ISD::getSetCCInverse(CC, true);
3905     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3906       std::swap(TVal, FVal);
3907       std::swap(CTVal, CFVal);
3908       CC = ISD::getSetCCInverse(CC, true);
3909     } else if (TVal.getOpcode() == ISD::XOR) {
3910       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3911       // with a CSINV rather than a CSEL.
3912       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3913
3914       if (CVal && CVal->isAllOnesValue()) {
3915         std::swap(TVal, FVal);
3916         std::swap(CTVal, CFVal);
3917         CC = ISD::getSetCCInverse(CC, true);
3918       }
3919     } else if (TVal.getOpcode() == ISD::SUB) {
3920       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3921       // that we can match with a CSNEG rather than a CSEL.
3922       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3923
3924       if (CVal && CVal->isNullValue()) {
3925         std::swap(TVal, FVal);
3926         std::swap(CTVal, CFVal);
3927         CC = ISD::getSetCCInverse(CC, true);
3928       }
3929     } else if (CTVal && CFVal) {
3930       const int64_t TrueVal = CTVal->getSExtValue();
3931       const int64_t FalseVal = CFVal->getSExtValue();
3932       bool Swap = false;
3933
3934       // If both TVal and FVal are constants, see if FVal is the
3935       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3936       // instead of a CSEL in that case.
3937       if (TrueVal == ~FalseVal) {
3938         Opcode = AArch64ISD::CSINV;
3939       } else if (TrueVal == -FalseVal) {
3940         Opcode = AArch64ISD::CSNEG;
3941       } else if (TVal.getValueType() == MVT::i32) {
3942         // If our operands are only 32-bit wide, make sure we use 32-bit
3943         // arithmetic for the check whether we can use CSINC. This ensures that
3944         // the addition in the check will wrap around properly in case there is
3945         // an overflow (which would not be the case if we do the check with
3946         // 64-bit arithmetic).
3947         const uint32_t TrueVal32 = CTVal->getZExtValue();
3948         const uint32_t FalseVal32 = CFVal->getZExtValue();
3949
3950         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3951           Opcode = AArch64ISD::CSINC;
3952
3953           if (TrueVal32 > FalseVal32) {
3954             Swap = true;
3955           }
3956         }
3957         // 64-bit check whether we can use CSINC.
3958       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3959         Opcode = AArch64ISD::CSINC;
3960
3961         if (TrueVal > FalseVal) {
3962           Swap = true;
3963         }
3964       }
3965
3966       // Swap TVal and FVal if necessary.
3967       if (Swap) {
3968         std::swap(TVal, FVal);
3969         std::swap(CTVal, CFVal);
3970         CC = ISD::getSetCCInverse(CC, true);
3971       }
3972
3973       if (Opcode != AArch64ISD::CSEL) {
3974         // Drop FVal since we can get its value by simply inverting/negating
3975         // TVal.
3976         FVal = TVal;
3977       }
3978     }
3979
3980     SDValue CCVal;
3981     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3982
3983     EVT VT = TVal.getValueType();
3984     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3985   }
3986
3987   // Now we know we're dealing with FP values.
3988   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3989   assert(LHS.getValueType() == RHS.getValueType());
3990   EVT VT = TVal.getValueType();
3991   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3992
3993   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3994   // clean.  Some of them require two CSELs to implement.
3995   AArch64CC::CondCode CC1, CC2;
3996   changeFPCCToAArch64CC(CC, CC1, CC2);
3997   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3998   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3999
4000   // If we need a second CSEL, emit it, using the output of the first as the
4001   // RHS.  We're effectively OR'ing the two CC's together.
4002   if (CC2 != AArch64CC::AL) {
4003     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4004     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4005   }
4006
4007   // Otherwise, return the output of the first CSEL.
4008   return CS1;
4009 }
4010
4011 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4012                                               SelectionDAG &DAG) const {
4013   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4014   SDValue LHS = Op.getOperand(0);
4015   SDValue RHS = Op.getOperand(1);
4016   SDValue TVal = Op.getOperand(2);
4017   SDValue FVal = Op.getOperand(3);
4018   SDLoc DL(Op);
4019   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4020 }
4021
4022 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4023                                            SelectionDAG &DAG) const {
4024   SDValue CCVal = Op->getOperand(0);
4025   SDValue TVal = Op->getOperand(1);
4026   SDValue FVal = Op->getOperand(2);
4027   SDLoc DL(Op);
4028
4029   unsigned Opc = CCVal.getOpcode();
4030   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4031   // instruction.
4032   if (CCVal.getResNo() == 1 &&
4033       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4034        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4035     // Only lower legal XALUO ops.
4036     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4037       return SDValue();
4038
4039     AArch64CC::CondCode OFCC;
4040     SDValue Value, Overflow;
4041     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4042     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4043
4044     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4045                        CCVal, Overflow);
4046   }
4047
4048   // Lower it the same way as we would lower a SELECT_CC node.
4049   ISD::CondCode CC;
4050   SDValue LHS, RHS;
4051   if (CCVal.getOpcode() == ISD::SETCC) {
4052     LHS = CCVal.getOperand(0);
4053     RHS = CCVal.getOperand(1);
4054     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4055   } else {
4056     LHS = CCVal;
4057     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4058     CC = ISD::SETNE;
4059   }
4060   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4061 }
4062
4063 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4064                                               SelectionDAG &DAG) const {
4065   // Jump table entries as PC relative offsets. No additional tweaking
4066   // is necessary here. Just get the address of the jump table.
4067   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4068   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4069   SDLoc DL(Op);
4070
4071   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4072       !Subtarget->isTargetMachO()) {
4073     const unsigned char MO_NC = AArch64II::MO_NC;
4074     return DAG.getNode(
4075         AArch64ISD::WrapperLarge, DL, PtrVT,
4076         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4077         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4078         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4079         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4080                                AArch64II::MO_G0 | MO_NC));
4081   }
4082
4083   SDValue Hi =
4084       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4085   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4086                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4087   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4088   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4089 }
4090
4091 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4092                                                  SelectionDAG &DAG) const {
4093   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4094   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4095   SDLoc DL(Op);
4096
4097   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4098     // Use the GOT for the large code model on iOS.
4099     if (Subtarget->isTargetMachO()) {
4100       SDValue GotAddr = DAG.getTargetConstantPool(
4101           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4102           AArch64II::MO_GOT);
4103       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4104     }
4105
4106     const unsigned char MO_NC = AArch64II::MO_NC;
4107     return DAG.getNode(
4108         AArch64ISD::WrapperLarge, DL, PtrVT,
4109         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4110                                   CP->getOffset(), AArch64II::MO_G3),
4111         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4112                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4113         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4114                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4115         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4116                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4117   } else {
4118     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4119     // ELF, the only valid one on Darwin.
4120     SDValue Hi =
4121         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4122                                   CP->getOffset(), AArch64II::MO_PAGE);
4123     SDValue Lo = DAG.getTargetConstantPool(
4124         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4125         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4126
4127     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4128     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4129   }
4130 }
4131
4132 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4133                                                SelectionDAG &DAG) const {
4134   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4135   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4136   SDLoc DL(Op);
4137   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4138       !Subtarget->isTargetMachO()) {
4139     const unsigned char MO_NC = AArch64II::MO_NC;
4140     return DAG.getNode(
4141         AArch64ISD::WrapperLarge, DL, PtrVT,
4142         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4143         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4144         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4145         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4146   } else {
4147     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4148     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4149                                                              AArch64II::MO_NC);
4150     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4151     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4152   }
4153 }
4154
4155 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4156                                                  SelectionDAG &DAG) const {
4157   AArch64FunctionInfo *FuncInfo =
4158       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4159
4160   SDLoc DL(Op);
4161   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4162                                  getPointerTy(DAG.getDataLayout()));
4163   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4164   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4165                       MachinePointerInfo(SV), false, false, 0);
4166 }
4167
4168 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4169                                                 SelectionDAG &DAG) const {
4170   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4171   // Standard, section B.3.
4172   MachineFunction &MF = DAG.getMachineFunction();
4173   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4174   auto PtrVT = getPointerTy(DAG.getDataLayout());
4175   SDLoc DL(Op);
4176
4177   SDValue Chain = Op.getOperand(0);
4178   SDValue VAList = Op.getOperand(1);
4179   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4180   SmallVector<SDValue, 4> MemOps;
4181
4182   // void *__stack at offset 0
4183   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4184   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4185                                 MachinePointerInfo(SV), false, false, 8));
4186
4187   // void *__gr_top at offset 8
4188   int GPRSize = FuncInfo->getVarArgsGPRSize();
4189   if (GPRSize > 0) {
4190     SDValue GRTop, GRTopAddr;
4191
4192     GRTopAddr =
4193         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4194
4195     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4196     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4197                         DAG.getConstant(GPRSize, DL, PtrVT));
4198
4199     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4200                                   MachinePointerInfo(SV, 8), false, false, 8));
4201   }
4202
4203   // void *__vr_top at offset 16
4204   int FPRSize = FuncInfo->getVarArgsFPRSize();
4205   if (FPRSize > 0) {
4206     SDValue VRTop, VRTopAddr;
4207     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4208                             DAG.getConstant(16, DL, PtrVT));
4209
4210     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4211     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4212                         DAG.getConstant(FPRSize, DL, PtrVT));
4213
4214     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4215                                   MachinePointerInfo(SV, 16), false, false, 8));
4216   }
4217
4218   // int __gr_offs at offset 24
4219   SDValue GROffsAddr =
4220       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4221   MemOps.push_back(DAG.getStore(Chain, DL,
4222                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4223                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4224                                 false, 4));
4225
4226   // int __vr_offs at offset 28
4227   SDValue VROffsAddr =
4228       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4229   MemOps.push_back(DAG.getStore(Chain, DL,
4230                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4231                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4232                                 false, 4));
4233
4234   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4235 }
4236
4237 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4238                                             SelectionDAG &DAG) const {
4239   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4240                                      : LowerAAPCS_VASTART(Op, DAG);
4241 }
4242
4243 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4244                                            SelectionDAG &DAG) const {
4245   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4246   // pointer.
4247   SDLoc DL(Op);
4248   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4249   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4250   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4251
4252   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4253                        Op.getOperand(2),
4254                        DAG.getConstant(VaListSize, DL, MVT::i32),
4255                        8, false, false, false, MachinePointerInfo(DestSV),
4256                        MachinePointerInfo(SrcSV));
4257 }
4258
4259 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4260   assert(Subtarget->isTargetDarwin() &&
4261          "automatic va_arg instruction only works on Darwin");
4262
4263   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4264   EVT VT = Op.getValueType();
4265   SDLoc DL(Op);
4266   SDValue Chain = Op.getOperand(0);
4267   SDValue Addr = Op.getOperand(1);
4268   unsigned Align = Op.getConstantOperandVal(3);
4269   auto PtrVT = getPointerTy(DAG.getDataLayout());
4270
4271   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4272                                false, false, false, 0);
4273   Chain = VAList.getValue(1);
4274
4275   if (Align > 8) {
4276     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4277     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4278                          DAG.getConstant(Align - 1, DL, PtrVT));
4279     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4280                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4281   }
4282
4283   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4284   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4285
4286   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4287   // up to 64 bits.  At the very least, we have to increase the striding of the
4288   // vaargs list to match this, and for FP values we need to introduce
4289   // FP_ROUND nodes as well.
4290   if (VT.isInteger() && !VT.isVector())
4291     ArgSize = 8;
4292   bool NeedFPTrunc = false;
4293   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4294     ArgSize = 8;
4295     NeedFPTrunc = true;
4296   }
4297
4298   // Increment the pointer, VAList, to the next vaarg
4299   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4300                                DAG.getConstant(ArgSize, DL, PtrVT));
4301   // Store the incremented VAList to the legalized pointer
4302   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4303                                  false, false, 0);
4304
4305   // Load the actual argument out of the pointer VAList
4306   if (NeedFPTrunc) {
4307     // Load the value as an f64.
4308     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4309                                  MachinePointerInfo(), false, false, false, 0);
4310     // Round the value down to an f32.
4311     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4312                                    DAG.getIntPtrConstant(1, DL));
4313     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4314     // Merge the rounded value with the chain output of the load.
4315     return DAG.getMergeValues(Ops, DL);
4316   }
4317
4318   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4319                      false, false, 0);
4320 }
4321
4322 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4323                                               SelectionDAG &DAG) const {
4324   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4325   MFI->setFrameAddressIsTaken(true);
4326
4327   EVT VT = Op.getValueType();
4328   SDLoc DL(Op);
4329   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4330   SDValue FrameAddr =
4331       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4332   while (Depth--)
4333     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4334                             MachinePointerInfo(), false, false, false, 0);
4335   return FrameAddr;
4336 }
4337
4338 // FIXME? Maybe this could be a TableGen attribute on some registers and
4339 // this table could be generated automatically from RegInfo.
4340 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4341                                                   SelectionDAG &DAG) const {
4342   unsigned Reg = StringSwitch<unsigned>(RegName)
4343                        .Case("sp", AArch64::SP)
4344                        .Default(0);
4345   if (Reg)
4346     return Reg;
4347   report_fatal_error(Twine("Invalid register name \""
4348                               + StringRef(RegName)  + "\"."));
4349 }
4350
4351 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4352                                                SelectionDAG &DAG) const {
4353   MachineFunction &MF = DAG.getMachineFunction();
4354   MachineFrameInfo *MFI = MF.getFrameInfo();
4355   MFI->setReturnAddressIsTaken(true);
4356
4357   EVT VT = Op.getValueType();
4358   SDLoc DL(Op);
4359   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4360   if (Depth) {
4361     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4362     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4363     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4364                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4365                        MachinePointerInfo(), false, false, false, 0);
4366   }
4367
4368   // Return LR, which contains the return address. Mark it an implicit live-in.
4369   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4370   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4371 }
4372
4373 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4374 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4375 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4376                                                     SelectionDAG &DAG) const {
4377   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4378   EVT VT = Op.getValueType();
4379   unsigned VTBits = VT.getSizeInBits();
4380   SDLoc dl(Op);
4381   SDValue ShOpLo = Op.getOperand(0);
4382   SDValue ShOpHi = Op.getOperand(1);
4383   SDValue ShAmt = Op.getOperand(2);
4384   SDValue ARMcc;
4385   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4386
4387   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4388
4389   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4390                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4391   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4392   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4393                                    DAG.getConstant(VTBits, dl, MVT::i64));
4394   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4395
4396   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4397                                ISD::SETGE, dl, DAG);
4398   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4399
4400   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4401   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4402   SDValue Lo =
4403       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4404
4405   // AArch64 shifts larger than the register width are wrapped rather than
4406   // clamped, so we can't just emit "hi >> x".
4407   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4408   SDValue TrueValHi = Opc == ISD::SRA
4409                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4410                                         DAG.getConstant(VTBits - 1, dl,
4411                                                         MVT::i64))
4412                           : DAG.getConstant(0, dl, VT);
4413   SDValue Hi =
4414       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4415
4416   SDValue Ops[2] = { Lo, Hi };
4417   return DAG.getMergeValues(Ops, dl);
4418 }
4419
4420 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4421 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4422 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4423                                                  SelectionDAG &DAG) const {
4424   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4425   EVT VT = Op.getValueType();
4426   unsigned VTBits = VT.getSizeInBits();
4427   SDLoc dl(Op);
4428   SDValue ShOpLo = Op.getOperand(0);
4429   SDValue ShOpHi = Op.getOperand(1);
4430   SDValue ShAmt = Op.getOperand(2);
4431   SDValue ARMcc;
4432
4433   assert(Op.getOpcode() == ISD::SHL_PARTS);
4434   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4435                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4436   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4437   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4438                                    DAG.getConstant(VTBits, dl, MVT::i64));
4439   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4440   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4441
4442   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4443
4444   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4445                                ISD::SETGE, dl, DAG);
4446   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4447   SDValue Hi =
4448       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4449
4450   // AArch64 shifts of larger than register sizes are wrapped rather than
4451   // clamped, so we can't just emit "lo << a" if a is too big.
4452   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4453   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4454   SDValue Lo =
4455       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4456
4457   SDValue Ops[2] = { Lo, Hi };
4458   return DAG.getMergeValues(Ops, dl);
4459 }
4460
4461 bool AArch64TargetLowering::isOffsetFoldingLegal(
4462     const GlobalAddressSDNode *GA) const {
4463   // The AArch64 target doesn't support folding offsets into global addresses.
4464   return false;
4465 }
4466
4467 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4468   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4469   // FIXME: We should be able to handle f128 as well with a clever lowering.
4470   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4471     return true;
4472
4473   if (VT == MVT::f64)
4474     return AArch64_AM::getFP64Imm(Imm) != -1;
4475   else if (VT == MVT::f32)
4476     return AArch64_AM::getFP32Imm(Imm) != -1;
4477   return false;
4478 }
4479
4480 //===----------------------------------------------------------------------===//
4481 //                          AArch64 Optimization Hooks
4482 //===----------------------------------------------------------------------===//
4483
4484 //===----------------------------------------------------------------------===//
4485 //                          AArch64 Inline Assembly Support
4486 //===----------------------------------------------------------------------===//
4487
4488 // Table of Constraints
4489 // TODO: This is the current set of constraints supported by ARM for the
4490 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4491 //
4492 // r - A general register
4493 // w - An FP/SIMD register of some size in the range v0-v31
4494 // x - An FP/SIMD register of some size in the range v0-v15
4495 // I - Constant that can be used with an ADD instruction
4496 // J - Constant that can be used with a SUB instruction
4497 // K - Constant that can be used with a 32-bit logical instruction
4498 // L - Constant that can be used with a 64-bit logical instruction
4499 // M - Constant that can be used as a 32-bit MOV immediate
4500 // N - Constant that can be used as a 64-bit MOV immediate
4501 // Q - A memory reference with base register and no offset
4502 // S - A symbolic address
4503 // Y - Floating point constant zero
4504 // Z - Integer constant zero
4505 //
4506 //   Note that general register operands will be output using their 64-bit x
4507 // register name, whatever the size of the variable, unless the asm operand
4508 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4509 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4510 // %q modifier.
4511
4512 /// getConstraintType - Given a constraint letter, return the type of
4513 /// constraint it is for this target.
4514 AArch64TargetLowering::ConstraintType
4515 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4516   if (Constraint.size() == 1) {
4517     switch (Constraint[0]) {
4518     default:
4519       break;
4520     case 'z':
4521       return C_Other;
4522     case 'x':
4523     case 'w':
4524       return C_RegisterClass;
4525     // An address with a single base register. Due to the way we
4526     // currently handle addresses it is the same as 'r'.
4527     case 'Q':
4528       return C_Memory;
4529     }
4530   }
4531   return TargetLowering::getConstraintType(Constraint);
4532 }
4533
4534 /// Examine constraint type and operand type and determine a weight value.
4535 /// This object must already have been set up with the operand type
4536 /// and the current alternative constraint selected.
4537 TargetLowering::ConstraintWeight
4538 AArch64TargetLowering::getSingleConstraintMatchWeight(
4539     AsmOperandInfo &info, const char *constraint) const {
4540   ConstraintWeight weight = CW_Invalid;
4541   Value *CallOperandVal = info.CallOperandVal;
4542   // If we don't have a value, we can't do a match,
4543   // but allow it at the lowest weight.
4544   if (!CallOperandVal)
4545     return CW_Default;
4546   Type *type = CallOperandVal->getType();
4547   // Look at the constraint type.
4548   switch (*constraint) {
4549   default:
4550     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4551     break;
4552   case 'x':
4553   case 'w':
4554     if (type->isFloatingPointTy() || type->isVectorTy())
4555       weight = CW_Register;
4556     break;
4557   case 'z':
4558     weight = CW_Constant;
4559     break;
4560   }
4561   return weight;
4562 }
4563
4564 std::pair<unsigned, const TargetRegisterClass *>
4565 AArch64TargetLowering::getRegForInlineAsmConstraint(
4566     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4567   if (Constraint.size() == 1) {
4568     switch (Constraint[0]) {
4569     case 'r':
4570       if (VT.getSizeInBits() == 64)
4571         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4572       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4573     case 'w':
4574       if (VT == MVT::f32)
4575         return std::make_pair(0U, &AArch64::FPR32RegClass);
4576       if (VT.getSizeInBits() == 64)
4577         return std::make_pair(0U, &AArch64::FPR64RegClass);
4578       if (VT.getSizeInBits() == 128)
4579         return std::make_pair(0U, &AArch64::FPR128RegClass);
4580       break;
4581     // The instructions that this constraint is designed for can
4582     // only take 128-bit registers so just use that regclass.
4583     case 'x':
4584       if (VT.getSizeInBits() == 128)
4585         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4586       break;
4587     }
4588   }
4589   if (StringRef("{cc}").equals_lower(Constraint))
4590     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4591
4592   // Use the default implementation in TargetLowering to convert the register
4593   // constraint into a member of a register class.
4594   std::pair<unsigned, const TargetRegisterClass *> Res;
4595   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4596
4597   // Not found as a standard register?
4598   if (!Res.second) {
4599     unsigned Size = Constraint.size();
4600     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4601         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4602       int RegNo;
4603       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4604       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4605         // v0 - v31 are aliases of q0 - q31.
4606         // By default we'll emit v0-v31 for this unless there's a modifier where
4607         // we'll emit the correct register as well.
4608         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4609         Res.second = &AArch64::FPR128RegClass;
4610       }
4611     }
4612   }
4613
4614   return Res;
4615 }
4616
4617 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4618 /// vector.  If it is invalid, don't add anything to Ops.
4619 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4620     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4621     SelectionDAG &DAG) const {
4622   SDValue Result;
4623
4624   // Currently only support length 1 constraints.
4625   if (Constraint.length() != 1)
4626     return;
4627
4628   char ConstraintLetter = Constraint[0];
4629   switch (ConstraintLetter) {
4630   default:
4631     break;
4632
4633   // This set of constraints deal with valid constants for various instructions.
4634   // Validate and return a target constant for them if we can.
4635   case 'z': {
4636     // 'z' maps to xzr or wzr so it needs an input of 0.
4637     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4638     if (!C || C->getZExtValue() != 0)
4639       return;
4640
4641     if (Op.getValueType() == MVT::i64)
4642       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4643     else
4644       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4645     break;
4646   }
4647
4648   case 'I':
4649   case 'J':
4650   case 'K':
4651   case 'L':
4652   case 'M':
4653   case 'N':
4654     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4655     if (!C)
4656       return;
4657
4658     // Grab the value and do some validation.
4659     uint64_t CVal = C->getZExtValue();
4660     switch (ConstraintLetter) {
4661     // The I constraint applies only to simple ADD or SUB immediate operands:
4662     // i.e. 0 to 4095 with optional shift by 12
4663     // The J constraint applies only to ADD or SUB immediates that would be
4664     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4665     // instruction [or vice versa], in other words -1 to -4095 with optional
4666     // left shift by 12.
4667     case 'I':
4668       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4669         break;
4670       return;
4671     case 'J': {
4672       uint64_t NVal = -C->getSExtValue();
4673       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4674         CVal = C->getSExtValue();
4675         break;
4676       }
4677       return;
4678     }
4679     // The K and L constraints apply *only* to logical immediates, including
4680     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4681     // been removed and MOV should be used). So these constraints have to
4682     // distinguish between bit patterns that are valid 32-bit or 64-bit
4683     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4684     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4685     // versa.
4686     case 'K':
4687       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4688         break;
4689       return;
4690     case 'L':
4691       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4692         break;
4693       return;
4694     // The M and N constraints are a superset of K and L respectively, for use
4695     // with the MOV (immediate) alias. As well as the logical immediates they
4696     // also match 32 or 64-bit immediates that can be loaded either using a
4697     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4698     // (M) or 64-bit 0x1234000000000000 (N) etc.
4699     // As a note some of this code is liberally stolen from the asm parser.
4700     case 'M': {
4701       if (!isUInt<32>(CVal))
4702         return;
4703       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4704         break;
4705       if ((CVal & 0xFFFF) == CVal)
4706         break;
4707       if ((CVal & 0xFFFF0000ULL) == CVal)
4708         break;
4709       uint64_t NCVal = ~(uint32_t)CVal;
4710       if ((NCVal & 0xFFFFULL) == NCVal)
4711         break;
4712       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4713         break;
4714       return;
4715     }
4716     case 'N': {
4717       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4718         break;
4719       if ((CVal & 0xFFFFULL) == CVal)
4720         break;
4721       if ((CVal & 0xFFFF0000ULL) == CVal)
4722         break;
4723       if ((CVal & 0xFFFF00000000ULL) == CVal)
4724         break;
4725       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4726         break;
4727       uint64_t NCVal = ~CVal;
4728       if ((NCVal & 0xFFFFULL) == NCVal)
4729         break;
4730       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4731         break;
4732       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4733         break;
4734       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4735         break;
4736       return;
4737     }
4738     default:
4739       return;
4740     }
4741
4742     // All assembler immediates are 64-bit integers.
4743     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4744     break;
4745   }
4746
4747   if (Result.getNode()) {
4748     Ops.push_back(Result);
4749     return;
4750   }
4751
4752   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4753 }
4754
4755 //===----------------------------------------------------------------------===//
4756 //                     AArch64 Advanced SIMD Support
4757 //===----------------------------------------------------------------------===//
4758
4759 /// WidenVector - Given a value in the V64 register class, produce the
4760 /// equivalent value in the V128 register class.
4761 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4762   EVT VT = V64Reg.getValueType();
4763   unsigned NarrowSize = VT.getVectorNumElements();
4764   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4765   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4766   SDLoc DL(V64Reg);
4767
4768   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4769                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4770 }
4771
4772 /// getExtFactor - Determine the adjustment factor for the position when
4773 /// generating an "extract from vector registers" instruction.
4774 static unsigned getExtFactor(SDValue &V) {
4775   EVT EltType = V.getValueType().getVectorElementType();
4776   return EltType.getSizeInBits() / 8;
4777 }
4778
4779 /// NarrowVector - Given a value in the V128 register class, produce the
4780 /// equivalent value in the V64 register class.
4781 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4782   EVT VT = V128Reg.getValueType();
4783   unsigned WideSize = VT.getVectorNumElements();
4784   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4785   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4786   SDLoc DL(V128Reg);
4787
4788   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4789 }
4790
4791 // Gather data to see if the operation can be modelled as a
4792 // shuffle in combination with VEXTs.
4793 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4794                                                   SelectionDAG &DAG) const {
4795   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4796   SDLoc dl(Op);
4797   EVT VT = Op.getValueType();
4798   unsigned NumElts = VT.getVectorNumElements();
4799
4800   struct ShuffleSourceInfo {
4801     SDValue Vec;
4802     unsigned MinElt;
4803     unsigned MaxElt;
4804
4805     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4806     // be compatible with the shuffle we intend to construct. As a result
4807     // ShuffleVec will be some sliding window into the original Vec.
4808     SDValue ShuffleVec;
4809
4810     // Code should guarantee that element i in Vec starts at element "WindowBase
4811     // + i * WindowScale in ShuffleVec".
4812     int WindowBase;
4813     int WindowScale;
4814
4815     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4816     ShuffleSourceInfo(SDValue Vec)
4817         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4818           WindowScale(1) {}
4819   };
4820
4821   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4822   // node.
4823   SmallVector<ShuffleSourceInfo, 2> Sources;
4824   for (unsigned i = 0; i < NumElts; ++i) {
4825     SDValue V = Op.getOperand(i);
4826     if (V.getOpcode() == ISD::UNDEF)
4827       continue;
4828     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4829       // A shuffle can only come from building a vector from various
4830       // elements of other vectors.
4831       return SDValue();
4832     }
4833
4834     // Add this element source to the list if it's not already there.
4835     SDValue SourceVec = V.getOperand(0);
4836     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4837     if (Source == Sources.end())
4838       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4839
4840     // Update the minimum and maximum lane number seen.
4841     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4842     Source->MinElt = std::min(Source->MinElt, EltNo);
4843     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4844   }
4845
4846   // Currently only do something sane when at most two source vectors
4847   // are involved.
4848   if (Sources.size() > 2)
4849     return SDValue();
4850
4851   // Find out the smallest element size among result and two sources, and use
4852   // it as element size to build the shuffle_vector.
4853   EVT SmallestEltTy = VT.getVectorElementType();
4854   for (auto &Source : Sources) {
4855     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4856     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4857       SmallestEltTy = SrcEltTy;
4858     }
4859   }
4860   unsigned ResMultiplier =
4861       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4862   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4863   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4864
4865   // If the source vector is too wide or too narrow, we may nevertheless be able
4866   // to construct a compatible shuffle either by concatenating it with UNDEF or
4867   // extracting a suitable range of elements.
4868   for (auto &Src : Sources) {
4869     EVT SrcVT = Src.ShuffleVec.getValueType();
4870
4871     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4872       continue;
4873
4874     // This stage of the search produces a source with the same element type as
4875     // the original, but with a total width matching the BUILD_VECTOR output.
4876     EVT EltVT = SrcVT.getVectorElementType();
4877     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4878     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4879
4880     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4881       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4882       // We can pad out the smaller vector for free, so if it's part of a
4883       // shuffle...
4884       Src.ShuffleVec =
4885           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4886                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4887       continue;
4888     }
4889
4890     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4891
4892     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4893       // Span too large for a VEXT to cope
4894       return SDValue();
4895     }
4896
4897     if (Src.MinElt >= NumSrcElts) {
4898       // The extraction can just take the second half
4899       Src.ShuffleVec =
4900           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4901                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4902       Src.WindowBase = -NumSrcElts;
4903     } else if (Src.MaxElt < NumSrcElts) {
4904       // The extraction can just take the first half
4905       Src.ShuffleVec =
4906           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4907                       DAG.getConstant(0, dl, MVT::i64));
4908     } else {
4909       // An actual VEXT is needed
4910       SDValue VEXTSrc1 =
4911           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4912                       DAG.getConstant(0, dl, MVT::i64));
4913       SDValue VEXTSrc2 =
4914           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4915                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4916       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4917
4918       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4919                                    VEXTSrc2,
4920                                    DAG.getConstant(Imm, dl, MVT::i32));
4921       Src.WindowBase = -Src.MinElt;
4922     }
4923   }
4924
4925   // Another possible incompatibility occurs from the vector element types. We
4926   // can fix this by bitcasting the source vectors to the same type we intend
4927   // for the shuffle.
4928   for (auto &Src : Sources) {
4929     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4930     if (SrcEltTy == SmallestEltTy)
4931       continue;
4932     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4933     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4934     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4935     Src.WindowBase *= Src.WindowScale;
4936   }
4937
4938   // Final sanity check before we try to actually produce a shuffle.
4939   DEBUG(
4940     for (auto Src : Sources)
4941       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4942   );
4943
4944   // The stars all align, our next step is to produce the mask for the shuffle.
4945   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4946   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4947   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4948     SDValue Entry = Op.getOperand(i);
4949     if (Entry.getOpcode() == ISD::UNDEF)
4950       continue;
4951
4952     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4953     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4954
4955     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4956     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4957     // segment.
4958     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4959     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4960                                VT.getVectorElementType().getSizeInBits());
4961     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4962
4963     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4964     // starting at the appropriate offset.
4965     int *LaneMask = &Mask[i * ResMultiplier];
4966
4967     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4968     ExtractBase += NumElts * (Src - Sources.begin());
4969     for (int j = 0; j < LanesDefined; ++j)
4970       LaneMask[j] = ExtractBase + j;
4971   }
4972
4973   // Final check before we try to produce nonsense...
4974   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4975     return SDValue();
4976
4977   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4978   for (unsigned i = 0; i < Sources.size(); ++i)
4979     ShuffleOps[i] = Sources[i].ShuffleVec;
4980
4981   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4982                                          ShuffleOps[1], &Mask[0]);
4983   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4984 }
4985
4986 // check if an EXT instruction can handle the shuffle mask when the
4987 // vector sources of the shuffle are the same.
4988 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4989   unsigned NumElts = VT.getVectorNumElements();
4990
4991   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4992   if (M[0] < 0)
4993     return false;
4994
4995   Imm = M[0];
4996
4997   // If this is a VEXT shuffle, the immediate value is the index of the first
4998   // element.  The other shuffle indices must be the successive elements after
4999   // the first one.
5000   unsigned ExpectedElt = Imm;
5001   for (unsigned i = 1; i < NumElts; ++i) {
5002     // Increment the expected index.  If it wraps around, just follow it
5003     // back to index zero and keep going.
5004     ++ExpectedElt;
5005     if (ExpectedElt == NumElts)
5006       ExpectedElt = 0;
5007
5008     if (M[i] < 0)
5009       continue; // ignore UNDEF indices
5010     if (ExpectedElt != static_cast<unsigned>(M[i]))
5011       return false;
5012   }
5013
5014   return true;
5015 }
5016
5017 // check if an EXT instruction can handle the shuffle mask when the
5018 // vector sources of the shuffle are different.
5019 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5020                       unsigned &Imm) {
5021   // Look for the first non-undef element.
5022   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5023       [](int Elt) {return Elt >= 0;});
5024
5025   // Benefit form APInt to handle overflow when calculating expected element.
5026   unsigned NumElts = VT.getVectorNumElements();
5027   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5028   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5029   // The following shuffle indices must be the successive elements after the
5030   // first real element.
5031   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5032       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5033   if (FirstWrongElt != M.end())
5034     return false;
5035
5036   // The index of an EXT is the first element if it is not UNDEF.
5037   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5038   // value of the first element.  E.g. 
5039   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5040   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5041   // ExpectedElt is the last mask index plus 1.
5042   Imm = ExpectedElt.getZExtValue();
5043
5044   // There are two difference cases requiring to reverse input vectors.
5045   // For example, for vector <4 x i32> we have the following cases,
5046   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5047   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5048   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5049   // to reverse two input vectors.
5050   if (Imm < NumElts)
5051     ReverseEXT = true;
5052   else
5053     Imm -= NumElts;
5054
5055   return true;
5056 }
5057
5058 /// isREVMask - Check if a vector shuffle corresponds to a REV
5059 /// instruction with the specified blocksize.  (The order of the elements
5060 /// within each block of the vector is reversed.)
5061 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5062   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5063          "Only possible block sizes for REV are: 16, 32, 64");
5064
5065   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5066   if (EltSz == 64)
5067     return false;
5068
5069   unsigned NumElts = VT.getVectorNumElements();
5070   unsigned BlockElts = M[0] + 1;
5071   // If the first shuffle index is UNDEF, be optimistic.
5072   if (M[0] < 0)
5073     BlockElts = BlockSize / EltSz;
5074
5075   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5076     return false;
5077
5078   for (unsigned i = 0; i < NumElts; ++i) {
5079     if (M[i] < 0)
5080       continue; // ignore UNDEF indices
5081     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5082       return false;
5083   }
5084
5085   return true;
5086 }
5087
5088 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5089   unsigned NumElts = VT.getVectorNumElements();
5090   WhichResult = (M[0] == 0 ? 0 : 1);
5091   unsigned Idx = WhichResult * NumElts / 2;
5092   for (unsigned i = 0; i != NumElts; i += 2) {
5093     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5094         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5095       return false;
5096     Idx += 1;
5097   }
5098
5099   return true;
5100 }
5101
5102 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5103   unsigned NumElts = VT.getVectorNumElements();
5104   WhichResult = (M[0] == 0 ? 0 : 1);
5105   for (unsigned i = 0; i != NumElts; ++i) {
5106     if (M[i] < 0)
5107       continue; // ignore UNDEF indices
5108     if ((unsigned)M[i] != 2 * i + WhichResult)
5109       return false;
5110   }
5111
5112   return true;
5113 }
5114
5115 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5116   unsigned NumElts = VT.getVectorNumElements();
5117   WhichResult = (M[0] == 0 ? 0 : 1);
5118   for (unsigned i = 0; i < NumElts; i += 2) {
5119     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5120         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5121       return false;
5122   }
5123   return true;
5124 }
5125
5126 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5127 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5128 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5129 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5130   unsigned NumElts = VT.getVectorNumElements();
5131   WhichResult = (M[0] == 0 ? 0 : 1);
5132   unsigned Idx = WhichResult * NumElts / 2;
5133   for (unsigned i = 0; i != NumElts; i += 2) {
5134     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5135         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5136       return false;
5137     Idx += 1;
5138   }
5139
5140   return true;
5141 }
5142
5143 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5144 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5145 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5146 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5147   unsigned Half = VT.getVectorNumElements() / 2;
5148   WhichResult = (M[0] == 0 ? 0 : 1);
5149   for (unsigned j = 0; j != 2; ++j) {
5150     unsigned Idx = WhichResult;
5151     for (unsigned i = 0; i != Half; ++i) {
5152       int MIdx = M[i + j * Half];
5153       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5154         return false;
5155       Idx += 2;
5156     }
5157   }
5158
5159   return true;
5160 }
5161
5162 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5163 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5164 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5165 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5166   unsigned NumElts = VT.getVectorNumElements();
5167   WhichResult = (M[0] == 0 ? 0 : 1);
5168   for (unsigned i = 0; i < NumElts; i += 2) {
5169     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5170         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5171       return false;
5172   }
5173   return true;
5174 }
5175
5176 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5177                       bool &DstIsLeft, int &Anomaly) {
5178   if (M.size() != static_cast<size_t>(NumInputElements))
5179     return false;
5180
5181   int NumLHSMatch = 0, NumRHSMatch = 0;
5182   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5183
5184   for (int i = 0; i < NumInputElements; ++i) {
5185     if (M[i] == -1) {
5186       ++NumLHSMatch;
5187       ++NumRHSMatch;
5188       continue;
5189     }
5190
5191     if (M[i] == i)
5192       ++NumLHSMatch;
5193     else
5194       LastLHSMismatch = i;
5195
5196     if (M[i] == i + NumInputElements)
5197       ++NumRHSMatch;
5198     else
5199       LastRHSMismatch = i;
5200   }
5201
5202   if (NumLHSMatch == NumInputElements - 1) {
5203     DstIsLeft = true;
5204     Anomaly = LastLHSMismatch;
5205     return true;
5206   } else if (NumRHSMatch == NumInputElements - 1) {
5207     DstIsLeft = false;
5208     Anomaly = LastRHSMismatch;
5209     return true;
5210   }
5211
5212   return false;
5213 }
5214
5215 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5216   if (VT.getSizeInBits() != 128)
5217     return false;
5218
5219   unsigned NumElts = VT.getVectorNumElements();
5220
5221   for (int I = 0, E = NumElts / 2; I != E; I++) {
5222     if (Mask[I] != I)
5223       return false;
5224   }
5225
5226   int Offset = NumElts / 2;
5227   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5228     if (Mask[I] != I + SplitLHS * Offset)
5229       return false;
5230   }
5231
5232   return true;
5233 }
5234
5235 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5236   SDLoc DL(Op);
5237   EVT VT = Op.getValueType();
5238   SDValue V0 = Op.getOperand(0);
5239   SDValue V1 = Op.getOperand(1);
5240   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5241
5242   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5243       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5244     return SDValue();
5245
5246   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5247
5248   if (!isConcatMask(Mask, VT, SplitV0))
5249     return SDValue();
5250
5251   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5252                                 VT.getVectorNumElements() / 2);
5253   if (SplitV0) {
5254     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5255                      DAG.getConstant(0, DL, MVT::i64));
5256   }
5257   if (V1.getValueType().getSizeInBits() == 128) {
5258     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5259                      DAG.getConstant(0, DL, MVT::i64));
5260   }
5261   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5262 }
5263
5264 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5265 /// the specified operations to build the shuffle.
5266 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5267                                       SDValue RHS, SelectionDAG &DAG,
5268                                       SDLoc dl) {
5269   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5270   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5271   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5272
5273   enum {
5274     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5275     OP_VREV,
5276     OP_VDUP0,
5277     OP_VDUP1,
5278     OP_VDUP2,
5279     OP_VDUP3,
5280     OP_VEXT1,
5281     OP_VEXT2,
5282     OP_VEXT3,
5283     OP_VUZPL, // VUZP, left result
5284     OP_VUZPR, // VUZP, right result
5285     OP_VZIPL, // VZIP, left result
5286     OP_VZIPR, // VZIP, right result
5287     OP_VTRNL, // VTRN, left result
5288     OP_VTRNR  // VTRN, right result
5289   };
5290
5291   if (OpNum == OP_COPY) {
5292     if (LHSID == (1 * 9 + 2) * 9 + 3)
5293       return LHS;
5294     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5295     return RHS;
5296   }
5297
5298   SDValue OpLHS, OpRHS;
5299   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5300   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5301   EVT VT = OpLHS.getValueType();
5302
5303   switch (OpNum) {
5304   default:
5305     llvm_unreachable("Unknown shuffle opcode!");
5306   case OP_VREV:
5307     // VREV divides the vector in half and swaps within the half.
5308     if (VT.getVectorElementType() == MVT::i32 ||
5309         VT.getVectorElementType() == MVT::f32)
5310       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5311     // vrev <4 x i16> -> REV32
5312     if (VT.getVectorElementType() == MVT::i16 ||
5313         VT.getVectorElementType() == MVT::f16)
5314       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5315     // vrev <4 x i8> -> REV16
5316     assert(VT.getVectorElementType() == MVT::i8);
5317     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5318   case OP_VDUP0:
5319   case OP_VDUP1:
5320   case OP_VDUP2:
5321   case OP_VDUP3: {
5322     EVT EltTy = VT.getVectorElementType();
5323     unsigned Opcode;
5324     if (EltTy == MVT::i8)
5325       Opcode = AArch64ISD::DUPLANE8;
5326     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5327       Opcode = AArch64ISD::DUPLANE16;
5328     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5329       Opcode = AArch64ISD::DUPLANE32;
5330     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5331       Opcode = AArch64ISD::DUPLANE64;
5332     else
5333       llvm_unreachable("Invalid vector element type?");
5334
5335     if (VT.getSizeInBits() == 64)
5336       OpLHS = WidenVector(OpLHS, DAG);
5337     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5338     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5339   }
5340   case OP_VEXT1:
5341   case OP_VEXT2:
5342   case OP_VEXT3: {
5343     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5344     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5345                        DAG.getConstant(Imm, dl, MVT::i32));
5346   }
5347   case OP_VUZPL:
5348     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5349                        OpRHS);
5350   case OP_VUZPR:
5351     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5352                        OpRHS);
5353   case OP_VZIPL:
5354     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5355                        OpRHS);
5356   case OP_VZIPR:
5357     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5358                        OpRHS);
5359   case OP_VTRNL:
5360     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5361                        OpRHS);
5362   case OP_VTRNR:
5363     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5364                        OpRHS);
5365   }
5366 }
5367
5368 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5369                            SelectionDAG &DAG) {
5370   // Check to see if we can use the TBL instruction.
5371   SDValue V1 = Op.getOperand(0);
5372   SDValue V2 = Op.getOperand(1);
5373   SDLoc DL(Op);
5374
5375   EVT EltVT = Op.getValueType().getVectorElementType();
5376   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5377
5378   SmallVector<SDValue, 8> TBLMask;
5379   for (int Val : ShuffleMask) {
5380     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5381       unsigned Offset = Byte + Val * BytesPerElt;
5382       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5383     }
5384   }
5385
5386   MVT IndexVT = MVT::v8i8;
5387   unsigned IndexLen = 8;
5388   if (Op.getValueType().getSizeInBits() == 128) {
5389     IndexVT = MVT::v16i8;
5390     IndexLen = 16;
5391   }
5392
5393   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5394   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5395
5396   SDValue Shuffle;
5397   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5398     if (IndexLen == 8)
5399       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5400     Shuffle = DAG.getNode(
5401         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5402         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5403         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5404                     makeArrayRef(TBLMask.data(), IndexLen)));
5405   } else {
5406     if (IndexLen == 8) {
5407       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5408       Shuffle = DAG.getNode(
5409           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5410           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5411           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5412                       makeArrayRef(TBLMask.data(), IndexLen)));
5413     } else {
5414       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5415       // cannot currently represent the register constraints on the input
5416       // table registers.
5417       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5418       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5419       //                               &TBLMask[0], IndexLen));
5420       Shuffle = DAG.getNode(
5421           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5422           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5423           V1Cst, V2Cst,
5424           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5425                       makeArrayRef(TBLMask.data(), IndexLen)));
5426     }
5427   }
5428   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5429 }
5430
5431 static unsigned getDUPLANEOp(EVT EltType) {
5432   if (EltType == MVT::i8)
5433     return AArch64ISD::DUPLANE8;
5434   if (EltType == MVT::i16 || EltType == MVT::f16)
5435     return AArch64ISD::DUPLANE16;
5436   if (EltType == MVT::i32 || EltType == MVT::f32)
5437     return AArch64ISD::DUPLANE32;
5438   if (EltType == MVT::i64 || EltType == MVT::f64)
5439     return AArch64ISD::DUPLANE64;
5440
5441   llvm_unreachable("Invalid vector element type?");
5442 }
5443
5444 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5445                                                    SelectionDAG &DAG) const {
5446   SDLoc dl(Op);
5447   EVT VT = Op.getValueType();
5448
5449   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5450
5451   // Convert shuffles that are directly supported on NEON to target-specific
5452   // DAG nodes, instead of keeping them as shuffles and matching them again
5453   // during code selection.  This is more efficient and avoids the possibility
5454   // of inconsistencies between legalization and selection.
5455   ArrayRef<int> ShuffleMask = SVN->getMask();
5456
5457   SDValue V1 = Op.getOperand(0);
5458   SDValue V2 = Op.getOperand(1);
5459
5460   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5461                                        V1.getValueType().getSimpleVT())) {
5462     int Lane = SVN->getSplatIndex();
5463     // If this is undef splat, generate it via "just" vdup, if possible.
5464     if (Lane == -1)
5465       Lane = 0;
5466
5467     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5468       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5469                          V1.getOperand(0));
5470     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5471     // constant. If so, we can just reference the lane's definition directly.
5472     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5473         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5474       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5475
5476     // Otherwise, duplicate from the lane of the input vector.
5477     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5478
5479     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5480     // to make a vector of the same size as this SHUFFLE. We can ignore the
5481     // extract entirely, and canonicalise the concat using WidenVector.
5482     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5483       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5484       V1 = V1.getOperand(0);
5485     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5486       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5487       Lane -= Idx * VT.getVectorNumElements() / 2;
5488       V1 = WidenVector(V1.getOperand(Idx), DAG);
5489     } else if (VT.getSizeInBits() == 64)
5490       V1 = WidenVector(V1, DAG);
5491
5492     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5493   }
5494
5495   if (isREVMask(ShuffleMask, VT, 64))
5496     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5497   if (isREVMask(ShuffleMask, VT, 32))
5498     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5499   if (isREVMask(ShuffleMask, VT, 16))
5500     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5501
5502   bool ReverseEXT = false;
5503   unsigned Imm;
5504   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5505     if (ReverseEXT)
5506       std::swap(V1, V2);
5507     Imm *= getExtFactor(V1);
5508     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5509                        DAG.getConstant(Imm, dl, MVT::i32));
5510   } else if (V2->getOpcode() == ISD::UNDEF &&
5511              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5512     Imm *= getExtFactor(V1);
5513     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5514                        DAG.getConstant(Imm, dl, MVT::i32));
5515   }
5516
5517   unsigned WhichResult;
5518   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5519     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5520     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5521   }
5522   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5523     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5524     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5525   }
5526   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5527     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5528     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5529   }
5530
5531   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5532     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5533     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5534   }
5535   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5536     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5537     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5538   }
5539   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5540     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5541     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5542   }
5543
5544   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5545   if (Concat.getNode())
5546     return Concat;
5547
5548   bool DstIsLeft;
5549   int Anomaly;
5550   int NumInputElements = V1.getValueType().getVectorNumElements();
5551   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5552     SDValue DstVec = DstIsLeft ? V1 : V2;
5553     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5554
5555     SDValue SrcVec = V1;
5556     int SrcLane = ShuffleMask[Anomaly];
5557     if (SrcLane >= NumInputElements) {
5558       SrcVec = V2;
5559       SrcLane -= VT.getVectorNumElements();
5560     }
5561     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5562
5563     EVT ScalarVT = VT.getVectorElementType();
5564
5565     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5566       ScalarVT = MVT::i32;
5567
5568     return DAG.getNode(
5569         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5570         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5571         DstLaneV);
5572   }
5573
5574   // If the shuffle is not directly supported and it has 4 elements, use
5575   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5576   unsigned NumElts = VT.getVectorNumElements();
5577   if (NumElts == 4) {
5578     unsigned PFIndexes[4];
5579     for (unsigned i = 0; i != 4; ++i) {
5580       if (ShuffleMask[i] < 0)
5581         PFIndexes[i] = 8;
5582       else
5583         PFIndexes[i] = ShuffleMask[i];
5584     }
5585
5586     // Compute the index in the perfect shuffle table.
5587     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5588                             PFIndexes[2] * 9 + PFIndexes[3];
5589     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5590     unsigned Cost = (PFEntry >> 30);
5591
5592     if (Cost <= 4)
5593       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5594   }
5595
5596   return GenerateTBL(Op, ShuffleMask, DAG);
5597 }
5598
5599 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5600                                APInt &UndefBits) {
5601   EVT VT = BVN->getValueType(0);
5602   APInt SplatBits, SplatUndef;
5603   unsigned SplatBitSize;
5604   bool HasAnyUndefs;
5605   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5606     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5607
5608     for (unsigned i = 0; i < NumSplats; ++i) {
5609       CnstBits <<= SplatBitSize;
5610       UndefBits <<= SplatBitSize;
5611       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5612       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5613     }
5614
5615     return true;
5616   }
5617
5618   return false;
5619 }
5620
5621 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5622                                               SelectionDAG &DAG) const {
5623   BuildVectorSDNode *BVN =
5624       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5625   SDValue LHS = Op.getOperand(0);
5626   SDLoc dl(Op);
5627   EVT VT = Op.getValueType();
5628
5629   if (!BVN)
5630     return Op;
5631
5632   APInt CnstBits(VT.getSizeInBits(), 0);
5633   APInt UndefBits(VT.getSizeInBits(), 0);
5634   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5635     // We only have BIC vector immediate instruction, which is and-not.
5636     CnstBits = ~CnstBits;
5637
5638     // We make use of a little bit of goto ickiness in order to avoid having to
5639     // duplicate the immediate matching logic for the undef toggled case.
5640     bool SecondTry = false;
5641   AttemptModImm:
5642
5643     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5644       CnstBits = CnstBits.zextOrTrunc(64);
5645       uint64_t CnstVal = CnstBits.getZExtValue();
5646
5647       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5648         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5649         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5650         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5651                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5652                                   DAG.getConstant(0, dl, MVT::i32));
5653         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5654       }
5655
5656       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5657         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5658         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5659         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5660                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5661                                   DAG.getConstant(8, dl, MVT::i32));
5662         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5663       }
5664
5665       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5666         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5667         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5668         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5669                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5670                                   DAG.getConstant(16, dl, MVT::i32));
5671         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5672       }
5673
5674       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5675         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5676         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5677         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5678                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5679                                   DAG.getConstant(24, dl, MVT::i32));
5680         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5681       }
5682
5683       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5684         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5685         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5686         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5687                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5688                                   DAG.getConstant(0, dl, MVT::i32));
5689         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5690       }
5691
5692       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5693         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5694         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5695         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5696                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5697                                   DAG.getConstant(8, dl, MVT::i32));
5698         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5699       }
5700     }
5701
5702     if (SecondTry)
5703       goto FailedModImm;
5704     SecondTry = true;
5705     CnstBits = ~UndefBits;
5706     goto AttemptModImm;
5707   }
5708
5709 // We can always fall back to a non-immediate AND.
5710 FailedModImm:
5711   return Op;
5712 }
5713
5714 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5715 // consists of only the same constant int value, returned in reference arg
5716 // ConstVal
5717 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5718                                      uint64_t &ConstVal) {
5719   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5720   if (!Bvec)
5721     return false;
5722   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5723   if (!FirstElt)
5724     return false;
5725   EVT VT = Bvec->getValueType(0);
5726   unsigned NumElts = VT.getVectorNumElements();
5727   for (unsigned i = 1; i < NumElts; ++i)
5728     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5729       return false;
5730   ConstVal = FirstElt->getZExtValue();
5731   return true;
5732 }
5733
5734 static unsigned getIntrinsicID(const SDNode *N) {
5735   unsigned Opcode = N->getOpcode();
5736   switch (Opcode) {
5737   default:
5738     return Intrinsic::not_intrinsic;
5739   case ISD::INTRINSIC_WO_CHAIN: {
5740     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5741     if (IID < Intrinsic::num_intrinsics)
5742       return IID;
5743     return Intrinsic::not_intrinsic;
5744   }
5745   }
5746 }
5747
5748 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5749 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5750 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5751 // Also, logical shift right -> sri, with the same structure.
5752 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5753   EVT VT = N->getValueType(0);
5754
5755   if (!VT.isVector())
5756     return SDValue();
5757
5758   SDLoc DL(N);
5759
5760   // Is the first op an AND?
5761   const SDValue And = N->getOperand(0);
5762   if (And.getOpcode() != ISD::AND)
5763     return SDValue();
5764
5765   // Is the second op an shl or lshr?
5766   SDValue Shift = N->getOperand(1);
5767   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5768   // or AArch64ISD::VLSHR vector, #shift
5769   unsigned ShiftOpc = Shift.getOpcode();
5770   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5771     return SDValue();
5772   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5773
5774   // Is the shift amount constant?
5775   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5776   if (!C2node)
5777     return SDValue();
5778
5779   // Is the and mask vector all constant?
5780   uint64_t C1;
5781   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5782     return SDValue();
5783
5784   // Is C1 == ~C2, taking into account how much one can shift elements of a
5785   // particular size?
5786   uint64_t C2 = C2node->getZExtValue();
5787   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5788   if (C2 > ElemSizeInBits)
5789     return SDValue();
5790   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5791   if ((C1 & ElemMask) != (~C2 & ElemMask))
5792     return SDValue();
5793
5794   SDValue X = And.getOperand(0);
5795   SDValue Y = Shift.getOperand(0);
5796
5797   unsigned Intrin =
5798       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5799   SDValue ResultSLI =
5800       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5801                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5802                   Shift.getOperand(1));
5803
5804   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5805   DEBUG(N->dump(&DAG));
5806   DEBUG(dbgs() << "into: \n");
5807   DEBUG(ResultSLI->dump(&DAG));
5808
5809   ++NumShiftInserts;
5810   return ResultSLI;
5811 }
5812
5813 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5814                                              SelectionDAG &DAG) const {
5815   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5816   if (EnableAArch64SlrGeneration) {
5817     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5818     if (Res.getNode())
5819       return Res;
5820   }
5821
5822   BuildVectorSDNode *BVN =
5823       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5824   SDValue LHS = Op.getOperand(1);
5825   SDLoc dl(Op);
5826   EVT VT = Op.getValueType();
5827
5828   // OR commutes, so try swapping the operands.
5829   if (!BVN) {
5830     LHS = Op.getOperand(0);
5831     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5832   }
5833   if (!BVN)
5834     return Op;
5835
5836   APInt CnstBits(VT.getSizeInBits(), 0);
5837   APInt UndefBits(VT.getSizeInBits(), 0);
5838   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5839     // We make use of a little bit of goto ickiness in order to avoid having to
5840     // duplicate the immediate matching logic for the undef toggled case.
5841     bool SecondTry = false;
5842   AttemptModImm:
5843
5844     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5845       CnstBits = CnstBits.zextOrTrunc(64);
5846       uint64_t CnstVal = CnstBits.getZExtValue();
5847
5848       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5849         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5850         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5851         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5852                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5853                                   DAG.getConstant(0, dl, MVT::i32));
5854         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5855       }
5856
5857       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5858         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5859         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5860         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5861                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5862                                   DAG.getConstant(8, dl, MVT::i32));
5863         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5864       }
5865
5866       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5867         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5868         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5869         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5870                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5871                                   DAG.getConstant(16, dl, MVT::i32));
5872         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5873       }
5874
5875       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5876         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5877         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5878         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5879                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5880                                   DAG.getConstant(24, dl, MVT::i32));
5881         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5882       }
5883
5884       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5885         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5886         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5887         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5888                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5889                                   DAG.getConstant(0, dl, MVT::i32));
5890         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5891       }
5892
5893       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5894         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5895         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5896         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5897                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5898                                   DAG.getConstant(8, dl, MVT::i32));
5899         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5900       }
5901     }
5902
5903     if (SecondTry)
5904       goto FailedModImm;
5905     SecondTry = true;
5906     CnstBits = UndefBits;
5907     goto AttemptModImm;
5908   }
5909
5910 // We can always fall back to a non-immediate OR.
5911 FailedModImm:
5912   return Op;
5913 }
5914
5915 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5916 // be truncated to fit element width.
5917 static SDValue NormalizeBuildVector(SDValue Op,
5918                                     SelectionDAG &DAG) {
5919   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5920   SDLoc dl(Op);
5921   EVT VT = Op.getValueType();
5922   EVT EltTy= VT.getVectorElementType();
5923
5924   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5925     return Op;
5926
5927   SmallVector<SDValue, 16> Ops;
5928   for (SDValue Lane : Op->ops()) {
5929     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5930       APInt LowBits(EltTy.getSizeInBits(),
5931                     CstLane->getZExtValue());
5932       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5933     }
5934     Ops.push_back(Lane);
5935   }
5936   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5937 }
5938
5939 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5940                                                  SelectionDAG &DAG) const {
5941   SDLoc dl(Op);
5942   EVT VT = Op.getValueType();
5943   Op = NormalizeBuildVector(Op, DAG);
5944   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5945
5946   APInt CnstBits(VT.getSizeInBits(), 0);
5947   APInt UndefBits(VT.getSizeInBits(), 0);
5948   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5949     // We make use of a little bit of goto ickiness in order to avoid having to
5950     // duplicate the immediate matching logic for the undef toggled case.
5951     bool SecondTry = false;
5952   AttemptModImm:
5953
5954     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5955       CnstBits = CnstBits.zextOrTrunc(64);
5956       uint64_t CnstVal = CnstBits.getZExtValue();
5957
5958       // Certain magic vector constants (used to express things like NOT
5959       // and NEG) are passed through unmodified.  This allows codegen patterns
5960       // for these operations to match.  Special-purpose patterns will lower
5961       // these immediates to MOVIs if it proves necessary.
5962       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5963         return Op;
5964
5965       // The many faces of MOVI...
5966       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5967         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5968         if (VT.getSizeInBits() == 128) {
5969           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5970                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5971           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5972         }
5973
5974         // Support the V64 version via subregister insertion.
5975         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5976                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5977         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5978       }
5979
5980       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5981         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5982         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5983         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5984                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5985                                   DAG.getConstant(0, dl, MVT::i32));
5986         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5987       }
5988
5989       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5990         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5991         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5992         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5993                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5994                                   DAG.getConstant(8, dl, MVT::i32));
5995         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5996       }
5997
5998       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5999         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6000         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6001         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6002                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6003                                   DAG.getConstant(16, dl, MVT::i32));
6004         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6005       }
6006
6007       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6008         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6009         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6010         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6011                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6012                                   DAG.getConstant(24, dl, MVT::i32));
6013         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6014       }
6015
6016       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6017         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6018         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6019         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6020                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6021                                   DAG.getConstant(0, dl, MVT::i32));
6022         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6023       }
6024
6025       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6026         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6027         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6028         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6029                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6030                                   DAG.getConstant(8, dl, MVT::i32));
6031         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6032       }
6033
6034       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6035         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6036         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6037         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6038                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6039                                   DAG.getConstant(264, dl, MVT::i32));
6040         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6041       }
6042
6043       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6044         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6045         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6046         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6047                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6048                                   DAG.getConstant(272, dl, MVT::i32));
6049         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6050       }
6051
6052       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6053         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6054         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6055         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6056                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6057         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6058       }
6059
6060       // The few faces of FMOV...
6061       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6062         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6063         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6064         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6065                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6066         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6067       }
6068
6069       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6070           VT.getSizeInBits() == 128) {
6071         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6072         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6073                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6074         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6075       }
6076
6077       // The many faces of MVNI...
6078       CnstVal = ~CnstVal;
6079       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6080         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6081         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6082         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6083                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6084                                   DAG.getConstant(0, dl, MVT::i32));
6085         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6086       }
6087
6088       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6089         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6090         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6091         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6092                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6093                                   DAG.getConstant(8, dl, MVT::i32));
6094         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6095       }
6096
6097       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6098         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6099         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6100         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6101                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6102                                   DAG.getConstant(16, dl, MVT::i32));
6103         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6104       }
6105
6106       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6107         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6108         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6109         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6110                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6111                                   DAG.getConstant(24, dl, MVT::i32));
6112         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6113       }
6114
6115       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6116         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6117         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6118         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6119                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6120                                   DAG.getConstant(0, dl, MVT::i32));
6121         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6122       }
6123
6124       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6125         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6126         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6127         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6128                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6129                                   DAG.getConstant(8, dl, MVT::i32));
6130         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6131       }
6132
6133       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6134         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6135         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6136         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6137                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6138                                   DAG.getConstant(264, dl, MVT::i32));
6139         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6140       }
6141
6142       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6143         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6144         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6145         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6146                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6147                                   DAG.getConstant(272, dl, MVT::i32));
6148         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6149       }
6150     }
6151
6152     if (SecondTry)
6153       goto FailedModImm;
6154     SecondTry = true;
6155     CnstBits = UndefBits;
6156     goto AttemptModImm;
6157   }
6158 FailedModImm:
6159
6160   // Scan through the operands to find some interesting properties we can
6161   // exploit:
6162   //   1) If only one value is used, we can use a DUP, or
6163   //   2) if only the low element is not undef, we can just insert that, or
6164   //   3) if only one constant value is used (w/ some non-constant lanes),
6165   //      we can splat the constant value into the whole vector then fill
6166   //      in the non-constant lanes.
6167   //   4) FIXME: If different constant values are used, but we can intelligently
6168   //             select the values we'll be overwriting for the non-constant
6169   //             lanes such that we can directly materialize the vector
6170   //             some other way (MOVI, e.g.), we can be sneaky.
6171   unsigned NumElts = VT.getVectorNumElements();
6172   bool isOnlyLowElement = true;
6173   bool usesOnlyOneValue = true;
6174   bool usesOnlyOneConstantValue = true;
6175   bool isConstant = true;
6176   unsigned NumConstantLanes = 0;
6177   SDValue Value;
6178   SDValue ConstantValue;
6179   for (unsigned i = 0; i < NumElts; ++i) {
6180     SDValue V = Op.getOperand(i);
6181     if (V.getOpcode() == ISD::UNDEF)
6182       continue;
6183     if (i > 0)
6184       isOnlyLowElement = false;
6185     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6186       isConstant = false;
6187
6188     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6189       ++NumConstantLanes;
6190       if (!ConstantValue.getNode())
6191         ConstantValue = V;
6192       else if (ConstantValue != V)
6193         usesOnlyOneConstantValue = false;
6194     }
6195
6196     if (!Value.getNode())
6197       Value = V;
6198     else if (V != Value)
6199       usesOnlyOneValue = false;
6200   }
6201
6202   if (!Value.getNode())
6203     return DAG.getUNDEF(VT);
6204
6205   if (isOnlyLowElement)
6206     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6207
6208   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6209   // i32 and try again.
6210   if (usesOnlyOneValue) {
6211     if (!isConstant) {
6212       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6213           Value.getValueType() != VT)
6214         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6215
6216       // This is actually a DUPLANExx operation, which keeps everything vectory.
6217
6218       // DUPLANE works on 128-bit vectors, widen it if necessary.
6219       SDValue Lane = Value.getOperand(1);
6220       Value = Value.getOperand(0);
6221       if (Value.getValueType().getSizeInBits() == 64)
6222         Value = WidenVector(Value, DAG);
6223
6224       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6225       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6226     }
6227
6228     if (VT.getVectorElementType().isFloatingPoint()) {
6229       SmallVector<SDValue, 8> Ops;
6230       EVT EltTy = VT.getVectorElementType();
6231       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6232               "Unsupported floating-point vector type");
6233       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6234       for (unsigned i = 0; i < NumElts; ++i)
6235         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6236       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6237       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6238       Val = LowerBUILD_VECTOR(Val, DAG);
6239       if (Val.getNode())
6240         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6241     }
6242   }
6243
6244   // If there was only one constant value used and for more than one lane,
6245   // start by splatting that value, then replace the non-constant lanes. This
6246   // is better than the default, which will perform a separate initialization
6247   // for each lane.
6248   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6249     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6250     // Now insert the non-constant lanes.
6251     for (unsigned i = 0; i < NumElts; ++i) {
6252       SDValue V = Op.getOperand(i);
6253       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6254       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6255         // Note that type legalization likely mucked about with the VT of the
6256         // source operand, so we may have to convert it here before inserting.
6257         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6258       }
6259     }
6260     return Val;
6261   }
6262
6263   // If all elements are constants and the case above didn't get hit, fall back
6264   // to the default expansion, which will generate a load from the constant
6265   // pool.
6266   if (isConstant)
6267     return SDValue();
6268
6269   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6270   if (NumElts >= 4) {
6271     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6272       return shuffle;
6273   }
6274
6275   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6276   // know the default expansion would otherwise fall back on something even
6277   // worse. For a vector with one or two non-undef values, that's
6278   // scalar_to_vector for the elements followed by a shuffle (provided the
6279   // shuffle is valid for the target) and materialization element by element
6280   // on the stack followed by a load for everything else.
6281   if (!isConstant && !usesOnlyOneValue) {
6282     SDValue Vec = DAG.getUNDEF(VT);
6283     SDValue Op0 = Op.getOperand(0);
6284     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6285     unsigned i = 0;
6286     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6287     // a) Avoid a RMW dependency on the full vector register, and
6288     // b) Allow the register coalescer to fold away the copy if the
6289     //    value is already in an S or D register.
6290     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6291     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6292     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6293         (ElemSize == 32 || ElemSize == 64)) {
6294       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6295       MachineSDNode *N =
6296           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6297                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6298       Vec = SDValue(N, 0);
6299       ++i;
6300     }
6301     for (; i < NumElts; ++i) {
6302       SDValue V = Op.getOperand(i);
6303       if (V.getOpcode() == ISD::UNDEF)
6304         continue;
6305       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6306       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6307     }
6308     return Vec;
6309   }
6310
6311   // Just use the default expansion. We failed to find a better alternative.
6312   return SDValue();
6313 }
6314
6315 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6316                                                       SelectionDAG &DAG) const {
6317   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6318
6319   // Check for non-constant or out of range lane.
6320   EVT VT = Op.getOperand(0).getValueType();
6321   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6322   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6323     return SDValue();
6324
6325
6326   // Insertion/extraction are legal for V128 types.
6327   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6328       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6329       VT == MVT::v8f16)
6330     return Op;
6331
6332   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6333       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6334     return SDValue();
6335
6336   // For V64 types, we perform insertion by expanding the value
6337   // to a V128 type and perform the insertion on that.
6338   SDLoc DL(Op);
6339   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6340   EVT WideTy = WideVec.getValueType();
6341
6342   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6343                              Op.getOperand(1), Op.getOperand(2));
6344   // Re-narrow the resultant vector.
6345   return NarrowVector(Node, DAG);
6346 }
6347
6348 SDValue
6349 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6350                                                SelectionDAG &DAG) const {
6351   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6352
6353   // Check for non-constant or out of range lane.
6354   EVT VT = Op.getOperand(0).getValueType();
6355   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6356   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6357     return SDValue();
6358
6359
6360   // Insertion/extraction are legal for V128 types.
6361   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6362       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6363       VT == MVT::v8f16)
6364     return Op;
6365
6366   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6367       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6368     return SDValue();
6369
6370   // For V64 types, we perform extraction by expanding the value
6371   // to a V128 type and perform the extraction on that.
6372   SDLoc DL(Op);
6373   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6374   EVT WideTy = WideVec.getValueType();
6375
6376   EVT ExtrTy = WideTy.getVectorElementType();
6377   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6378     ExtrTy = MVT::i32;
6379
6380   // For extractions, we just return the result directly.
6381   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6382                      Op.getOperand(1));
6383 }
6384
6385 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6386                                                       SelectionDAG &DAG) const {
6387   EVT VT = Op.getOperand(0).getValueType();
6388   SDLoc dl(Op);
6389   // Just in case...
6390   if (!VT.isVector())
6391     return SDValue();
6392
6393   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6394   if (!Cst)
6395     return SDValue();
6396   unsigned Val = Cst->getZExtValue();
6397
6398   unsigned Size = Op.getValueType().getSizeInBits();
6399   if (Val == 0) {
6400     switch (Size) {
6401     case 8:
6402       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6403                                         Op.getOperand(0));
6404     case 16:
6405       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6406                                         Op.getOperand(0));
6407     case 32:
6408       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6409                                         Op.getOperand(0));
6410     case 64:
6411       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6412                                         Op.getOperand(0));
6413     default:
6414       llvm_unreachable("Unexpected vector type in extract_subvector!");
6415     }
6416   }
6417   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6418   // that directly.
6419   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6420     return Op;
6421
6422   return SDValue();
6423 }
6424
6425 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6426                                                EVT VT) const {
6427   if (VT.getVectorNumElements() == 4 &&
6428       (VT.is128BitVector() || VT.is64BitVector())) {
6429     unsigned PFIndexes[4];
6430     for (unsigned i = 0; i != 4; ++i) {
6431       if (M[i] < 0)
6432         PFIndexes[i] = 8;
6433       else
6434         PFIndexes[i] = M[i];
6435     }
6436
6437     // Compute the index in the perfect shuffle table.
6438     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6439                             PFIndexes[2] * 9 + PFIndexes[3];
6440     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6441     unsigned Cost = (PFEntry >> 30);
6442
6443     if (Cost <= 4)
6444       return true;
6445   }
6446
6447   bool DummyBool;
6448   int DummyInt;
6449   unsigned DummyUnsigned;
6450
6451   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6452           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6453           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6454           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6455           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6456           isZIPMask(M, VT, DummyUnsigned) ||
6457           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6458           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6459           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6460           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6461           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6462 }
6463
6464 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6465 /// operand of a vector shift operation, where all the elements of the
6466 /// build_vector must have the same constant integer value.
6467 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6468   // Ignore bit_converts.
6469   while (Op.getOpcode() == ISD::BITCAST)
6470     Op = Op.getOperand(0);
6471   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6472   APInt SplatBits, SplatUndef;
6473   unsigned SplatBitSize;
6474   bool HasAnyUndefs;
6475   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6476                                     HasAnyUndefs, ElementBits) ||
6477       SplatBitSize > ElementBits)
6478     return false;
6479   Cnt = SplatBits.getSExtValue();
6480   return true;
6481 }
6482
6483 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6484 /// operand of a vector shift left operation.  That value must be in the range:
6485 ///   0 <= Value < ElementBits for a left shift; or
6486 ///   0 <= Value <= ElementBits for a long left shift.
6487 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6488   assert(VT.isVector() && "vector shift count is not a vector type");
6489   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6490   if (!getVShiftImm(Op, ElementBits, Cnt))
6491     return false;
6492   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6493 }
6494
6495 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6496 /// operand of a vector shift right operation. The value must be in the range:
6497 ///   1 <= Value <= ElementBits for a right shift; or
6498 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6499   assert(VT.isVector() && "vector shift count is not a vector type");
6500   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6501   if (!getVShiftImm(Op, ElementBits, Cnt))
6502     return false;
6503   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6504 }
6505
6506 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6507                                                       SelectionDAG &DAG) const {
6508   EVT VT = Op.getValueType();
6509   SDLoc DL(Op);
6510   int64_t Cnt;
6511
6512   if (!Op.getOperand(1).getValueType().isVector())
6513     return Op;
6514   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6515
6516   switch (Op.getOpcode()) {
6517   default:
6518     llvm_unreachable("unexpected shift opcode");
6519
6520   case ISD::SHL:
6521     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6522       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6523                          DAG.getConstant(Cnt, DL, MVT::i32));
6524     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6525                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6526                                        MVT::i32),
6527                        Op.getOperand(0), Op.getOperand(1));
6528   case ISD::SRA:
6529   case ISD::SRL:
6530     // Right shift immediate
6531     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6532       unsigned Opc =
6533           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6534       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6535                          DAG.getConstant(Cnt, DL, MVT::i32));
6536     }
6537
6538     // Right shift register.  Note, there is not a shift right register
6539     // instruction, but the shift left register instruction takes a signed
6540     // value, where negative numbers specify a right shift.
6541     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6542                                                 : Intrinsic::aarch64_neon_ushl;
6543     // negate the shift amount
6544     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6545     SDValue NegShiftLeft =
6546         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6547                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6548                     NegShift);
6549     return NegShiftLeft;
6550   }
6551
6552   return SDValue();
6553 }
6554
6555 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6556                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6557                                     SDLoc dl, SelectionDAG &DAG) {
6558   EVT SrcVT = LHS.getValueType();
6559   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6560          "function only supposed to emit natural comparisons");
6561
6562   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6563   APInt CnstBits(VT.getSizeInBits(), 0);
6564   APInt UndefBits(VT.getSizeInBits(), 0);
6565   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6566   bool IsZero = IsCnst && (CnstBits == 0);
6567
6568   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6569     switch (CC) {
6570     default:
6571       return SDValue();
6572     case AArch64CC::NE: {
6573       SDValue Fcmeq;
6574       if (IsZero)
6575         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6576       else
6577         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6578       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6579     }
6580     case AArch64CC::EQ:
6581       if (IsZero)
6582         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6583       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6584     case AArch64CC::GE:
6585       if (IsZero)
6586         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6587       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6588     case AArch64CC::GT:
6589       if (IsZero)
6590         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6591       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6592     case AArch64CC::LS:
6593       if (IsZero)
6594         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6595       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6596     case AArch64CC::LT:
6597       if (!NoNans)
6598         return SDValue();
6599     // If we ignore NaNs then we can use to the MI implementation.
6600     // Fallthrough.
6601     case AArch64CC::MI:
6602       if (IsZero)
6603         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6604       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6605     }
6606   }
6607
6608   switch (CC) {
6609   default:
6610     return SDValue();
6611   case AArch64CC::NE: {
6612     SDValue Cmeq;
6613     if (IsZero)
6614       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6615     else
6616       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6617     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6618   }
6619   case AArch64CC::EQ:
6620     if (IsZero)
6621       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6622     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6623   case AArch64CC::GE:
6624     if (IsZero)
6625       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6626     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6627   case AArch64CC::GT:
6628     if (IsZero)
6629       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6630     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6631   case AArch64CC::LE:
6632     if (IsZero)
6633       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6634     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6635   case AArch64CC::LS:
6636     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6637   case AArch64CC::LO:
6638     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6639   case AArch64CC::LT:
6640     if (IsZero)
6641       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6642     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6643   case AArch64CC::HI:
6644     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6645   case AArch64CC::HS:
6646     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6647   }
6648 }
6649
6650 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6651                                            SelectionDAG &DAG) const {
6652   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6653   SDValue LHS = Op.getOperand(0);
6654   SDValue RHS = Op.getOperand(1);
6655   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6656   SDLoc dl(Op);
6657
6658   if (LHS.getValueType().getVectorElementType().isInteger()) {
6659     assert(LHS.getValueType() == RHS.getValueType());
6660     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6661     SDValue Cmp =
6662         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6663     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6664   }
6665
6666   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6667          LHS.getValueType().getVectorElementType() == MVT::f64);
6668
6669   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6670   // clean.  Some of them require two branches to implement.
6671   AArch64CC::CondCode CC1, CC2;
6672   bool ShouldInvert;
6673   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6674
6675   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6676   SDValue Cmp =
6677       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6678   if (!Cmp.getNode())
6679     return SDValue();
6680
6681   if (CC2 != AArch64CC::AL) {
6682     SDValue Cmp2 =
6683         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6684     if (!Cmp2.getNode())
6685       return SDValue();
6686
6687     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6688   }
6689
6690   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6691
6692   if (ShouldInvert)
6693     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6694
6695   return Cmp;
6696 }
6697
6698 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6699 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6700 /// specified in the intrinsic calls.
6701 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6702                                                const CallInst &I,
6703                                                unsigned Intrinsic) const {
6704   auto &DL = I.getModule()->getDataLayout();
6705   switch (Intrinsic) {
6706   case Intrinsic::aarch64_neon_ld2:
6707   case Intrinsic::aarch64_neon_ld3:
6708   case Intrinsic::aarch64_neon_ld4:
6709   case Intrinsic::aarch64_neon_ld1x2:
6710   case Intrinsic::aarch64_neon_ld1x3:
6711   case Intrinsic::aarch64_neon_ld1x4:
6712   case Intrinsic::aarch64_neon_ld2lane:
6713   case Intrinsic::aarch64_neon_ld3lane:
6714   case Intrinsic::aarch64_neon_ld4lane:
6715   case Intrinsic::aarch64_neon_ld2r:
6716   case Intrinsic::aarch64_neon_ld3r:
6717   case Intrinsic::aarch64_neon_ld4r: {
6718     Info.opc = ISD::INTRINSIC_W_CHAIN;
6719     // Conservatively set memVT to the entire set of vectors loaded.
6720     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6721     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6722     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6723     Info.offset = 0;
6724     Info.align = 0;
6725     Info.vol = false; // volatile loads with NEON intrinsics not supported
6726     Info.readMem = true;
6727     Info.writeMem = false;
6728     return true;
6729   }
6730   case Intrinsic::aarch64_neon_st2:
6731   case Intrinsic::aarch64_neon_st3:
6732   case Intrinsic::aarch64_neon_st4:
6733   case Intrinsic::aarch64_neon_st1x2:
6734   case Intrinsic::aarch64_neon_st1x3:
6735   case Intrinsic::aarch64_neon_st1x4:
6736   case Intrinsic::aarch64_neon_st2lane:
6737   case Intrinsic::aarch64_neon_st3lane:
6738   case Intrinsic::aarch64_neon_st4lane: {
6739     Info.opc = ISD::INTRINSIC_VOID;
6740     // Conservatively set memVT to the entire set of vectors stored.
6741     unsigned NumElts = 0;
6742     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6743       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6744       if (!ArgTy->isVectorTy())
6745         break;
6746       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6747     }
6748     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6749     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6750     Info.offset = 0;
6751     Info.align = 0;
6752     Info.vol = false; // volatile stores with NEON intrinsics not supported
6753     Info.readMem = false;
6754     Info.writeMem = true;
6755     return true;
6756   }
6757   case Intrinsic::aarch64_ldaxr:
6758   case Intrinsic::aarch64_ldxr: {
6759     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6760     Info.opc = ISD::INTRINSIC_W_CHAIN;
6761     Info.memVT = MVT::getVT(PtrTy->getElementType());
6762     Info.ptrVal = I.getArgOperand(0);
6763     Info.offset = 0;
6764     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6765     Info.vol = true;
6766     Info.readMem = true;
6767     Info.writeMem = false;
6768     return true;
6769   }
6770   case Intrinsic::aarch64_stlxr:
6771   case Intrinsic::aarch64_stxr: {
6772     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6773     Info.opc = ISD::INTRINSIC_W_CHAIN;
6774     Info.memVT = MVT::getVT(PtrTy->getElementType());
6775     Info.ptrVal = I.getArgOperand(1);
6776     Info.offset = 0;
6777     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6778     Info.vol = true;
6779     Info.readMem = false;
6780     Info.writeMem = true;
6781     return true;
6782   }
6783   case Intrinsic::aarch64_ldaxp:
6784   case Intrinsic::aarch64_ldxp: {
6785     Info.opc = ISD::INTRINSIC_W_CHAIN;
6786     Info.memVT = MVT::i128;
6787     Info.ptrVal = I.getArgOperand(0);
6788     Info.offset = 0;
6789     Info.align = 16;
6790     Info.vol = true;
6791     Info.readMem = true;
6792     Info.writeMem = false;
6793     return true;
6794   }
6795   case Intrinsic::aarch64_stlxp:
6796   case Intrinsic::aarch64_stxp: {
6797     Info.opc = ISD::INTRINSIC_W_CHAIN;
6798     Info.memVT = MVT::i128;
6799     Info.ptrVal = I.getArgOperand(2);
6800     Info.offset = 0;
6801     Info.align = 16;
6802     Info.vol = true;
6803     Info.readMem = false;
6804     Info.writeMem = true;
6805     return true;
6806   }
6807   default:
6808     break;
6809   }
6810
6811   return false;
6812 }
6813
6814 // Truncations from 64-bit GPR to 32-bit GPR is free.
6815 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6816   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6817     return false;
6818   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6819   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6820   return NumBits1 > NumBits2;
6821 }
6822 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6823   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6824     return false;
6825   unsigned NumBits1 = VT1.getSizeInBits();
6826   unsigned NumBits2 = VT2.getSizeInBits();
6827   return NumBits1 > NumBits2;
6828 }
6829
6830 /// Check if it is profitable to hoist instruction in then/else to if.
6831 /// Not profitable if I and it's user can form a FMA instruction
6832 /// because we prefer FMSUB/FMADD.
6833 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6834   if (I->getOpcode() != Instruction::FMul)
6835     return true;
6836
6837   if (I->getNumUses() != 1)
6838     return true;
6839
6840   Instruction *User = I->user_back();
6841
6842   if (User &&
6843       !(User->getOpcode() == Instruction::FSub ||
6844         User->getOpcode() == Instruction::FAdd))
6845     return true;
6846
6847   const TargetOptions &Options = getTargetMachine().Options;
6848   const DataLayout &DL = I->getModule()->getDataLayout();
6849   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6850
6851   if (isFMAFasterThanFMulAndFAdd(VT) &&
6852       isOperationLegalOrCustom(ISD::FMA, VT) &&
6853       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6854     return false;
6855
6856   return true;
6857 }
6858
6859 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6860 // 64-bit GPR.
6861 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6862   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6863     return false;
6864   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6865   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6866   return NumBits1 == 32 && NumBits2 == 64;
6867 }
6868 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6869   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6870     return false;
6871   unsigned NumBits1 = VT1.getSizeInBits();
6872   unsigned NumBits2 = VT2.getSizeInBits();
6873   return NumBits1 == 32 && NumBits2 == 64;
6874 }
6875
6876 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6877   EVT VT1 = Val.getValueType();
6878   if (isZExtFree(VT1, VT2)) {
6879     return true;
6880   }
6881
6882   if (Val.getOpcode() != ISD::LOAD)
6883     return false;
6884
6885   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6886   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6887           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6888           VT1.getSizeInBits() <= 32);
6889 }
6890
6891 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6892   if (isa<FPExtInst>(Ext))
6893     return false;
6894
6895   // Vector types are next free.
6896   if (Ext->getType()->isVectorTy())
6897     return false;
6898
6899   for (const Use &U : Ext->uses()) {
6900     // The extension is free if we can fold it with a left shift in an
6901     // addressing mode or an arithmetic operation: add, sub, and cmp.
6902
6903     // Is there a shift?
6904     const Instruction *Instr = cast<Instruction>(U.getUser());
6905
6906     // Is this a constant shift?
6907     switch (Instr->getOpcode()) {
6908     case Instruction::Shl:
6909       if (!isa<ConstantInt>(Instr->getOperand(1)))
6910         return false;
6911       break;
6912     case Instruction::GetElementPtr: {
6913       gep_type_iterator GTI = gep_type_begin(Instr);
6914       auto &DL = Ext->getModule()->getDataLayout();
6915       std::advance(GTI, U.getOperandNo());
6916       Type *IdxTy = *GTI;
6917       // This extension will end up with a shift because of the scaling factor.
6918       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6919       // Get the shift amount based on the scaling factor:
6920       // log2(sizeof(IdxTy)) - log2(8).
6921       uint64_t ShiftAmt =
6922           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6923       // Is the constant foldable in the shift of the addressing mode?
6924       // I.e., shift amount is between 1 and 4 inclusive.
6925       if (ShiftAmt == 0 || ShiftAmt > 4)
6926         return false;
6927       break;
6928     }
6929     case Instruction::Trunc:
6930       // Check if this is a noop.
6931       // trunc(sext ty1 to ty2) to ty1.
6932       if (Instr->getType() == Ext->getOperand(0)->getType())
6933         continue;
6934     // FALL THROUGH.
6935     default:
6936       return false;
6937     }
6938
6939     // At this point we can use the bfm family, so this extension is free
6940     // for that use.
6941   }
6942   return true;
6943 }
6944
6945 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6946                                           unsigned &RequiredAligment) const {
6947   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6948     return false;
6949   // Cyclone supports unaligned accesses.
6950   RequiredAligment = 0;
6951   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6952   return NumBits == 32 || NumBits == 64;
6953 }
6954
6955 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6956                                           unsigned &RequiredAligment) const {
6957   if (!LoadedType.isSimple() ||
6958       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6959     return false;
6960   // Cyclone supports unaligned accesses.
6961   RequiredAligment = 0;
6962   unsigned NumBits = LoadedType.getSizeInBits();
6963   return NumBits == 32 || NumBits == 64;
6964 }
6965
6966 /// \brief Lower an interleaved load into a ldN intrinsic.
6967 ///
6968 /// E.g. Lower an interleaved load (Factor = 2):
6969 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6970 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6971 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6972 ///
6973 ///      Into:
6974 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6975 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6976 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6977 bool AArch64TargetLowering::lowerInterleavedLoad(
6978     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6979     ArrayRef<unsigned> Indices, unsigned Factor) const {
6980   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6981          "Invalid interleave factor");
6982   assert(!Shuffles.empty() && "Empty shufflevector input");
6983   assert(Shuffles.size() == Indices.size() &&
6984          "Unmatched number of shufflevectors and indices");
6985
6986   const DataLayout &DL = LI->getModule()->getDataLayout();
6987
6988   VectorType *VecTy = Shuffles[0]->getType();
6989   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6990
6991   // Skip if we do not have NEON and skip illegal vector types.
6992   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
6993     return false;
6994
6995   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6996   // load integer vectors first and then convert to pointer vectors.
6997   Type *EltTy = VecTy->getVectorElementType();
6998   if (EltTy->isPointerTy())
6999     VecTy =
7000         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7001
7002   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7003   Type *Tys[2] = {VecTy, PtrTy};
7004   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7005                                             Intrinsic::aarch64_neon_ld3,
7006                                             Intrinsic::aarch64_neon_ld4};
7007   Function *LdNFunc =
7008       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7009
7010   IRBuilder<> Builder(LI);
7011   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7012
7013   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7014
7015   // Replace uses of each shufflevector with the corresponding vector loaded
7016   // by ldN.
7017   for (unsigned i = 0; i < Shuffles.size(); i++) {
7018     ShuffleVectorInst *SVI = Shuffles[i];
7019     unsigned Index = Indices[i];
7020
7021     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7022
7023     // Convert the integer vector to pointer vector if the element is pointer.
7024     if (EltTy->isPointerTy())
7025       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7026
7027     SVI->replaceAllUsesWith(SubVec);
7028   }
7029
7030   return true;
7031 }
7032
7033 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7034 ///
7035 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7036 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7037                                    unsigned NumElts) {
7038   SmallVector<Constant *, 16> Mask;
7039   for (unsigned i = 0; i < NumElts; i++)
7040     Mask.push_back(Builder.getInt32(Start + i));
7041
7042   return ConstantVector::get(Mask);
7043 }
7044
7045 /// \brief Lower an interleaved store into a stN intrinsic.
7046 ///
7047 /// E.g. Lower an interleaved store (Factor = 3):
7048 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7049 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7050 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7051 ///
7052 ///      Into:
7053 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7054 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7055 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7056 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7057 ///
7058 /// Note that the new shufflevectors will be removed and we'll only generate one
7059 /// st3 instruction in CodeGen.
7060 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7061                                                   ShuffleVectorInst *SVI,
7062                                                   unsigned Factor) const {
7063   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7064          "Invalid interleave factor");
7065
7066   VectorType *VecTy = SVI->getType();
7067   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7068          "Invalid interleaved store");
7069
7070   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7071   Type *EltTy = VecTy->getVectorElementType();
7072   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7073
7074   const DataLayout &DL = SI->getModule()->getDataLayout();
7075   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7076
7077   // Skip if we do not have NEON and skip illegal vector types.
7078   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7079     return false;
7080
7081   Value *Op0 = SVI->getOperand(0);
7082   Value *Op1 = SVI->getOperand(1);
7083   IRBuilder<> Builder(SI);
7084
7085   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7086   // vectors to integer vectors.
7087   if (EltTy->isPointerTy()) {
7088     Type *IntTy = DL.getIntPtrType(EltTy);
7089     unsigned NumOpElts =
7090         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7091
7092     // Convert to the corresponding integer vector.
7093     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7094     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7095     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7096
7097     SubVecTy = VectorType::get(IntTy, NumSubElts);
7098   }
7099
7100   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7101   Type *Tys[2] = {SubVecTy, PtrTy};
7102   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7103                                              Intrinsic::aarch64_neon_st3,
7104                                              Intrinsic::aarch64_neon_st4};
7105   Function *StNFunc =
7106       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7107
7108   SmallVector<Value *, 5> Ops;
7109
7110   // Split the shufflevector operands into sub vectors for the new stN call.
7111   for (unsigned i = 0; i < Factor; i++)
7112     Ops.push_back(Builder.CreateShuffleVector(
7113         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7114
7115   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7116   Builder.CreateCall(StNFunc, Ops);
7117   return true;
7118 }
7119
7120 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7121                        unsigned AlignCheck) {
7122   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7123           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7124 }
7125
7126 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7127                                                unsigned SrcAlign, bool IsMemset,
7128                                                bool ZeroMemset,
7129                                                bool MemcpyStrSrc,
7130                                                MachineFunction &MF) const {
7131   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7132   // instruction to materialize the v2i64 zero and one store (with restrictive
7133   // addressing mode). Just do two i64 store of zero-registers.
7134   bool Fast;
7135   const Function *F = MF.getFunction();
7136   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7137       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7138       (memOpAlign(SrcAlign, DstAlign, 16) ||
7139        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7140     return MVT::f128;
7141
7142   if (Size >= 8 &&
7143       (memOpAlign(SrcAlign, DstAlign, 8) ||
7144        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7145     return MVT::i64;
7146
7147   if (Size >= 4 &&
7148       (memOpAlign(SrcAlign, DstAlign, 4) ||
7149        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7150     return MVT::i32;
7151
7152   return MVT::Other;
7153 }
7154
7155 // 12-bit optionally shifted immediates are legal for adds.
7156 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7157   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7158     return true;
7159   return false;
7160 }
7161
7162 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7163 // immediates is the same as for an add or a sub.
7164 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7165   if (Immed < 0)
7166     Immed *= -1;
7167   return isLegalAddImmediate(Immed);
7168 }
7169
7170 /// isLegalAddressingMode - Return true if the addressing mode represented
7171 /// by AM is legal for this target, for a load/store of the specified type.
7172 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7173                                                   const AddrMode &AM, Type *Ty,
7174                                                   unsigned AS) const {
7175   // AArch64 has five basic addressing modes:
7176   //  reg
7177   //  reg + 9-bit signed offset
7178   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7179   //  reg1 + reg2
7180   //  reg + SIZE_IN_BYTES * reg
7181
7182   // No global is ever allowed as a base.
7183   if (AM.BaseGV)
7184     return false;
7185
7186   // No reg+reg+imm addressing.
7187   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7188     return false;
7189
7190   // check reg + imm case:
7191   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7192   uint64_t NumBytes = 0;
7193   if (Ty->isSized()) {
7194     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7195     NumBytes = NumBits / 8;
7196     if (!isPowerOf2_64(NumBits))
7197       NumBytes = 0;
7198   }
7199
7200   if (!AM.Scale) {
7201     int64_t Offset = AM.BaseOffs;
7202
7203     // 9-bit signed offset
7204     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7205       return true;
7206
7207     // 12-bit unsigned offset
7208     unsigned shift = Log2_64(NumBytes);
7209     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7210         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7211         (Offset >> shift) << shift == Offset)
7212       return true;
7213     return false;
7214   }
7215
7216   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7217
7218   if (!AM.Scale || AM.Scale == 1 ||
7219       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7220     return true;
7221   return false;
7222 }
7223
7224 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7225                                                 const AddrMode &AM, Type *Ty,
7226                                                 unsigned AS) const {
7227   // Scaling factors are not free at all.
7228   // Operands                     | Rt Latency
7229   // -------------------------------------------
7230   // Rt, [Xn, Xm]                 | 4
7231   // -------------------------------------------
7232   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7233   // Rt, [Xn, Wm, <extend> #imm]  |
7234   if (isLegalAddressingMode(DL, AM, Ty, AS))
7235     // Scale represents reg2 * scale, thus account for 1 if
7236     // it is not equal to 0 or 1.
7237     return AM.Scale != 0 && AM.Scale != 1;
7238   return -1;
7239 }
7240
7241 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7242   VT = VT.getScalarType();
7243
7244   if (!VT.isSimple())
7245     return false;
7246
7247   switch (VT.getSimpleVT().SimpleTy) {
7248   case MVT::f32:
7249   case MVT::f64:
7250     return true;
7251   default:
7252     break;
7253   }
7254
7255   return false;
7256 }
7257
7258 const MCPhysReg *
7259 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7260   // LR is a callee-save register, but we must treat it as clobbered by any call
7261   // site. Hence we include LR in the scratch registers, which are in turn added
7262   // as implicit-defs for stackmaps and patchpoints.
7263   static const MCPhysReg ScratchRegs[] = {
7264     AArch64::X16, AArch64::X17, AArch64::LR, 0
7265   };
7266   return ScratchRegs;
7267 }
7268
7269 bool
7270 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7271   EVT VT = N->getValueType(0);
7272     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7273     // it with shift to let it be lowered to UBFX.
7274   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7275       isa<ConstantSDNode>(N->getOperand(1))) {
7276     uint64_t TruncMask = N->getConstantOperandVal(1);
7277     if (isMask_64(TruncMask) &&
7278       N->getOperand(0).getOpcode() == ISD::SRL &&
7279       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7280       return false;
7281   }
7282   return true;
7283 }
7284
7285 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7286                                                               Type *Ty) const {
7287   assert(Ty->isIntegerTy());
7288
7289   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7290   if (BitSize == 0)
7291     return false;
7292
7293   int64_t Val = Imm.getSExtValue();
7294   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7295     return true;
7296
7297   if ((int64_t)Val < 0)
7298     Val = ~Val;
7299   if (BitSize == 32)
7300     Val &= (1LL << 32) - 1;
7301
7302   unsigned LZ = countLeadingZeros((uint64_t)Val);
7303   unsigned Shift = (63 - LZ) / 16;
7304   // MOVZ is free so return true for one or fewer MOVK.
7305   return Shift < 3;
7306 }
7307
7308 // Generate SUBS and CSEL for integer abs.
7309 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7310   EVT VT = N->getValueType(0);
7311
7312   SDValue N0 = N->getOperand(0);
7313   SDValue N1 = N->getOperand(1);
7314   SDLoc DL(N);
7315
7316   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7317   // and change it to SUB and CSEL.
7318   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7319       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7320       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7321     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7322       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7323         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7324                                   N0.getOperand(0));
7325         // Generate SUBS & CSEL.
7326         SDValue Cmp =
7327             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7328                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7329         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7330                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7331                            SDValue(Cmp.getNode(), 1));
7332       }
7333   return SDValue();
7334 }
7335
7336 // performXorCombine - Attempts to handle integer ABS.
7337 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7338                                  TargetLowering::DAGCombinerInfo &DCI,
7339                                  const AArch64Subtarget *Subtarget) {
7340   if (DCI.isBeforeLegalizeOps())
7341     return SDValue();
7342
7343   return performIntegerAbsCombine(N, DAG);
7344 }
7345
7346 SDValue
7347 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7348                                      SelectionDAG &DAG,
7349                                      std::vector<SDNode *> *Created) const {
7350   // fold (sdiv X, pow2)
7351   EVT VT = N->getValueType(0);
7352   if ((VT != MVT::i32 && VT != MVT::i64) ||
7353       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7354     return SDValue();
7355
7356   SDLoc DL(N);
7357   SDValue N0 = N->getOperand(0);
7358   unsigned Lg2 = Divisor.countTrailingZeros();
7359   SDValue Zero = DAG.getConstant(0, DL, VT);
7360   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7361
7362   // Add (N0 < 0) ? Pow2 - 1 : 0;
7363   SDValue CCVal;
7364   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7365   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7366   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7367
7368   if (Created) {
7369     Created->push_back(Cmp.getNode());
7370     Created->push_back(Add.getNode());
7371     Created->push_back(CSel.getNode());
7372   }
7373
7374   // Divide by pow2.
7375   SDValue SRA =
7376       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7377
7378   // If we're dividing by a positive value, we're done.  Otherwise, we must
7379   // negate the result.
7380   if (Divisor.isNonNegative())
7381     return SRA;
7382
7383   if (Created)
7384     Created->push_back(SRA.getNode());
7385   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7386 }
7387
7388 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7389                                  TargetLowering::DAGCombinerInfo &DCI,
7390                                  const AArch64Subtarget *Subtarget) {
7391   if (DCI.isBeforeLegalizeOps())
7392     return SDValue();
7393
7394   // Multiplication of a power of two plus/minus one can be done more
7395   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7396   // future CPUs have a cheaper MADD instruction, this may need to be
7397   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7398   // 64-bit is 5 cycles, so this is always a win.
7399   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7400     APInt Value = C->getAPIntValue();
7401     EVT VT = N->getValueType(0);
7402     SDLoc DL(N);
7403     if (Value.isNonNegative()) {
7404       // (mul x, 2^N + 1) => (add (shl x, N), x)
7405       APInt VM1 = Value - 1;
7406       if (VM1.isPowerOf2()) {
7407         SDValue ShiftedVal =
7408             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7409                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7410         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7411                            N->getOperand(0));
7412       }
7413       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7414       APInt VP1 = Value + 1;
7415       if (VP1.isPowerOf2()) {
7416         SDValue ShiftedVal =
7417             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7418                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7419         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7420                            N->getOperand(0));
7421       }
7422     } else {
7423       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7424       APInt VNP1 = -Value + 1;
7425       if (VNP1.isPowerOf2()) {
7426         SDValue ShiftedVal =
7427             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7428                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7429         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7430                            ShiftedVal);
7431       }
7432       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7433       APInt VNM1 = -Value - 1;
7434       if (VNM1.isPowerOf2()) {
7435         SDValue ShiftedVal =
7436             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7437                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7438         SDValue Add =
7439             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7440         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7441       }
7442     }
7443   }
7444   return SDValue();
7445 }
7446
7447 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7448                                                          SelectionDAG &DAG) {
7449   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7450   // optimize away operation when it's from a constant.
7451   //
7452   // The general transformation is:
7453   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7454   //       AND(VECTOR_CMP(x,y), constant2)
7455   //    constant2 = UNARYOP(constant)
7456
7457   // Early exit if this isn't a vector operation, the operand of the
7458   // unary operation isn't a bitwise AND, or if the sizes of the operations
7459   // aren't the same.
7460   EVT VT = N->getValueType(0);
7461   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7462       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7463       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7464     return SDValue();
7465
7466   // Now check that the other operand of the AND is a constant. We could
7467   // make the transformation for non-constant splats as well, but it's unclear
7468   // that would be a benefit as it would not eliminate any operations, just
7469   // perform one more step in scalar code before moving to the vector unit.
7470   if (BuildVectorSDNode *BV =
7471           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7472     // Bail out if the vector isn't a constant.
7473     if (!BV->isConstant())
7474       return SDValue();
7475
7476     // Everything checks out. Build up the new and improved node.
7477     SDLoc DL(N);
7478     EVT IntVT = BV->getValueType(0);
7479     // Create a new constant of the appropriate type for the transformed
7480     // DAG.
7481     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7482     // The AND node needs bitcasts to/from an integer vector type around it.
7483     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7484     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7485                                  N->getOperand(0)->getOperand(0), MaskConst);
7486     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7487     return Res;
7488   }
7489
7490   return SDValue();
7491 }
7492
7493 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7494                                      const AArch64Subtarget *Subtarget) {
7495   // First try to optimize away the conversion when it's conditionally from
7496   // a constant. Vectors only.
7497   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7498     return Res;
7499
7500   EVT VT = N->getValueType(0);
7501   if (VT != MVT::f32 && VT != MVT::f64)
7502     return SDValue();
7503
7504   // Only optimize when the source and destination types have the same width.
7505   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7506     return SDValue();
7507
7508   // If the result of an integer load is only used by an integer-to-float
7509   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7510   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7511   SDValue N0 = N->getOperand(0);
7512   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7513       // Do not change the width of a volatile load.
7514       !cast<LoadSDNode>(N0)->isVolatile()) {
7515     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7516     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7517                                LN0->getPointerInfo(), LN0->isVolatile(),
7518                                LN0->isNonTemporal(), LN0->isInvariant(),
7519                                LN0->getAlignment());
7520
7521     // Make sure successors of the original load stay after it by updating them
7522     // to use the new Chain.
7523     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7524
7525     unsigned Opcode =
7526         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7527     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7528   }
7529
7530   return SDValue();
7531 }
7532
7533 /// Fold a floating-point multiply by power of two into floating-point to
7534 /// fixed-point conversion.
7535 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7536                                      const AArch64Subtarget *Subtarget) {
7537   if (!Subtarget->hasNEON())
7538     return SDValue();
7539
7540   SDValue Op = N->getOperand(0);
7541   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7542     return SDValue();
7543
7544   SDValue ConstVec = Op->getOperand(1);
7545   if (!isa<BuildVectorSDNode>(ConstVec))
7546     return SDValue();
7547
7548   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7549   uint32_t FloatBits = FloatTy.getSizeInBits();
7550   if (FloatBits != 32 && FloatBits != 64)
7551     return SDValue();
7552
7553   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7554   uint32_t IntBits = IntTy.getSizeInBits();
7555   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7556     return SDValue();
7557
7558   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7559   if (IntBits > FloatBits)
7560     return SDValue();
7561
7562   BitVector UndefElements;
7563   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7564   int32_t Bits = IntBits == 64 ? 64 : 32;
7565   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7566   if (C == -1 || C == 0 || C > Bits)
7567     return SDValue();
7568
7569   MVT ResTy;
7570   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7571   switch (NumLanes) {
7572   default:
7573     return SDValue();
7574   case 2:
7575     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7576     break;
7577   case 4:
7578     ResTy = MVT::v4i32;
7579     break;
7580   }
7581
7582   SDLoc DL(N);
7583   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7584   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7585                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7586   SDValue FixConv =
7587       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7588                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7589                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7590   // We can handle smaller integers by generating an extra trunc.
7591   if (IntBits < FloatBits)
7592     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7593
7594   return FixConv;
7595 }
7596
7597 /// Fold a floating-point divide by power of two into fixed-point to
7598 /// floating-point conversion.
7599 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7600                                   const AArch64Subtarget *Subtarget) {
7601   if (!Subtarget->hasNEON())
7602     return SDValue();
7603
7604   SDValue Op = N->getOperand(0);
7605   unsigned Opc = Op->getOpcode();
7606   if (!Op.getValueType().isVector() ||
7607       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7608     return SDValue();
7609
7610   SDValue ConstVec = N->getOperand(1);
7611   if (!isa<BuildVectorSDNode>(ConstVec))
7612     return SDValue();
7613
7614   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7615   int32_t IntBits = IntTy.getSizeInBits();
7616   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7617     return SDValue();
7618
7619   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7620   int32_t FloatBits = FloatTy.getSizeInBits();
7621   if (FloatBits != 32 && FloatBits != 64)
7622     return SDValue();
7623
7624   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7625   if (IntBits > FloatBits)
7626     return SDValue();
7627
7628   BitVector UndefElements;
7629   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7630   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7631   if (C == -1 || C == 0 || C > FloatBits)
7632     return SDValue();
7633
7634   MVT ResTy;
7635   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7636   switch (NumLanes) {
7637   default:
7638     return SDValue();
7639   case 2:
7640     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7641     break;
7642   case 4:
7643     ResTy = MVT::v4i32;
7644     break;
7645   }
7646
7647   SDLoc DL(N);
7648   SDValue ConvInput = Op.getOperand(0);
7649   bool IsSigned = Opc == ISD::SINT_TO_FP;
7650   if (IntBits < FloatBits)
7651     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7652                             ResTy, ConvInput);
7653
7654   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7655                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7656   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7657                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7658                      DAG.getConstant(C, DL, MVT::i32));
7659 }
7660
7661 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7662 /// searches for and classifies those shifts.
7663 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7664                          bool &FromHi) {
7665   if (N.getOpcode() == ISD::SHL)
7666     FromHi = false;
7667   else if (N.getOpcode() == ISD::SRL)
7668     FromHi = true;
7669   else
7670     return false;
7671
7672   if (!isa<ConstantSDNode>(N.getOperand(1)))
7673     return false;
7674
7675   ShiftAmount = N->getConstantOperandVal(1);
7676   Src = N->getOperand(0);
7677   return true;
7678 }
7679
7680 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7681 /// registers viewed as a high/low pair. This function looks for the pattern:
7682 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7683 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7684 /// independent.
7685 static SDValue tryCombineToEXTR(SDNode *N,
7686                                 TargetLowering::DAGCombinerInfo &DCI) {
7687   SelectionDAG &DAG = DCI.DAG;
7688   SDLoc DL(N);
7689   EVT VT = N->getValueType(0);
7690
7691   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7692
7693   if (VT != MVT::i32 && VT != MVT::i64)
7694     return SDValue();
7695
7696   SDValue LHS;
7697   uint32_t ShiftLHS = 0;
7698   bool LHSFromHi = 0;
7699   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7700     return SDValue();
7701
7702   SDValue RHS;
7703   uint32_t ShiftRHS = 0;
7704   bool RHSFromHi = 0;
7705   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7706     return SDValue();
7707
7708   // If they're both trying to come from the high part of the register, they're
7709   // not really an EXTR.
7710   if (LHSFromHi == RHSFromHi)
7711     return SDValue();
7712
7713   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7714     return SDValue();
7715
7716   if (LHSFromHi) {
7717     std::swap(LHS, RHS);
7718     std::swap(ShiftLHS, ShiftRHS);
7719   }
7720
7721   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7722                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7723 }
7724
7725 static SDValue tryCombineToBSL(SDNode *N,
7726                                 TargetLowering::DAGCombinerInfo &DCI) {
7727   EVT VT = N->getValueType(0);
7728   SelectionDAG &DAG = DCI.DAG;
7729   SDLoc DL(N);
7730
7731   if (!VT.isVector())
7732     return SDValue();
7733
7734   SDValue N0 = N->getOperand(0);
7735   if (N0.getOpcode() != ISD::AND)
7736     return SDValue();
7737
7738   SDValue N1 = N->getOperand(1);
7739   if (N1.getOpcode() != ISD::AND)
7740     return SDValue();
7741
7742   // We only have to look for constant vectors here since the general, variable
7743   // case can be handled in TableGen.
7744   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7745   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7746   for (int i = 1; i >= 0; --i)
7747     for (int j = 1; j >= 0; --j) {
7748       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7749       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7750       if (!BVN0 || !BVN1)
7751         continue;
7752
7753       bool FoundMatch = true;
7754       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7755         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7756         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7757         if (!CN0 || !CN1 ||
7758             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7759           FoundMatch = false;
7760           break;
7761         }
7762       }
7763
7764       if (FoundMatch)
7765         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7766                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7767     }
7768
7769   return SDValue();
7770 }
7771
7772 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7773                                 const AArch64Subtarget *Subtarget) {
7774   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7775   if (!EnableAArch64ExtrGeneration)
7776     return SDValue();
7777   SelectionDAG &DAG = DCI.DAG;
7778   EVT VT = N->getValueType(0);
7779
7780   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7781     return SDValue();
7782
7783   SDValue Res = tryCombineToEXTR(N, DCI);
7784   if (Res.getNode())
7785     return Res;
7786
7787   Res = tryCombineToBSL(N, DCI);
7788   if (Res.getNode())
7789     return Res;
7790
7791   return SDValue();
7792 }
7793
7794 static SDValue performBitcastCombine(SDNode *N,
7795                                      TargetLowering::DAGCombinerInfo &DCI,
7796                                      SelectionDAG &DAG) {
7797   // Wait 'til after everything is legalized to try this. That way we have
7798   // legal vector types and such.
7799   if (DCI.isBeforeLegalizeOps())
7800     return SDValue();
7801
7802   // Remove extraneous bitcasts around an extract_subvector.
7803   // For example,
7804   //    (v4i16 (bitconvert
7805   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7806   //  becomes
7807   //    (extract_subvector ((v8i16 ...), (i64 4)))
7808
7809   // Only interested in 64-bit vectors as the ultimate result.
7810   EVT VT = N->getValueType(0);
7811   if (!VT.isVector())
7812     return SDValue();
7813   if (VT.getSimpleVT().getSizeInBits() != 64)
7814     return SDValue();
7815   // Is the operand an extract_subvector starting at the beginning or halfway
7816   // point of the vector? A low half may also come through as an
7817   // EXTRACT_SUBREG, so look for that, too.
7818   SDValue Op0 = N->getOperand(0);
7819   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7820       !(Op0->isMachineOpcode() &&
7821         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7822     return SDValue();
7823   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7824   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7825     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7826       return SDValue();
7827   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7828     if (idx != AArch64::dsub)
7829       return SDValue();
7830     // The dsub reference is equivalent to a lane zero subvector reference.
7831     idx = 0;
7832   }
7833   // Look through the bitcast of the input to the extract.
7834   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7835     return SDValue();
7836   SDValue Source = Op0->getOperand(0)->getOperand(0);
7837   // If the source type has twice the number of elements as our destination
7838   // type, we know this is an extract of the high or low half of the vector.
7839   EVT SVT = Source->getValueType(0);
7840   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7841     return SDValue();
7842
7843   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7844
7845   // Create the simplified form to just extract the low or high half of the
7846   // vector directly rather than bothering with the bitcasts.
7847   SDLoc dl(N);
7848   unsigned NumElements = VT.getVectorNumElements();
7849   if (idx) {
7850     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7851     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7852   } else {
7853     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7854     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7855                                       Source, SubReg),
7856                    0);
7857   }
7858 }
7859
7860 static SDValue performConcatVectorsCombine(SDNode *N,
7861                                            TargetLowering::DAGCombinerInfo &DCI,
7862                                            SelectionDAG &DAG) {
7863   SDLoc dl(N);
7864   EVT VT = N->getValueType(0);
7865   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7866
7867   // Optimize concat_vectors of truncated vectors, where the intermediate
7868   // type is illegal, to avoid said illegality,  e.g.,
7869   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7870   //                          (v2i16 (truncate (v2i64)))))
7871   // ->
7872   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7873   //                                    (v4i32 (bitcast (v2i64))),
7874   //                                    <0, 2, 4, 6>)))
7875   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7876   // on both input and result type, so we might generate worse code.
7877   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7878   if (N->getNumOperands() == 2 &&
7879       N0->getOpcode() == ISD::TRUNCATE &&
7880       N1->getOpcode() == ISD::TRUNCATE) {
7881     SDValue N00 = N0->getOperand(0);
7882     SDValue N10 = N1->getOperand(0);
7883     EVT N00VT = N00.getValueType();
7884
7885     if (N00VT == N10.getValueType() &&
7886         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7887         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7888       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7889       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7890       for (size_t i = 0; i < Mask.size(); ++i)
7891         Mask[i] = i * 2;
7892       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7893                          DAG.getVectorShuffle(
7894                              MidVT, dl,
7895                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7896                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7897     }
7898   }
7899
7900   // Wait 'til after everything is legalized to try this. That way we have
7901   // legal vector types and such.
7902   if (DCI.isBeforeLegalizeOps())
7903     return SDValue();
7904
7905   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7906   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7907   // canonicalise to that.
7908   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7909     assert(VT.getVectorElementType().getSizeInBits() == 64);
7910     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7911                        DAG.getConstant(0, dl, MVT::i64));
7912   }
7913
7914   // Canonicalise concat_vectors so that the right-hand vector has as few
7915   // bit-casts as possible before its real operation. The primary matching
7916   // destination for these operations will be the narrowing "2" instructions,
7917   // which depend on the operation being performed on this right-hand vector.
7918   // For example,
7919   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7920   // becomes
7921   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7922
7923   if (N1->getOpcode() != ISD::BITCAST)
7924     return SDValue();
7925   SDValue RHS = N1->getOperand(0);
7926   MVT RHSTy = RHS.getValueType().getSimpleVT();
7927   // If the RHS is not a vector, this is not the pattern we're looking for.
7928   if (!RHSTy.isVector())
7929     return SDValue();
7930
7931   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7932
7933   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7934                                   RHSTy.getVectorNumElements() * 2);
7935   return DAG.getNode(ISD::BITCAST, dl, VT,
7936                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7937                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7938                                  RHS));
7939 }
7940
7941 static SDValue tryCombineFixedPointConvert(SDNode *N,
7942                                            TargetLowering::DAGCombinerInfo &DCI,
7943                                            SelectionDAG &DAG) {
7944   // Wait 'til after everything is legalized to try this. That way we have
7945   // legal vector types and such.
7946   if (DCI.isBeforeLegalizeOps())
7947     return SDValue();
7948   // Transform a scalar conversion of a value from a lane extract into a
7949   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7950   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7951   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7952   //
7953   // The second form interacts better with instruction selection and the
7954   // register allocator to avoid cross-class register copies that aren't
7955   // coalescable due to a lane reference.
7956
7957   // Check the operand and see if it originates from a lane extract.
7958   SDValue Op1 = N->getOperand(1);
7959   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7960     // Yep, no additional predication needed. Perform the transform.
7961     SDValue IID = N->getOperand(0);
7962     SDValue Shift = N->getOperand(2);
7963     SDValue Vec = Op1.getOperand(0);
7964     SDValue Lane = Op1.getOperand(1);
7965     EVT ResTy = N->getValueType(0);
7966     EVT VecResTy;
7967     SDLoc DL(N);
7968
7969     // The vector width should be 128 bits by the time we get here, even
7970     // if it started as 64 bits (the extract_vector handling will have
7971     // done so).
7972     assert(Vec.getValueType().getSizeInBits() == 128 &&
7973            "unexpected vector size on extract_vector_elt!");
7974     if (Vec.getValueType() == MVT::v4i32)
7975       VecResTy = MVT::v4f32;
7976     else if (Vec.getValueType() == MVT::v2i64)
7977       VecResTy = MVT::v2f64;
7978     else
7979       llvm_unreachable("unexpected vector type!");
7980
7981     SDValue Convert =
7982         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7983     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7984   }
7985   return SDValue();
7986 }
7987
7988 // AArch64 high-vector "long" operations are formed by performing the non-high
7989 // version on an extract_subvector of each operand which gets the high half:
7990 //
7991 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7992 //
7993 // However, there are cases which don't have an extract_high explicitly, but
7994 // have another operation that can be made compatible with one for free. For
7995 // example:
7996 //
7997 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7998 //
7999 // This routine does the actual conversion of such DUPs, once outer routines
8000 // have determined that everything else is in order.
8001 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8002 // similarly here.
8003 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8004   switch (N.getOpcode()) {
8005   case AArch64ISD::DUP:
8006   case AArch64ISD::DUPLANE8:
8007   case AArch64ISD::DUPLANE16:
8008   case AArch64ISD::DUPLANE32:
8009   case AArch64ISD::DUPLANE64:
8010   case AArch64ISD::MOVI:
8011   case AArch64ISD::MOVIshift:
8012   case AArch64ISD::MOVIedit:
8013   case AArch64ISD::MOVImsl:
8014   case AArch64ISD::MVNIshift:
8015   case AArch64ISD::MVNImsl:
8016     break;
8017   default:
8018     // FMOV could be supported, but isn't very useful, as it would only occur
8019     // if you passed a bitcast' floating point immediate to an eligible long
8020     // integer op (addl, smull, ...).
8021     return SDValue();
8022   }
8023
8024   MVT NarrowTy = N.getSimpleValueType();
8025   if (!NarrowTy.is64BitVector())
8026     return SDValue();
8027
8028   MVT ElementTy = NarrowTy.getVectorElementType();
8029   unsigned NumElems = NarrowTy.getVectorNumElements();
8030   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8031
8032   SDLoc dl(N);
8033   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8034                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8035                      DAG.getConstant(NumElems, dl, MVT::i64));
8036 }
8037
8038 static bool isEssentiallyExtractSubvector(SDValue N) {
8039   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8040     return true;
8041
8042   return N.getOpcode() == ISD::BITCAST &&
8043          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8044 }
8045
8046 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8047 struct GenericSetCCInfo {
8048   const SDValue *Opnd0;
8049   const SDValue *Opnd1;
8050   ISD::CondCode CC;
8051 };
8052
8053 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8054 struct AArch64SetCCInfo {
8055   const SDValue *Cmp;
8056   AArch64CC::CondCode CC;
8057 };
8058
8059 /// \brief Helper structure to keep track of SetCC information.
8060 union SetCCInfo {
8061   GenericSetCCInfo Generic;
8062   AArch64SetCCInfo AArch64;
8063 };
8064
8065 /// \brief Helper structure to be able to read SetCC information.  If set to
8066 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8067 /// GenericSetCCInfo.
8068 struct SetCCInfoAndKind {
8069   SetCCInfo Info;
8070   bool IsAArch64;
8071 };
8072
8073 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8074 /// an
8075 /// AArch64 lowered one.
8076 /// \p SetCCInfo is filled accordingly.
8077 /// \post SetCCInfo is meanginfull only when this function returns true.
8078 /// \return True when Op is a kind of SET_CC operation.
8079 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8080   // If this is a setcc, this is straight forward.
8081   if (Op.getOpcode() == ISD::SETCC) {
8082     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8083     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8084     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8085     SetCCInfo.IsAArch64 = false;
8086     return true;
8087   }
8088   // Otherwise, check if this is a matching csel instruction.
8089   // In other words:
8090   // - csel 1, 0, cc
8091   // - csel 0, 1, !cc
8092   if (Op.getOpcode() != AArch64ISD::CSEL)
8093     return false;
8094   // Set the information about the operands.
8095   // TODO: we want the operands of the Cmp not the csel
8096   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8097   SetCCInfo.IsAArch64 = true;
8098   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8099       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8100
8101   // Check that the operands matches the constraints:
8102   // (1) Both operands must be constants.
8103   // (2) One must be 1 and the other must be 0.
8104   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8105   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8106
8107   // Check (1).
8108   if (!TValue || !FValue)
8109     return false;
8110
8111   // Check (2).
8112   if (!TValue->isOne()) {
8113     // Update the comparison when we are interested in !cc.
8114     std::swap(TValue, FValue);
8115     SetCCInfo.Info.AArch64.CC =
8116         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8117   }
8118   return TValue->isOne() && FValue->isNullValue();
8119 }
8120
8121 // Returns true if Op is setcc or zext of setcc.
8122 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8123   if (isSetCC(Op, Info))
8124     return true;
8125   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8126     isSetCC(Op->getOperand(0), Info));
8127 }
8128
8129 // The folding we want to perform is:
8130 // (add x, [zext] (setcc cc ...) )
8131 //   -->
8132 // (csel x, (add x, 1), !cc ...)
8133 //
8134 // The latter will get matched to a CSINC instruction.
8135 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8136   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8137   SDValue LHS = Op->getOperand(0);
8138   SDValue RHS = Op->getOperand(1);
8139   SetCCInfoAndKind InfoAndKind;
8140
8141   // If neither operand is a SET_CC, give up.
8142   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8143     std::swap(LHS, RHS);
8144     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8145       return SDValue();
8146   }
8147
8148   // FIXME: This could be generatized to work for FP comparisons.
8149   EVT CmpVT = InfoAndKind.IsAArch64
8150                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8151                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8152   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8153     return SDValue();
8154
8155   SDValue CCVal;
8156   SDValue Cmp;
8157   SDLoc dl(Op);
8158   if (InfoAndKind.IsAArch64) {
8159     CCVal = DAG.getConstant(
8160         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8161         MVT::i32);
8162     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8163   } else
8164     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8165                       *InfoAndKind.Info.Generic.Opnd1,
8166                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8167                       CCVal, DAG, dl);
8168
8169   EVT VT = Op->getValueType(0);
8170   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8171   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8172 }
8173
8174 // The basic add/sub long vector instructions have variants with "2" on the end
8175 // which act on the high-half of their inputs. They are normally matched by
8176 // patterns like:
8177 //
8178 // (add (zeroext (extract_high LHS)),
8179 //      (zeroext (extract_high RHS)))
8180 // -> uaddl2 vD, vN, vM
8181 //
8182 // However, if one of the extracts is something like a duplicate, this
8183 // instruction can still be used profitably. This function puts the DAG into a
8184 // more appropriate form for those patterns to trigger.
8185 static SDValue performAddSubLongCombine(SDNode *N,
8186                                         TargetLowering::DAGCombinerInfo &DCI,
8187                                         SelectionDAG &DAG) {
8188   if (DCI.isBeforeLegalizeOps())
8189     return SDValue();
8190
8191   MVT VT = N->getSimpleValueType(0);
8192   if (!VT.is128BitVector()) {
8193     if (N->getOpcode() == ISD::ADD)
8194       return performSetccAddFolding(N, DAG);
8195     return SDValue();
8196   }
8197
8198   // Make sure both branches are extended in the same way.
8199   SDValue LHS = N->getOperand(0);
8200   SDValue RHS = N->getOperand(1);
8201   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8202        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8203       LHS.getOpcode() != RHS.getOpcode())
8204     return SDValue();
8205
8206   unsigned ExtType = LHS.getOpcode();
8207
8208   // It's not worth doing if at least one of the inputs isn't already an
8209   // extract, but we don't know which it'll be so we have to try both.
8210   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8211     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8212     if (!RHS.getNode())
8213       return SDValue();
8214
8215     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8216   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8217     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8218     if (!LHS.getNode())
8219       return SDValue();
8220
8221     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8222   }
8223
8224   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8225 }
8226
8227 // Massage DAGs which we can use the high-half "long" operations on into
8228 // something isel will recognize better. E.g.
8229 //
8230 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8231 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8232 //                     (extract_high (v2i64 (dup128 scalar)))))
8233 //
8234 static SDValue tryCombineLongOpWithDup(SDNode *N,
8235                                        TargetLowering::DAGCombinerInfo &DCI,
8236                                        SelectionDAG &DAG) {
8237   if (DCI.isBeforeLegalizeOps())
8238     return SDValue();
8239
8240   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8241   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8242   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8243   assert(LHS.getValueType().is64BitVector() &&
8244          RHS.getValueType().is64BitVector() &&
8245          "unexpected shape for long operation");
8246
8247   // Either node could be a DUP, but it's not worth doing both of them (you'd
8248   // just as well use the non-high version) so look for a corresponding extract
8249   // operation on the other "wing".
8250   if (isEssentiallyExtractSubvector(LHS)) {
8251     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8252     if (!RHS.getNode())
8253       return SDValue();
8254   } else if (isEssentiallyExtractSubvector(RHS)) {
8255     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8256     if (!LHS.getNode())
8257       return SDValue();
8258   }
8259
8260   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8261   if (IsIntrinsic)
8262     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8263                        N->getOperand(0), LHS, RHS);
8264   else
8265     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8266                        LHS, RHS);
8267 }
8268
8269 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8270   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8271   unsigned ElemBits = ElemTy.getSizeInBits();
8272
8273   int64_t ShiftAmount;
8274   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8275     APInt SplatValue, SplatUndef;
8276     unsigned SplatBitSize;
8277     bool HasAnyUndefs;
8278     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8279                               HasAnyUndefs, ElemBits) ||
8280         SplatBitSize != ElemBits)
8281       return SDValue();
8282
8283     ShiftAmount = SplatValue.getSExtValue();
8284   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8285     ShiftAmount = CVN->getSExtValue();
8286   } else
8287     return SDValue();
8288
8289   unsigned Opcode;
8290   bool IsRightShift;
8291   switch (IID) {
8292   default:
8293     llvm_unreachable("Unknown shift intrinsic");
8294   case Intrinsic::aarch64_neon_sqshl:
8295     Opcode = AArch64ISD::SQSHL_I;
8296     IsRightShift = false;
8297     break;
8298   case Intrinsic::aarch64_neon_uqshl:
8299     Opcode = AArch64ISD::UQSHL_I;
8300     IsRightShift = false;
8301     break;
8302   case Intrinsic::aarch64_neon_srshl:
8303     Opcode = AArch64ISD::SRSHR_I;
8304     IsRightShift = true;
8305     break;
8306   case Intrinsic::aarch64_neon_urshl:
8307     Opcode = AArch64ISD::URSHR_I;
8308     IsRightShift = true;
8309     break;
8310   case Intrinsic::aarch64_neon_sqshlu:
8311     Opcode = AArch64ISD::SQSHLU_I;
8312     IsRightShift = false;
8313     break;
8314   }
8315
8316   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8317     SDLoc dl(N);
8318     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8319                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8320   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8321     SDLoc dl(N);
8322     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8323                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8324   }
8325
8326   return SDValue();
8327 }
8328
8329 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8330 // the intrinsics must be legal and take an i32, this means there's almost
8331 // certainly going to be a zext in the DAG which we can eliminate.
8332 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8333   SDValue AndN = N->getOperand(2);
8334   if (AndN.getOpcode() != ISD::AND)
8335     return SDValue();
8336
8337   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8338   if (!CMask || CMask->getZExtValue() != Mask)
8339     return SDValue();
8340
8341   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8342                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8343 }
8344
8345 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8346                                            SelectionDAG &DAG) {
8347   SDLoc dl(N);
8348   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8349                      DAG.getNode(Opc, dl,
8350                                  N->getOperand(1).getSimpleValueType(),
8351                                  N->getOperand(1)),
8352                      DAG.getConstant(0, dl, MVT::i64));
8353 }
8354
8355 static SDValue performIntrinsicCombine(SDNode *N,
8356                                        TargetLowering::DAGCombinerInfo &DCI,
8357                                        const AArch64Subtarget *Subtarget) {
8358   SelectionDAG &DAG = DCI.DAG;
8359   unsigned IID = getIntrinsicID(N);
8360   switch (IID) {
8361   default:
8362     break;
8363   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8364   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8365     return tryCombineFixedPointConvert(N, DCI, DAG);
8366   case Intrinsic::aarch64_neon_saddv:
8367     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8368   case Intrinsic::aarch64_neon_uaddv:
8369     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8370   case Intrinsic::aarch64_neon_sminv:
8371     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8372   case Intrinsic::aarch64_neon_uminv:
8373     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8374   case Intrinsic::aarch64_neon_smaxv:
8375     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8376   case Intrinsic::aarch64_neon_umaxv:
8377     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8378   case Intrinsic::aarch64_neon_fmax:
8379     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8380                        N->getOperand(1), N->getOperand(2));
8381   case Intrinsic::aarch64_neon_fmin:
8382     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8383                        N->getOperand(1), N->getOperand(2));
8384   case Intrinsic::aarch64_neon_sabd:
8385     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8386                        N->getOperand(1), N->getOperand(2));
8387   case Intrinsic::aarch64_neon_uabd:
8388     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8389                        N->getOperand(1), N->getOperand(2));
8390   case Intrinsic::aarch64_neon_fmaxnm:
8391     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8392                        N->getOperand(1), N->getOperand(2));
8393   case Intrinsic::aarch64_neon_fminnm:
8394     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8395                        N->getOperand(1), N->getOperand(2));
8396   case Intrinsic::aarch64_neon_smull:
8397   case Intrinsic::aarch64_neon_umull:
8398   case Intrinsic::aarch64_neon_pmull:
8399   case Intrinsic::aarch64_neon_sqdmull:
8400     return tryCombineLongOpWithDup(N, DCI, DAG);
8401   case Intrinsic::aarch64_neon_sqshl:
8402   case Intrinsic::aarch64_neon_uqshl:
8403   case Intrinsic::aarch64_neon_sqshlu:
8404   case Intrinsic::aarch64_neon_srshl:
8405   case Intrinsic::aarch64_neon_urshl:
8406     return tryCombineShiftImm(IID, N, DAG);
8407   case Intrinsic::aarch64_crc32b:
8408   case Intrinsic::aarch64_crc32cb:
8409     return tryCombineCRC32(0xff, N, DAG);
8410   case Intrinsic::aarch64_crc32h:
8411   case Intrinsic::aarch64_crc32ch:
8412     return tryCombineCRC32(0xffff, N, DAG);
8413   }
8414   return SDValue();
8415 }
8416
8417 static SDValue performExtendCombine(SDNode *N,
8418                                     TargetLowering::DAGCombinerInfo &DCI,
8419                                     SelectionDAG &DAG) {
8420   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8421   // we can convert that DUP into another extract_high (of a bigger DUP), which
8422   // helps the backend to decide that an sabdl2 would be useful, saving a real
8423   // extract_high operation.
8424   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8425       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8426        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8427     SDNode *ABDNode = N->getOperand(0).getNode();
8428     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8429     if (!NewABD.getNode())
8430       return SDValue();
8431
8432     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8433                        NewABD);
8434   }
8435
8436   // This is effectively a custom type legalization for AArch64.
8437   //
8438   // Type legalization will split an extend of a small, legal, type to a larger
8439   // illegal type by first splitting the destination type, often creating
8440   // illegal source types, which then get legalized in isel-confusing ways,
8441   // leading to really terrible codegen. E.g.,
8442   //   %result = v8i32 sext v8i8 %value
8443   // becomes
8444   //   %losrc = extract_subreg %value, ...
8445   //   %hisrc = extract_subreg %value, ...
8446   //   %lo = v4i32 sext v4i8 %losrc
8447   //   %hi = v4i32 sext v4i8 %hisrc
8448   // Things go rapidly downhill from there.
8449   //
8450   // For AArch64, the [sz]ext vector instructions can only go up one element
8451   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8452   // take two instructions.
8453   //
8454   // This implies that the most efficient way to do the extend from v8i8
8455   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8456   // the normal splitting to happen for the v8i16->v8i32.
8457
8458   // This is pre-legalization to catch some cases where the default
8459   // type legalization will create ill-tempered code.
8460   if (!DCI.isBeforeLegalizeOps())
8461     return SDValue();
8462
8463   // We're only interested in cleaning things up for non-legal vector types
8464   // here. If both the source and destination are legal, things will just
8465   // work naturally without any fiddling.
8466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8467   EVT ResVT = N->getValueType(0);
8468   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8469     return SDValue();
8470   // If the vector type isn't a simple VT, it's beyond the scope of what
8471   // we're  worried about here. Let legalization do its thing and hope for
8472   // the best.
8473   SDValue Src = N->getOperand(0);
8474   EVT SrcVT = Src->getValueType(0);
8475   if (!ResVT.isSimple() || !SrcVT.isSimple())
8476     return SDValue();
8477
8478   // If the source VT is a 64-bit vector, we can play games and get the
8479   // better results we want.
8480   if (SrcVT.getSizeInBits() != 64)
8481     return SDValue();
8482
8483   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8484   unsigned ElementCount = SrcVT.getVectorNumElements();
8485   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8486   SDLoc DL(N);
8487   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8488
8489   // Now split the rest of the operation into two halves, each with a 64
8490   // bit source.
8491   EVT LoVT, HiVT;
8492   SDValue Lo, Hi;
8493   unsigned NumElements = ResVT.getVectorNumElements();
8494   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8495   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8496                                  ResVT.getVectorElementType(), NumElements / 2);
8497
8498   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8499                                LoVT.getVectorNumElements());
8500   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8501                    DAG.getConstant(0, DL, MVT::i64));
8502   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8503                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8504   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8505   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8506
8507   // Now combine the parts back together so we still have a single result
8508   // like the combiner expects.
8509   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8510 }
8511
8512 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8513 /// value. The load store optimizer pass will merge them to store pair stores.
8514 /// This has better performance than a splat of the scalar followed by a split
8515 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8516 /// followed by an ext.b and two stores.
8517 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8518   SDValue StVal = St->getValue();
8519   EVT VT = StVal.getValueType();
8520
8521   // Don't replace floating point stores, they possibly won't be transformed to
8522   // stp because of the store pair suppress pass.
8523   if (VT.isFloatingPoint())
8524     return SDValue();
8525
8526   // Check for insert vector elements.
8527   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8528     return SDValue();
8529
8530   // We can express a splat as store pair(s) for 2 or 4 elements.
8531   unsigned NumVecElts = VT.getVectorNumElements();
8532   if (NumVecElts != 4 && NumVecElts != 2)
8533     return SDValue();
8534   SDValue SplatVal = StVal.getOperand(1);
8535   unsigned RemainInsertElts = NumVecElts - 1;
8536
8537   // Check that this is a splat.
8538   while (--RemainInsertElts) {
8539     SDValue NextInsertElt = StVal.getOperand(0);
8540     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8541       return SDValue();
8542     if (NextInsertElt.getOperand(1) != SplatVal)
8543       return SDValue();
8544     StVal = NextInsertElt;
8545   }
8546   unsigned OrigAlignment = St->getAlignment();
8547   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8548   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8549
8550   // Create scalar stores. This is at least as good as the code sequence for a
8551   // split unaligned store which is a dup.s, ext.b, and two stores.
8552   // Most of the time the three stores should be replaced by store pair
8553   // instructions (stp).
8554   SDLoc DL(St);
8555   SDValue BasePtr = St->getBasePtr();
8556   SDValue NewST1 =
8557       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8558                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8559
8560   unsigned Offset = EltOffset;
8561   while (--NumVecElts) {
8562     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8563                                     DAG.getConstant(Offset, DL, MVT::i64));
8564     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8565                           St->getPointerInfo(), St->isVolatile(),
8566                           St->isNonTemporal(), Alignment);
8567     Offset += EltOffset;
8568   }
8569   return NewST1;
8570 }
8571
8572 static SDValue performSTORECombine(SDNode *N,
8573                                    TargetLowering::DAGCombinerInfo &DCI,
8574                                    SelectionDAG &DAG,
8575                                    const AArch64Subtarget *Subtarget) {
8576   if (!DCI.isBeforeLegalize())
8577     return SDValue();
8578
8579   StoreSDNode *S = cast<StoreSDNode>(N);
8580   if (S->isVolatile())
8581     return SDValue();
8582
8583   // FIXME: The logic for deciding if an unaligned store should be split should
8584   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8585   // a call to that function here.
8586
8587   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8588   // page boundaries. We want to split such stores.
8589   if (!Subtarget->isCyclone())
8590     return SDValue();
8591
8592   // Don't split at -Oz.
8593   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8594     return SDValue();
8595
8596   SDValue StVal = S->getValue();
8597   EVT VT = StVal.getValueType();
8598
8599   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8600   // those up regresses performance on micro-benchmarks and olden/bh.
8601   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8602     return SDValue();
8603
8604   // Split unaligned 16B stores. They are terrible for performance.
8605   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8606   // extensions can use this to mark that it does not want splitting to happen
8607   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8608   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8609   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8610       S->getAlignment() <= 2)
8611     return SDValue();
8612
8613   // If we get a splat of a scalar convert this vector store to a store of
8614   // scalars. They will be merged into store pairs thereby removing two
8615   // instructions.
8616   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8617     return ReplacedSplat;
8618
8619   SDLoc DL(S);
8620   unsigned NumElts = VT.getVectorNumElements() / 2;
8621   // Split VT into two.
8622   EVT HalfVT =
8623       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8624   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8625                                    DAG.getConstant(0, DL, MVT::i64));
8626   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8627                                    DAG.getConstant(NumElts, DL, MVT::i64));
8628   SDValue BasePtr = S->getBasePtr();
8629   SDValue NewST1 =
8630       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8631                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8632   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8633                                   DAG.getConstant(8, DL, MVT::i64));
8634   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8635                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8636                       S->getAlignment());
8637 }
8638
8639 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8640 /// post-increment LD1R.
8641 static SDValue performPostLD1Combine(SDNode *N,
8642                                      TargetLowering::DAGCombinerInfo &DCI,
8643                                      bool IsLaneOp) {
8644   if (DCI.isBeforeLegalizeOps())
8645     return SDValue();
8646
8647   SelectionDAG &DAG = DCI.DAG;
8648   EVT VT = N->getValueType(0);
8649
8650   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8651   SDNode *LD = N->getOperand(LoadIdx).getNode();
8652   // If it is not LOAD, can not do such combine.
8653   if (LD->getOpcode() != ISD::LOAD)
8654     return SDValue();
8655
8656   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8657   EVT MemVT = LoadSDN->getMemoryVT();
8658   // Check if memory operand is the same type as the vector element.
8659   if (MemVT != VT.getVectorElementType())
8660     return SDValue();
8661
8662   // Check if there are other uses. If so, do not combine as it will introduce
8663   // an extra load.
8664   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8665        ++UI) {
8666     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8667       continue;
8668     if (*UI != N)
8669       return SDValue();
8670   }
8671
8672   SDValue Addr = LD->getOperand(1);
8673   SDValue Vector = N->getOperand(0);
8674   // Search for a use of the address operand that is an increment.
8675   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8676        Addr.getNode()->use_end(); UI != UE; ++UI) {
8677     SDNode *User = *UI;
8678     if (User->getOpcode() != ISD::ADD
8679         || UI.getUse().getResNo() != Addr.getResNo())
8680       continue;
8681
8682     // Check that the add is independent of the load.  Otherwise, folding it
8683     // would create a cycle.
8684     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8685       continue;
8686     // Also check that add is not used in the vector operand.  This would also
8687     // create a cycle.
8688     if (User->isPredecessorOf(Vector.getNode()))
8689       continue;
8690
8691     // If the increment is a constant, it must match the memory ref size.
8692     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8693     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8694       uint32_t IncVal = CInc->getZExtValue();
8695       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8696       if (IncVal != NumBytes)
8697         continue;
8698       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8699     }
8700
8701     // Finally, check that the vector doesn't depend on the load.
8702     // Again, this would create a cycle.
8703     // The load depending on the vector is fine, as that's the case for the
8704     // LD1*post we'll eventually generate anyway.
8705     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8706       continue;
8707
8708     SmallVector<SDValue, 8> Ops;
8709     Ops.push_back(LD->getOperand(0));  // Chain
8710     if (IsLaneOp) {
8711       Ops.push_back(Vector);           // The vector to be inserted
8712       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8713     }
8714     Ops.push_back(Addr);
8715     Ops.push_back(Inc);
8716
8717     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8718     SDVTList SDTys = DAG.getVTList(Tys);
8719     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8720     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8721                                            MemVT,
8722                                            LoadSDN->getMemOperand());
8723
8724     // Update the uses.
8725     SmallVector<SDValue, 2> NewResults;
8726     NewResults.push_back(SDValue(LD, 0));             // The result of load
8727     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8728     DCI.CombineTo(LD, NewResults);
8729     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8730     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8731
8732     break;
8733   }
8734   return SDValue();
8735 }
8736
8737 /// This function handles the log2-shuffle pattern produced by the
8738 /// LoopVectorizer for the across vector reduction. It consists of
8739 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8740 /// are reduced, where s is an induction variable from 0 to
8741 /// log2(NumVectorElements).
8742 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8743                                                      unsigned Op,
8744                                                      SelectionDAG &DAG) {
8745   EVT VTy = OpV->getOperand(0).getValueType();
8746   if (!VTy.isVector())
8747     return SDValue();
8748
8749   int NumVecElts = VTy.getVectorNumElements();
8750   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8751     if (NumVecElts != 4)
8752       return SDValue();
8753   } else {
8754     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8755       return SDValue();
8756   }
8757
8758   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8759   SDValue PreOp = OpV;
8760   // Iterate over each step of the across vector reduction.
8761   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8762     SDValue CurOp = PreOp.getOperand(0);
8763     SDValue Shuffle = PreOp.getOperand(1);
8764     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8765       // Try to swap the 1st and 2nd operand as add and min/max instructions
8766       // are commutative.
8767       CurOp = PreOp.getOperand(1);
8768       Shuffle = PreOp.getOperand(0);
8769       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8770         return SDValue();
8771     }
8772
8773     // Check if the input vector is fed by the operator we want to handle,
8774     // except the last step; the very first input vector is not necessarily
8775     // the same operator we are handling.
8776     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8777       return SDValue();
8778
8779     // Check if it forms one step of the across vector reduction.
8780     // E.g.,
8781     //   %cur = add %1, %0
8782     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8783     //   %pre = add %cur, %shuffle
8784     if (Shuffle.getOperand(0) != CurOp)
8785       return SDValue();
8786
8787     int NumMaskElts = 1 << CurStep;
8788     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8789     // Check mask values in each step.
8790     // We expect the shuffle mask in each step follows a specific pattern
8791     // denoted here by the <M, U> form, where M is a sequence of integers
8792     // starting from NumMaskElts, increasing by 1, and the number integers
8793     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8794     // of undef in U should be NumVecElts - NumMaskElts.
8795     // E.g., for <8 x i16>, mask values in each step should be :
8796     //   step 0 : <1,u,u,u,u,u,u,u>
8797     //   step 1 : <2,3,u,u,u,u,u,u>
8798     //   step 2 : <4,5,6,7,u,u,u,u>
8799     for (int i = 0; i < NumVecElts; ++i)
8800       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8801           (i >= NumMaskElts && !(Mask[i] < 0)))
8802         return SDValue();
8803
8804     PreOp = CurOp;
8805   }
8806   unsigned Opcode;
8807   bool IsIntrinsic = false;
8808
8809   switch (Op) {
8810   default:
8811     llvm_unreachable("Unexpected operator for across vector reduction");
8812   case ISD::ADD:
8813     Opcode = AArch64ISD::UADDV;
8814     break;
8815   case ISD::SMAX:
8816     Opcode = AArch64ISD::SMAXV;
8817     break;
8818   case ISD::UMAX:
8819     Opcode = AArch64ISD::UMAXV;
8820     break;
8821   case ISD::SMIN:
8822     Opcode = AArch64ISD::SMINV;
8823     break;
8824   case ISD::UMIN:
8825     Opcode = AArch64ISD::UMINV;
8826     break;
8827   case ISD::FMAXNUM:
8828     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8829     IsIntrinsic = true;
8830     break;
8831   case ISD::FMINNUM:
8832     Opcode = Intrinsic::aarch64_neon_fminnmv;
8833     IsIntrinsic = true;
8834     break;
8835   }
8836   SDLoc DL(N);
8837
8838   return IsIntrinsic
8839              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8840                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8841              : DAG.getNode(
8842                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8843                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8844                    DAG.getConstant(0, DL, MVT::i64));
8845 }
8846
8847 /// Target-specific DAG combine for the across vector min/max reductions.
8848 /// This function specifically handles the final clean-up step of the vector
8849 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8850 /// pattern, which narrows down and finds the final min/max value from all
8851 /// elements of the vector.
8852 /// For example, for a <16 x i8> vector :
8853 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8854 ///   %smax0 = smax %arr, svn0
8855 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8856 ///   %smax1 = smax %smax0, %svn1
8857 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8858 ///   %smax2 = smax %smax1, svn2
8859 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8860 ///   %sc = setcc %smax2, %svn3, gt
8861 ///   %n0 = extract_vector_elt %sc, #0
8862 ///   %n1 = extract_vector_elt %smax2, #0
8863 ///   %n2 = extract_vector_elt $smax2, #1
8864 ///   %result = select %n0, %n1, n2
8865 ///     becomes :
8866 ///   %1 = smaxv %0
8867 ///   %result = extract_vector_elt %1, 0
8868 static SDValue
8869 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8870                                         const AArch64Subtarget *Subtarget) {
8871   if (!Subtarget->hasNEON())
8872     return SDValue();
8873
8874   SDValue N0 = N->getOperand(0);
8875   SDValue IfTrue = N->getOperand(1);
8876   SDValue IfFalse = N->getOperand(2);
8877
8878   // Check if the SELECT merges up the final result of the min/max
8879   // from a vector.
8880   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8881       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8882       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8883     return SDValue();
8884
8885   // Expect N0 is fed by SETCC.
8886   SDValue SetCC = N0.getOperand(0);
8887   EVT SetCCVT = SetCC.getValueType();
8888   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8889       SetCCVT.getVectorElementType() != MVT::i1)
8890     return SDValue();
8891
8892   SDValue VectorOp = SetCC.getOperand(0);
8893   unsigned Op = VectorOp->getOpcode();
8894   // Check if the input vector is fed by the operator we want to handle.
8895   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8896       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8897     return SDValue();
8898
8899   EVT VTy = VectorOp.getValueType();
8900   if (!VTy.isVector())
8901     return SDValue();
8902
8903   if (VTy.getSizeInBits() < 64)
8904     return SDValue();
8905
8906   EVT EltTy = VTy.getVectorElementType();
8907   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8908     if (EltTy != MVT::f32)
8909       return SDValue();
8910   } else {
8911     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8912       return SDValue();
8913   }
8914
8915   // Check if extracting from the same vector.
8916   // For example,
8917   //   %sc = setcc %vector, %svn1, gt
8918   //   %n0 = extract_vector_elt %sc, #0
8919   //   %n1 = extract_vector_elt %vector, #0
8920   //   %n2 = extract_vector_elt $vector, #1
8921   if (!(VectorOp == IfTrue->getOperand(0) &&
8922         VectorOp == IfFalse->getOperand(0)))
8923     return SDValue();
8924
8925   // Check if the condition code is matched with the operator type.
8926   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8927   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8928       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8929       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8930       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8931       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8932        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8933        CC != ISD::SETGE) ||
8934       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8935        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8936        CC != ISD::SETLE))
8937     return SDValue();
8938
8939   // Expect to check only lane 0 from the vector SETCC.
8940   if (!isa<ConstantSDNode>(N0.getOperand(1)) ||
8941       cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue() != 0)
8942     return SDValue();
8943
8944   // Expect to extract the true value from lane 0.
8945   if (!isa<ConstantSDNode>(IfTrue.getOperand(1)) ||
8946       cast<ConstantSDNode>(IfTrue.getOperand(1))->getZExtValue() != 0)
8947     return SDValue();
8948
8949   // Expect to extract the false value from lane 1.
8950   if (!isa<ConstantSDNode>(IfFalse.getOperand(1)) ||
8951       cast<ConstantSDNode>(IfFalse.getOperand(1))->getZExtValue() != 1)
8952     return SDValue();
8953
8954   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8955 }
8956
8957 /// Target-specific DAG combine for the across vector add reduction.
8958 /// This function specifically handles the final clean-up step of the vector
8959 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8960 /// pattern, which adds all elements of a vector together.
8961 /// For example, for a <4 x i32> vector :
8962 ///   %1 = vector_shuffle %0, <2,3,u,u>
8963 ///   %2 = add %0, %1
8964 ///   %3 = vector_shuffle %2, <1,u,u,u>
8965 ///   %4 = add %2, %3
8966 ///   %result = extract_vector_elt %4, 0
8967 /// becomes :
8968 ///   %0 = uaddv %0
8969 ///   %result = extract_vector_elt %0, 0
8970 static SDValue
8971 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
8972                                      const AArch64Subtarget *Subtarget) {
8973   if (!Subtarget->hasNEON())
8974     return SDValue();
8975   SDValue N0 = N->getOperand(0);
8976   SDValue N1 = N->getOperand(1);
8977
8978   // Check if the input vector is fed by the ADD.
8979   if (N0->getOpcode() != ISD::ADD)
8980     return SDValue();
8981
8982   // The vector extract idx must constant zero because we only expect the final
8983   // result of the reduction is placed in lane 0.
8984   if (!isa<ConstantSDNode>(N1) || cast<ConstantSDNode>(N1)->getZExtValue() != 0)
8985     return SDValue();
8986
8987   EVT VTy = N0.getValueType();
8988   if (!VTy.isVector())
8989     return SDValue();
8990
8991   EVT EltTy = VTy.getVectorElementType();
8992   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8993     return SDValue();
8994
8995   if (VTy.getSizeInBits() < 64)
8996     return SDValue();
8997
8998   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
8999 }
9000
9001 /// Target-specific DAG combine function for NEON load/store intrinsics
9002 /// to merge base address updates.
9003 static SDValue performNEONPostLDSTCombine(SDNode *N,
9004                                           TargetLowering::DAGCombinerInfo &DCI,
9005                                           SelectionDAG &DAG) {
9006   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9007     return SDValue();
9008
9009   unsigned AddrOpIdx = N->getNumOperands() - 1;
9010   SDValue Addr = N->getOperand(AddrOpIdx);
9011
9012   // Search for a use of the address operand that is an increment.
9013   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9014        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9015     SDNode *User = *UI;
9016     if (User->getOpcode() != ISD::ADD ||
9017         UI.getUse().getResNo() != Addr.getResNo())
9018       continue;
9019
9020     // Check that the add is independent of the load/store.  Otherwise, folding
9021     // it would create a cycle.
9022     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9023       continue;
9024
9025     // Find the new opcode for the updating load/store.
9026     bool IsStore = false;
9027     bool IsLaneOp = false;
9028     bool IsDupOp = false;
9029     unsigned NewOpc = 0;
9030     unsigned NumVecs = 0;
9031     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9032     switch (IntNo) {
9033     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9034     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9035       NumVecs = 2; break;
9036     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9037       NumVecs = 3; break;
9038     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9039       NumVecs = 4; break;
9040     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9041       NumVecs = 2; IsStore = true; break;
9042     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9043       NumVecs = 3; IsStore = true; break;
9044     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9045       NumVecs = 4; IsStore = true; break;
9046     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9047       NumVecs = 2; break;
9048     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9049       NumVecs = 3; break;
9050     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9051       NumVecs = 4; break;
9052     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9053       NumVecs = 2; IsStore = true; break;
9054     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9055       NumVecs = 3; IsStore = true; break;
9056     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9057       NumVecs = 4; IsStore = true; break;
9058     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9059       NumVecs = 2; IsDupOp = true; break;
9060     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9061       NumVecs = 3; IsDupOp = true; break;
9062     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9063       NumVecs = 4; IsDupOp = true; break;
9064     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9065       NumVecs = 2; IsLaneOp = true; break;
9066     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9067       NumVecs = 3; IsLaneOp = true; break;
9068     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9069       NumVecs = 4; IsLaneOp = true; break;
9070     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9071       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9072     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9073       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9074     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9075       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9076     }
9077
9078     EVT VecTy;
9079     if (IsStore)
9080       VecTy = N->getOperand(2).getValueType();
9081     else
9082       VecTy = N->getValueType(0);
9083
9084     // If the increment is a constant, it must match the memory ref size.
9085     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9086     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9087       uint32_t IncVal = CInc->getZExtValue();
9088       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9089       if (IsLaneOp || IsDupOp)
9090         NumBytes /= VecTy.getVectorNumElements();
9091       if (IncVal != NumBytes)
9092         continue;
9093       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9094     }
9095     SmallVector<SDValue, 8> Ops;
9096     Ops.push_back(N->getOperand(0)); // Incoming chain
9097     // Load lane and store have vector list as input.
9098     if (IsLaneOp || IsStore)
9099       for (unsigned i = 2; i < AddrOpIdx; ++i)
9100         Ops.push_back(N->getOperand(i));
9101     Ops.push_back(Addr); // Base register
9102     Ops.push_back(Inc);
9103
9104     // Return Types.
9105     EVT Tys[6];
9106     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9107     unsigned n;
9108     for (n = 0; n < NumResultVecs; ++n)
9109       Tys[n] = VecTy;
9110     Tys[n++] = MVT::i64;  // Type of write back register
9111     Tys[n] = MVT::Other;  // Type of the chain
9112     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9113
9114     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9115     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9116                                            MemInt->getMemoryVT(),
9117                                            MemInt->getMemOperand());
9118
9119     // Update the uses.
9120     std::vector<SDValue> NewResults;
9121     for (unsigned i = 0; i < NumResultVecs; ++i) {
9122       NewResults.push_back(SDValue(UpdN.getNode(), i));
9123     }
9124     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9125     DCI.CombineTo(N, NewResults);
9126     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9127
9128     break;
9129   }
9130   return SDValue();
9131 }
9132
9133 // Checks to see if the value is the prescribed width and returns information
9134 // about its extension mode.
9135 static
9136 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9137   ExtType = ISD::NON_EXTLOAD;
9138   switch(V.getNode()->getOpcode()) {
9139   default:
9140     return false;
9141   case ISD::LOAD: {
9142     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9143     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9144        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9145       ExtType = LoadNode->getExtensionType();
9146       return true;
9147     }
9148     return false;
9149   }
9150   case ISD::AssertSext: {
9151     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9152     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9153        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9154       ExtType = ISD::SEXTLOAD;
9155       return true;
9156     }
9157     return false;
9158   }
9159   case ISD::AssertZext: {
9160     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9161     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9162        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9163       ExtType = ISD::ZEXTLOAD;
9164       return true;
9165     }
9166     return false;
9167   }
9168   case ISD::Constant:
9169   case ISD::TargetConstant: {
9170     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9171         1LL << (width - 1))
9172       return true;
9173     return false;
9174   }
9175   }
9176
9177   return true;
9178 }
9179
9180 // This function does a whole lot of voodoo to determine if the tests are
9181 // equivalent without and with a mask. Essentially what happens is that given a
9182 // DAG resembling:
9183 //
9184 //  +-------------+ +-------------+ +-------------+ +-------------+
9185 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9186 //  +-------------+ +-------------+ +-------------+ +-------------+
9187 //           |           |           |               |
9188 //           V           V           |    +----------+
9189 //          +-------------+  +----+  |    |
9190 //          |     ADD     |  |0xff|  |    |
9191 //          +-------------+  +----+  |    |
9192 //                  |           |    |    |
9193 //                  V           V    |    |
9194 //                 +-------------+   |    |
9195 //                 |     AND     |   |    |
9196 //                 +-------------+   |    |
9197 //                      |            |    |
9198 //                      +-----+      |    |
9199 //                            |      |    |
9200 //                            V      V    V
9201 //                           +-------------+
9202 //                           |     CMP     |
9203 //                           +-------------+
9204 //
9205 // The AND node may be safely removed for some combinations of inputs. In
9206 // particular we need to take into account the extension type of the Input,
9207 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9208 // width of the input (this can work for any width inputs, the above graph is
9209 // specific to 8 bits.
9210 //
9211 // The specific equations were worked out by generating output tables for each
9212 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9213 // problem was simplified by working with 4 bit inputs, which means we only
9214 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9215 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9216 // patterns present in both extensions (0,7). For every distinct set of
9217 // AddConstant and CompConstants bit patterns we can consider the masked and
9218 // unmasked versions to be equivalent if the result of this function is true for
9219 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9220 //
9221 //   sub      w8, w0, w1
9222 //   and      w10, w8, #0x0f
9223 //   cmp      w8, w2
9224 //   cset     w9, AArch64CC
9225 //   cmp      w10, w2
9226 //   cset     w11, AArch64CC
9227 //   cmp      w9, w11
9228 //   cset     w0, eq
9229 //   ret
9230 //
9231 // Since the above function shows when the outputs are equivalent it defines
9232 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9233 // would be expensive to run during compiles. The equations below were written
9234 // in a test harness that confirmed they gave equivalent outputs to the above
9235 // for all inputs function, so they can be used determine if the removal is
9236 // legal instead.
9237 //
9238 // isEquivalentMaskless() is the code for testing if the AND can be removed
9239 // factored out of the DAG recognition as the DAG can take several forms.
9240
9241 static
9242 bool isEquivalentMaskless(unsigned CC, unsigned width,
9243                           ISD::LoadExtType ExtType, signed AddConstant,
9244                           signed CompConstant) {
9245   // By being careful about our equations and only writing the in term
9246   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9247   // make them generally applicable to all bit widths.
9248   signed MaxUInt = (1 << width);
9249
9250   // For the purposes of these comparisons sign extending the type is
9251   // equivalent to zero extending the add and displacing it by half the integer
9252   // width. Provided we are careful and make sure our equations are valid over
9253   // the whole range we can just adjust the input and avoid writing equations
9254   // for sign extended inputs.
9255   if (ExtType == ISD::SEXTLOAD)
9256     AddConstant -= (1 << (width-1));
9257
9258   switch(CC) {
9259   case AArch64CC::LE:
9260   case AArch64CC::GT: {
9261     if ((AddConstant == 0) ||
9262         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9263         (AddConstant >= 0 && CompConstant < 0) ||
9264         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9265       return true;
9266   } break;
9267   case AArch64CC::LT:
9268   case AArch64CC::GE: {
9269     if ((AddConstant == 0) ||
9270         (AddConstant >= 0 && CompConstant <= 0) ||
9271         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9272       return true;
9273   } break;
9274   case AArch64CC::HI:
9275   case AArch64CC::LS: {
9276     if ((AddConstant >= 0 && CompConstant < 0) ||
9277        (AddConstant <= 0 && CompConstant >= -1 &&
9278         CompConstant < AddConstant + MaxUInt))
9279       return true;
9280   } break;
9281   case AArch64CC::PL:
9282   case AArch64CC::MI: {
9283     if ((AddConstant == 0) ||
9284         (AddConstant > 0 && CompConstant <= 0) ||
9285         (AddConstant < 0 && CompConstant <= AddConstant))
9286       return true;
9287   } break;
9288   case AArch64CC::LO:
9289   case AArch64CC::HS: {
9290     if ((AddConstant >= 0 && CompConstant <= 0) ||
9291         (AddConstant <= 0 && CompConstant >= 0 &&
9292          CompConstant <= AddConstant + MaxUInt))
9293       return true;
9294   } break;
9295   case AArch64CC::EQ:
9296   case AArch64CC::NE: {
9297     if ((AddConstant > 0 && CompConstant < 0) ||
9298         (AddConstant < 0 && CompConstant >= 0 &&
9299          CompConstant < AddConstant + MaxUInt) ||
9300         (AddConstant >= 0 && CompConstant >= 0 &&
9301          CompConstant >= AddConstant) ||
9302         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9303
9304       return true;
9305   } break;
9306   case AArch64CC::VS:
9307   case AArch64CC::VC:
9308   case AArch64CC::AL:
9309   case AArch64CC::NV:
9310     return true;
9311   case AArch64CC::Invalid:
9312     break;
9313   }
9314
9315   return false;
9316 }
9317
9318 static
9319 SDValue performCONDCombine(SDNode *N,
9320                            TargetLowering::DAGCombinerInfo &DCI,
9321                            SelectionDAG &DAG, unsigned CCIndex,
9322                            unsigned CmpIndex) {
9323   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9324   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9325   unsigned CondOpcode = SubsNode->getOpcode();
9326
9327   if (CondOpcode != AArch64ISD::SUBS)
9328     return SDValue();
9329
9330   // There is a SUBS feeding this condition. Is it fed by a mask we can
9331   // use?
9332
9333   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9334   unsigned MaskBits = 0;
9335
9336   if (AndNode->getOpcode() != ISD::AND)
9337     return SDValue();
9338
9339   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9340     uint32_t CNV = CN->getZExtValue();
9341     if (CNV == 255)
9342       MaskBits = 8;
9343     else if (CNV == 65535)
9344       MaskBits = 16;
9345   }
9346
9347   if (!MaskBits)
9348     return SDValue();
9349
9350   SDValue AddValue = AndNode->getOperand(0);
9351
9352   if (AddValue.getOpcode() != ISD::ADD)
9353     return SDValue();
9354
9355   // The basic dag structure is correct, grab the inputs and validate them.
9356
9357   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9358   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9359   SDValue SubsInputValue = SubsNode->getOperand(1);
9360
9361   // The mask is present and the provenance of all the values is a smaller type,
9362   // lets see if the mask is superfluous.
9363
9364   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9365       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9366     return SDValue();
9367
9368   ISD::LoadExtType ExtType;
9369
9370   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9371       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9372       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9373     return SDValue();
9374
9375   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9376                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9377                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9378     return SDValue();
9379
9380   // The AND is not necessary, remove it.
9381
9382   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9383                                SubsNode->getValueType(1));
9384   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9385
9386   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9387   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9388
9389   return SDValue(N, 0);
9390 }
9391
9392 // Optimize compare with zero and branch.
9393 static SDValue performBRCONDCombine(SDNode *N,
9394                                     TargetLowering::DAGCombinerInfo &DCI,
9395                                     SelectionDAG &DAG) {
9396   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9397   if (NV.getNode())
9398     N = NV.getNode();
9399   SDValue Chain = N->getOperand(0);
9400   SDValue Dest = N->getOperand(1);
9401   SDValue CCVal = N->getOperand(2);
9402   SDValue Cmp = N->getOperand(3);
9403
9404   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9405   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9406   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9407     return SDValue();
9408
9409   unsigned CmpOpc = Cmp.getOpcode();
9410   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9411     return SDValue();
9412
9413   // Only attempt folding if there is only one use of the flag and no use of the
9414   // value.
9415   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9416     return SDValue();
9417
9418   SDValue LHS = Cmp.getOperand(0);
9419   SDValue RHS = Cmp.getOperand(1);
9420
9421   assert(LHS.getValueType() == RHS.getValueType() &&
9422          "Expected the value type to be the same for both operands!");
9423   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9424     return SDValue();
9425
9426   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9427     std::swap(LHS, RHS);
9428
9429   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9430     return SDValue();
9431
9432   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9433       LHS.getOpcode() == ISD::SRL)
9434     return SDValue();
9435
9436   // Fold the compare into the branch instruction.
9437   SDValue BR;
9438   if (CC == AArch64CC::EQ)
9439     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9440   else
9441     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9442
9443   // Do not add new nodes to DAG combiner worklist.
9444   DCI.CombineTo(N, BR, false);
9445
9446   return SDValue();
9447 }
9448
9449 // vselect (v1i1 setcc) ->
9450 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9451 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9452 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9453 // such VSELECT.
9454 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9455   SDValue N0 = N->getOperand(0);
9456   EVT CCVT = N0.getValueType();
9457
9458   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9459       CCVT.getVectorElementType() != MVT::i1)
9460     return SDValue();
9461
9462   EVT ResVT = N->getValueType(0);
9463   EVT CmpVT = N0.getOperand(0).getValueType();
9464   // Only combine when the result type is of the same size as the compared
9465   // operands.
9466   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9467     return SDValue();
9468
9469   SDValue IfTrue = N->getOperand(1);
9470   SDValue IfFalse = N->getOperand(2);
9471   SDValue SetCC =
9472       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9473                    N0.getOperand(0), N0.getOperand(1),
9474                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9475   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9476                      IfTrue, IfFalse);
9477 }
9478
9479 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9480 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9481 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9482 /// with a vector one followed by a DUP shuffle on the result.
9483 static SDValue performSelectCombine(SDNode *N,
9484                                     TargetLowering::DAGCombinerInfo &DCI) {
9485   SelectionDAG &DAG = DCI.DAG;
9486   SDValue N0 = N->getOperand(0);
9487   EVT ResVT = N->getValueType(0);
9488
9489   if (N0.getOpcode() != ISD::SETCC)
9490     return SDValue();
9491
9492   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9493   // scalar SetCCResultType. We also don't expect vectors, because we assume
9494   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9495   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9496          "Scalar-SETCC feeding SELECT has unexpected result type!");
9497
9498   // If NumMaskElts == 0, the comparison is larger than select result. The
9499   // largest real NEON comparison is 64-bits per lane, which means the result is
9500   // at most 32-bits and an illegal vector. Just bail out for now.
9501   EVT SrcVT = N0.getOperand(0).getValueType();
9502
9503   // Don't try to do this optimization when the setcc itself has i1 operands.
9504   // There are no legal vectors of i1, so this would be pointless.
9505   if (SrcVT == MVT::i1)
9506     return SDValue();
9507
9508   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9509   if (!ResVT.isVector() || NumMaskElts == 0)
9510     return SDValue();
9511
9512   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9513   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9514
9515   // Also bail out if the vector CCVT isn't the same size as ResVT.
9516   // This can happen if the SETCC operand size doesn't divide the ResVT size
9517   // (e.g., f64 vs v3f32).
9518   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9519     return SDValue();
9520
9521   // Make sure we didn't create illegal types, if we're not supposed to.
9522   assert(DCI.isBeforeLegalize() ||
9523          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9524
9525   // First perform a vector comparison, where lane 0 is the one we're interested
9526   // in.
9527   SDLoc DL(N0);
9528   SDValue LHS =
9529       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9530   SDValue RHS =
9531       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9532   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9533
9534   // Now duplicate the comparison mask we want across all other lanes.
9535   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9536   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9537   Mask = DAG.getNode(ISD::BITCAST, DL,
9538                      ResVT.changeVectorElementTypeToInteger(), Mask);
9539
9540   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9541 }
9542
9543 /// Get rid of unnecessary NVCASTs (that don't change the type).
9544 static SDValue performNVCASTCombine(SDNode *N) {
9545   if (N->getValueType(0) == N->getOperand(0).getValueType())
9546     return N->getOperand(0);
9547
9548   return SDValue();
9549 }
9550
9551 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9552                                                  DAGCombinerInfo &DCI) const {
9553   SelectionDAG &DAG = DCI.DAG;
9554   switch (N->getOpcode()) {
9555   default:
9556     break;
9557   case ISD::ADD:
9558   case ISD::SUB:
9559     return performAddSubLongCombine(N, DCI, DAG);
9560   case ISD::XOR:
9561     return performXorCombine(N, DAG, DCI, Subtarget);
9562   case ISD::MUL:
9563     return performMulCombine(N, DAG, DCI, Subtarget);
9564   case ISD::SINT_TO_FP:
9565   case ISD::UINT_TO_FP:
9566     return performIntToFpCombine(N, DAG, Subtarget);
9567   case ISD::FP_TO_SINT:
9568   case ISD::FP_TO_UINT:
9569     return performFpToIntCombine(N, DAG, Subtarget);
9570   case ISD::FDIV:
9571     return performFDivCombine(N, DAG, Subtarget);
9572   case ISD::OR:
9573     return performORCombine(N, DCI, Subtarget);
9574   case ISD::INTRINSIC_WO_CHAIN:
9575     return performIntrinsicCombine(N, DCI, Subtarget);
9576   case ISD::ANY_EXTEND:
9577   case ISD::ZERO_EXTEND:
9578   case ISD::SIGN_EXTEND:
9579     return performExtendCombine(N, DCI, DAG);
9580   case ISD::BITCAST:
9581     return performBitcastCombine(N, DCI, DAG);
9582   case ISD::CONCAT_VECTORS:
9583     return performConcatVectorsCombine(N, DCI, DAG);
9584   case ISD::SELECT: {
9585     SDValue RV = performSelectCombine(N, DCI);
9586     if (!RV.getNode())
9587       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9588     return RV;
9589   }
9590   case ISD::VSELECT:
9591     return performVSelectCombine(N, DCI.DAG);
9592   case ISD::STORE:
9593     return performSTORECombine(N, DCI, DAG, Subtarget);
9594   case AArch64ISD::BRCOND:
9595     return performBRCONDCombine(N, DCI, DAG);
9596   case AArch64ISD::CSEL:
9597     return performCONDCombine(N, DCI, DAG, 2, 3);
9598   case AArch64ISD::DUP:
9599     return performPostLD1Combine(N, DCI, false);
9600   case AArch64ISD::NVCAST:
9601     return performNVCASTCombine(N);
9602   case ISD::INSERT_VECTOR_ELT:
9603     return performPostLD1Combine(N, DCI, true);
9604   case ISD::EXTRACT_VECTOR_ELT:
9605     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9606   case ISD::INTRINSIC_VOID:
9607   case ISD::INTRINSIC_W_CHAIN:
9608     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9609     case Intrinsic::aarch64_neon_ld2:
9610     case Intrinsic::aarch64_neon_ld3:
9611     case Intrinsic::aarch64_neon_ld4:
9612     case Intrinsic::aarch64_neon_ld1x2:
9613     case Intrinsic::aarch64_neon_ld1x3:
9614     case Intrinsic::aarch64_neon_ld1x4:
9615     case Intrinsic::aarch64_neon_ld2lane:
9616     case Intrinsic::aarch64_neon_ld3lane:
9617     case Intrinsic::aarch64_neon_ld4lane:
9618     case Intrinsic::aarch64_neon_ld2r:
9619     case Intrinsic::aarch64_neon_ld3r:
9620     case Intrinsic::aarch64_neon_ld4r:
9621     case Intrinsic::aarch64_neon_st2:
9622     case Intrinsic::aarch64_neon_st3:
9623     case Intrinsic::aarch64_neon_st4:
9624     case Intrinsic::aarch64_neon_st1x2:
9625     case Intrinsic::aarch64_neon_st1x3:
9626     case Intrinsic::aarch64_neon_st1x4:
9627     case Intrinsic::aarch64_neon_st2lane:
9628     case Intrinsic::aarch64_neon_st3lane:
9629     case Intrinsic::aarch64_neon_st4lane:
9630       return performNEONPostLDSTCombine(N, DCI, DAG);
9631     default:
9632       break;
9633     }
9634   }
9635   return SDValue();
9636 }
9637
9638 // Check if the return value is used as only a return value, as otherwise
9639 // we can't perform a tail-call. In particular, we need to check for
9640 // target ISD nodes that are returns and any other "odd" constructs
9641 // that the generic analysis code won't necessarily catch.
9642 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9643                                                SDValue &Chain) const {
9644   if (N->getNumValues() != 1)
9645     return false;
9646   if (!N->hasNUsesOfValue(1, 0))
9647     return false;
9648
9649   SDValue TCChain = Chain;
9650   SDNode *Copy = *N->use_begin();
9651   if (Copy->getOpcode() == ISD::CopyToReg) {
9652     // If the copy has a glue operand, we conservatively assume it isn't safe to
9653     // perform a tail call.
9654     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9655         MVT::Glue)
9656       return false;
9657     TCChain = Copy->getOperand(0);
9658   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9659     return false;
9660
9661   bool HasRet = false;
9662   for (SDNode *Node : Copy->uses()) {
9663     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9664       return false;
9665     HasRet = true;
9666   }
9667
9668   if (!HasRet)
9669     return false;
9670
9671   Chain = TCChain;
9672   return true;
9673 }
9674
9675 // Return whether the an instruction can potentially be optimized to a tail
9676 // call. This will cause the optimizers to attempt to move, or duplicate,
9677 // return instructions to help enable tail call optimizations for this
9678 // instruction.
9679 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9680   if (!CI->isTailCall())
9681     return false;
9682
9683   return true;
9684 }
9685
9686 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9687                                                    SDValue &Offset,
9688                                                    ISD::MemIndexedMode &AM,
9689                                                    bool &IsInc,
9690                                                    SelectionDAG &DAG) const {
9691   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9692     return false;
9693
9694   Base = Op->getOperand(0);
9695   // All of the indexed addressing mode instructions take a signed
9696   // 9 bit immediate offset.
9697   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9698     int64_t RHSC = (int64_t)RHS->getZExtValue();
9699     if (RHSC >= 256 || RHSC <= -256)
9700       return false;
9701     IsInc = (Op->getOpcode() == ISD::ADD);
9702     Offset = Op->getOperand(1);
9703     return true;
9704   }
9705   return false;
9706 }
9707
9708 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9709                                                       SDValue &Offset,
9710                                                       ISD::MemIndexedMode &AM,
9711                                                       SelectionDAG &DAG) const {
9712   EVT VT;
9713   SDValue Ptr;
9714   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9715     VT = LD->getMemoryVT();
9716     Ptr = LD->getBasePtr();
9717   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9718     VT = ST->getMemoryVT();
9719     Ptr = ST->getBasePtr();
9720   } else
9721     return false;
9722
9723   bool IsInc;
9724   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9725     return false;
9726   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9727   return true;
9728 }
9729
9730 bool AArch64TargetLowering::getPostIndexedAddressParts(
9731     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9732     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9733   EVT VT;
9734   SDValue Ptr;
9735   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9736     VT = LD->getMemoryVT();
9737     Ptr = LD->getBasePtr();
9738   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9739     VT = ST->getMemoryVT();
9740     Ptr = ST->getBasePtr();
9741   } else
9742     return false;
9743
9744   bool IsInc;
9745   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9746     return false;
9747   // Post-indexing updates the base, so it's not a valid transform
9748   // if that's not the same as the load's pointer.
9749   if (Ptr != Base)
9750     return false;
9751   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9752   return true;
9753 }
9754
9755 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9756                                   SelectionDAG &DAG) {
9757   SDLoc DL(N);
9758   SDValue Op = N->getOperand(0);
9759
9760   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9761     return;
9762
9763   Op = SDValue(
9764       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9765                          DAG.getUNDEF(MVT::i32), Op,
9766                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9767       0);
9768   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9769   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9770 }
9771
9772 static void ReplaceReductionResults(SDNode *N,
9773                                     SmallVectorImpl<SDValue> &Results,
9774                                     SelectionDAG &DAG, unsigned InterOp,
9775                                     unsigned AcrossOp) {
9776   EVT LoVT, HiVT;
9777   SDValue Lo, Hi;
9778   SDLoc dl(N);
9779   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9780   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9781   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9782   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9783   Results.push_back(SplitVal);
9784 }
9785
9786 void AArch64TargetLowering::ReplaceNodeResults(
9787     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9788   switch (N->getOpcode()) {
9789   default:
9790     llvm_unreachable("Don't know how to custom expand this");
9791   case ISD::BITCAST:
9792     ReplaceBITCASTResults(N, Results, DAG);
9793     return;
9794   case AArch64ISD::SADDV:
9795     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9796     return;
9797   case AArch64ISD::UADDV:
9798     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9799     return;
9800   case AArch64ISD::SMINV:
9801     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9802     return;
9803   case AArch64ISD::UMINV:
9804     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9805     return;
9806   case AArch64ISD::SMAXV:
9807     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9808     return;
9809   case AArch64ISD::UMAXV:
9810     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9811     return;
9812   case ISD::FP_TO_UINT:
9813   case ISD::FP_TO_SINT:
9814     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9815     // Let normal code take care of it by not adding anything to Results.
9816     return;
9817   }
9818 }
9819
9820 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9821   return true;
9822 }
9823
9824 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9825   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9826   // reciprocal if there are three or more FDIVs.
9827   return 3;
9828 }
9829
9830 TargetLoweringBase::LegalizeTypeAction
9831 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9832   MVT SVT = VT.getSimpleVT();
9833   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9834   // v4i16, v2i32 instead of to promote.
9835   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9836       || SVT == MVT::v1f32)
9837     return TypeWidenVector;
9838
9839   return TargetLoweringBase::getPreferredVectorAction(VT);
9840 }
9841
9842 // Loads and stores less than 128-bits are already atomic; ones above that
9843 // are doomed anyway, so defer to the default libcall and blame the OS when
9844 // things go wrong.
9845 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9846   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9847   return Size == 128;
9848 }
9849
9850 // Loads and stores less than 128-bits are already atomic; ones above that
9851 // are doomed anyway, so defer to the default libcall and blame the OS when
9852 // things go wrong.
9853 TargetLowering::AtomicExpansionKind
9854 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9855   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9856   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9857 }
9858
9859 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9860 TargetLowering::AtomicExpansionKind
9861 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9862   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9863   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9864 }
9865
9866 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9867     AtomicCmpXchgInst *AI) const {
9868   return true;
9869 }
9870
9871 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9872                                              AtomicOrdering Ord) const {
9873   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9874   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9875   bool IsAcquire = isAtLeastAcquire(Ord);
9876
9877   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9878   // intrinsic must return {i64, i64} and we have to recombine them into a
9879   // single i128 here.
9880   if (ValTy->getPrimitiveSizeInBits() == 128) {
9881     Intrinsic::ID Int =
9882         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9883     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9884
9885     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9886     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9887
9888     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9889     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9890     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9891     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9892     return Builder.CreateOr(
9893         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9894   }
9895
9896   Type *Tys[] = { Addr->getType() };
9897   Intrinsic::ID Int =
9898       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9899   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9900
9901   return Builder.CreateTruncOrBitCast(
9902       Builder.CreateCall(Ldxr, Addr),
9903       cast<PointerType>(Addr->getType())->getElementType());
9904 }
9905
9906 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9907     IRBuilder<> &Builder) const {
9908   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9909   Builder.CreateCall(
9910       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9911 }
9912
9913 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9914                                                    Value *Val, Value *Addr,
9915                                                    AtomicOrdering Ord) const {
9916   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9917   bool IsRelease = isAtLeastRelease(Ord);
9918
9919   // Since the intrinsics must have legal type, the i128 intrinsics take two
9920   // parameters: "i64, i64". We must marshal Val into the appropriate form
9921   // before the call.
9922   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9923     Intrinsic::ID Int =
9924         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9925     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9926     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9927
9928     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9929     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9930     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9931     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9932   }
9933
9934   Intrinsic::ID Int =
9935       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9936   Type *Tys[] = { Addr->getType() };
9937   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9938
9939   return Builder.CreateCall(Stxr,
9940                             {Builder.CreateZExtOrBitCast(
9941                                  Val, Stxr->getFunctionType()->getParamType(0)),
9942                              Addr});
9943 }
9944
9945 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9946     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9947   return Ty->isArrayTy();
9948 }
9949
9950 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9951                                                             EVT) const {
9952   return false;
9953 }
9954
9955 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9956   if (!Subtarget->isTargetAndroid())
9957     return TargetLowering::getSafeStackPointerLocation(IRB);
9958
9959   // Android provides a fixed TLS slot for the SafeStack pointer. See the
9960   // definition of TLS_SLOT_SAFESTACK in
9961   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
9962   const unsigned TlsOffset = 0x48;
9963   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
9964   Function *ThreadPointerFunc =
9965       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
9966   return IRB.CreatePointerCast(
9967       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
9968       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
9969 }