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