cbb68a9f321280f190135388015d1978d19f724a
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 #define DEBUG_TYPE "aarch64-lower"
39
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
43 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147   // Virtually no operation on f128 is legal, but LLVM can't expand them when
148   // there's a valid register class, so we need custom operations in most cases.
149   setOperationAction(ISD::FABS, MVT::f128, Expand);
150   setOperationAction(ISD::FADD, MVT::f128, Custom);
151   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152   setOperationAction(ISD::FCOS, MVT::f128, Expand);
153   setOperationAction(ISD::FDIV, MVT::f128, Custom);
154   setOperationAction(ISD::FMA, MVT::f128, Expand);
155   setOperationAction(ISD::FMUL, MVT::f128, Custom);
156   setOperationAction(ISD::FNEG, MVT::f128, Expand);
157   setOperationAction(ISD::FPOW, MVT::f128, Expand);
158   setOperationAction(ISD::FREM, MVT::f128, Expand);
159   setOperationAction(ISD::FRINT, MVT::f128, Expand);
160   setOperationAction(ISD::FSIN, MVT::f128, Expand);
161   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163   setOperationAction(ISD::FSUB, MVT::f128, Custom);
164   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165   setOperationAction(ISD::SETCC, MVT::f128, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167   setOperationAction(ISD::SELECT, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171   // Lowering for many of the conversions is actually specified by the non-f128
172   // type. The LowerXXX function will be trivial when f128 isn't involved.
173   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188   // Variable arguments.
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Custom);
191   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194   // Variable-sized objects.
195   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
199   // Exception handling.
200   // FIXME: These are guesses. Has this been defined yet?
201   setExceptionPointerRegister(AArch64::X0);
202   setExceptionSelectorRegister(AArch64::X1);
203
204   // Constant pool entries
205   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
206
207   // BlockAddress
208   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
209
210   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211   setOperationAction(ISD::ADDC, MVT::i32, Custom);
212   setOperationAction(ISD::ADDE, MVT::i32, Custom);
213   setOperationAction(ISD::SUBC, MVT::i32, Custom);
214   setOperationAction(ISD::SUBE, MVT::i32, Custom);
215   setOperationAction(ISD::ADDC, MVT::i64, Custom);
216   setOperationAction(ISD::ADDE, MVT::i64, Custom);
217   setOperationAction(ISD::SUBC, MVT::i64, Custom);
218   setOperationAction(ISD::SUBE, MVT::i64, Custom);
219
220   // AArch64 lacks both left-rotate and popcount instructions.
221   setOperationAction(ISD::ROTL, MVT::i32, Expand);
222   setOperationAction(ISD::ROTL, MVT::i64, Expand);
223
224   // AArch64 doesn't have {U|S}MUL_LOHI.
225   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
227
228
229   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230   // counterparts, which AArch64 supports directly.
231   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
235
236   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
238
239   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241   setOperationAction(ISD::SREM, MVT::i32, Expand);
242   setOperationAction(ISD::SREM, MVT::i64, Expand);
243   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::UREM, MVT::i32, Expand);
246   setOperationAction(ISD::UREM, MVT::i64, Expand);
247
248   // Custom lower Add/Sub/Mul with overflow.
249   setOperationAction(ISD::SADDO, MVT::i32, Custom);
250   setOperationAction(ISD::SADDO, MVT::i64, Custom);
251   setOperationAction(ISD::UADDO, MVT::i32, Custom);
252   setOperationAction(ISD::UADDO, MVT::i64, Custom);
253   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255   setOperationAction(ISD::USUBO, MVT::i32, Custom);
256   setOperationAction(ISD::USUBO, MVT::i64, Custom);
257   setOperationAction(ISD::SMULO, MVT::i32, Custom);
258   setOperationAction(ISD::SMULO, MVT::i64, Custom);
259   setOperationAction(ISD::UMULO, MVT::i32, Custom);
260   setOperationAction(ISD::UMULO, MVT::i64, Custom);
261
262   setOperationAction(ISD::FSIN, MVT::f32, Expand);
263   setOperationAction(ISD::FSIN, MVT::f64, Expand);
264   setOperationAction(ISD::FCOS, MVT::f32, Expand);
265   setOperationAction(ISD::FCOS, MVT::f64, Expand);
266   setOperationAction(ISD::FPOW, MVT::f32, Expand);
267   setOperationAction(ISD::FPOW, MVT::f64, Expand);
268   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
270
271   // f16 is a storage-only type, always promote it to f32.
272   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
273   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
274   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
275   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
276   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
277   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
278   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
279   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
280   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
281   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
282   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
283   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
284   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
285   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
286   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
287   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
288   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
289   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
290   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
291   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
292   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
293   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
294   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
295   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
296   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
297   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
298   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
299   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
300   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
301   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
302   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
303   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
304   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
305   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
306
307   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
308   // known to be safe.
309   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
321
322   // Expand all other v4f16 operations.
323   // FIXME: We could generate better code by promoting some operations to
324   // a pair of v4f32s
325   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
351
352
353   // v8f16 is also a storage-only type, so expand it.
354   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
385
386   // AArch64 has implementations of a lot of rounding-like FP operations.
387   for (MVT Ty : {MVT::f32, MVT::f64}) {
388     setOperationAction(ISD::FFLOOR, Ty, Legal);
389     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390     setOperationAction(ISD::FCEIL, Ty, Legal);
391     setOperationAction(ISD::FRINT, Ty, Legal);
392     setOperationAction(ISD::FTRUNC, Ty, Legal);
393     setOperationAction(ISD::FROUND, Ty, Legal);
394     setOperationAction(ISD::FMINNUM, Ty, Legal);
395     setOperationAction(ISD::FMAXNUM, Ty, Legal);
396     setOperationAction(ISD::FMINNAN, Ty, Legal);
397     setOperationAction(ISD::FMAXNAN, Ty, Legal);
398   }
399
400   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
401
402   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
403   // This requires the Performance Monitors extension.
404   if (Subtarget->hasPerfMon())
405     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
406
407   if (Subtarget->isTargetMachO()) {
408     // For iOS, we don't want to the normal expansion of a libcall to
409     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
410     // traffic.
411     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
412     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
413   } else {
414     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
415     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
416   }
417
418   // Make floating-point constants legal for the large code model, so they don't
419   // become loads from the constant pool.
420   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
421     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
422     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
423   }
424
425   // AArch64 does not have floating-point extending loads, i1 sign-extending
426   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
427   for (MVT VT : MVT::fp_valuetypes()) {
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
432   }
433   for (MVT VT : MVT::integer_valuetypes())
434     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
435
436   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
443
444   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
445   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
446
447   // Indexed loads and stores are supported.
448   for (unsigned im = (unsigned)ISD::PRE_INC;
449        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
450     setIndexedLoadAction(im, MVT::i8, Legal);
451     setIndexedLoadAction(im, MVT::i16, Legal);
452     setIndexedLoadAction(im, MVT::i32, Legal);
453     setIndexedLoadAction(im, MVT::i64, Legal);
454     setIndexedLoadAction(im, MVT::f64, Legal);
455     setIndexedLoadAction(im, MVT::f32, Legal);
456     setIndexedLoadAction(im, MVT::f16, Legal);
457     setIndexedStoreAction(im, MVT::i8, Legal);
458     setIndexedStoreAction(im, MVT::i16, Legal);
459     setIndexedStoreAction(im, MVT::i32, Legal);
460     setIndexedStoreAction(im, MVT::i64, Legal);
461     setIndexedStoreAction(im, MVT::f64, Legal);
462     setIndexedStoreAction(im, MVT::f32, Legal);
463     setIndexedStoreAction(im, MVT::f16, Legal);
464   }
465
466   // Trap.
467   setOperationAction(ISD::TRAP, MVT::Other, Legal);
468
469   // We combine OR nodes for bitfield operations.
470   setTargetDAGCombine(ISD::OR);
471
472   // Vector add and sub nodes may conceal a high-half opportunity.
473   // Also, try to fold ADD into CSINC/CSINV..
474   setTargetDAGCombine(ISD::ADD);
475   setTargetDAGCombine(ISD::SUB);
476
477   setTargetDAGCombine(ISD::XOR);
478   setTargetDAGCombine(ISD::SINT_TO_FP);
479   setTargetDAGCombine(ISD::UINT_TO_FP);
480
481   setTargetDAGCombine(ISD::FP_TO_SINT);
482   setTargetDAGCombine(ISD::FP_TO_UINT);
483   setTargetDAGCombine(ISD::FDIV);
484
485   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
486
487   setTargetDAGCombine(ISD::ANY_EXTEND);
488   setTargetDAGCombine(ISD::ZERO_EXTEND);
489   setTargetDAGCombine(ISD::SIGN_EXTEND);
490   setTargetDAGCombine(ISD::BITCAST);
491   setTargetDAGCombine(ISD::CONCAT_VECTORS);
492   setTargetDAGCombine(ISD::STORE);
493
494   setTargetDAGCombine(ISD::MUL);
495
496   setTargetDAGCombine(ISD::SELECT);
497   setTargetDAGCombine(ISD::VSELECT);
498
499   setTargetDAGCombine(ISD::INTRINSIC_VOID);
500   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
501   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
502   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
503
504   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
505   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
506   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
507
508   setStackPointerRegisterToSaveRestore(AArch64::SP);
509
510   setSchedulingPreference(Sched::Hybrid);
511
512   // Enable TBZ/TBNZ
513   MaskAndBranchFoldingIsLegal = true;
514   EnableExtLdPromotion = true;
515
516   setMinFunctionAlignment(2);
517
518   setHasExtractBitsInsn(true);
519
520   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
521
522   if (Subtarget->hasNEON()) {
523     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
524     // silliness like this:
525     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
526     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
528     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
529     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
532     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
533     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
534     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
535     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
536     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
537     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
538     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
539     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
542     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
543     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
544     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
545     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
546     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
547     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
548     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
549     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
550
551     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
552     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
553     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
554     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
555     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
556
557     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
558
559     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
560     // elements smaller than i32, so promote the input to i32 first.
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
564     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
565     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
566     // -> v8f16 conversions.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
571     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
576     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
577     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
578     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
580
581     // AArch64 doesn't have MUL.2d:
582     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
583     // Custom handling for some quad-vector types to detect MULL.
584     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
585     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
586     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
587
588     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
589     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
590     // Likewise, narrowing and extending vector loads/stores aren't handled
591     // directly.
592     for (MVT VT : MVT::vector_valuetypes()) {
593       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
594
595       setOperationAction(ISD::MULHS, VT, Expand);
596       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
597       setOperationAction(ISD::MULHU, VT, Expand);
598       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
599
600       setOperationAction(ISD::BSWAP, VT, Expand);
601
602       for (MVT InnerVT : MVT::vector_valuetypes()) {
603         setTruncStoreAction(VT, InnerVT, Expand);
604         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
607       }
608     }
609
610     // AArch64 has implementations of a lot of rounding-like FP operations.
611     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
612       setOperationAction(ISD::FFLOOR, Ty, Legal);
613       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
614       setOperationAction(ISD::FCEIL, Ty, Legal);
615       setOperationAction(ISD::FRINT, Ty, Legal);
616       setOperationAction(ISD::FTRUNC, Ty, Legal);
617       setOperationAction(ISD::FROUND, Ty, Legal);
618     }
619   }
620
621   // Prefer likely predicted branches to selects on out-of-order cores.
622   if (Subtarget->isCortexA57())
623     PredictableSelectIsExpensive = true;
624 }
625
626 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
627   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
628     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
629     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
630
631     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
632     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
633   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
634     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
635     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
636
637     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
638     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
639   }
640
641   // Mark vector float intrinsics as expand.
642   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
643     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
652
653     // But we do support custom-lowering for FCOPYSIGN.
654     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
655   }
656
657   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
669
670   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
671   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
672   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
673   for (MVT InnerVT : MVT::all_valuetypes())
674     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
675
676   // CNT supports only B element sizes.
677   if (VT != MVT::v8i8 && VT != MVT::v16i8)
678     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
679
680   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
681   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
682   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
683   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
684   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
685
686   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
687   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
688
689   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
690   // i64.
691   if (!VT.isFloatingPoint() &&
692       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
693     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
694                             ISD::SABSDIFF, ISD::UABSDIFF})
695       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
696
697   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
698   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
699     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
700                             ISD::FMINNUM, ISD::FMAXNUM})
701       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
702
703   if (Subtarget->isLittleEndian()) {
704     for (unsigned im = (unsigned)ISD::PRE_INC;
705          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
707       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
708     }
709   }
710 }
711
712 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
713   addRegisterClass(VT, &AArch64::FPR64RegClass);
714   addTypeForNEON(VT, MVT::v2i32);
715 }
716
717 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
718   addRegisterClass(VT, &AArch64::FPR128RegClass);
719   addTypeForNEON(VT, MVT::v4i32);
720 }
721
722 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
723                                               EVT VT) const {
724   if (!VT.isVector())
725     return MVT::i32;
726   return VT.changeVectorElementTypeToInteger();
727 }
728
729 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
730 /// Mask are known to be either zero or one and return them in the
731 /// KnownZero/KnownOne bitsets.
732 void AArch64TargetLowering::computeKnownBitsForTargetNode(
733     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
734     const SelectionDAG &DAG, unsigned Depth) const {
735   switch (Op.getOpcode()) {
736   default:
737     break;
738   case AArch64ISD::CSEL: {
739     APInt KnownZero2, KnownOne2;
740     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
741     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
742     KnownZero &= KnownZero2;
743     KnownOne &= KnownOne2;
744     break;
745   }
746   case ISD::INTRINSIC_W_CHAIN: {
747     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
748     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
749     switch (IntID) {
750     default: return;
751     case Intrinsic::aarch64_ldaxr:
752     case Intrinsic::aarch64_ldxr: {
753       unsigned BitWidth = KnownOne.getBitWidth();
754       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
755       unsigned MemBits = VT.getScalarType().getSizeInBits();
756       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
757       return;
758     }
759     }
760     break;
761   }
762   case ISD::INTRINSIC_WO_CHAIN:
763   case ISD::INTRINSIC_VOID: {
764     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
765     switch (IntNo) {
766     default:
767       break;
768     case Intrinsic::aarch64_neon_umaxv:
769     case Intrinsic::aarch64_neon_uminv: {
770       // Figure out the datatype of the vector operand. The UMINV instruction
771       // will zero extend the result, so we can mark as known zero all the
772       // bits larger than the element datatype. 32-bit or larget doesn't need
773       // this as those are legal types and will be handled by isel directly.
774       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
775       unsigned BitWidth = KnownZero.getBitWidth();
776       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
777         assert(BitWidth >= 8 && "Unexpected width!");
778         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
779         KnownZero |= Mask;
780       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
781         assert(BitWidth >= 16 && "Unexpected width!");
782         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
783         KnownZero |= Mask;
784       }
785       break;
786     } break;
787     }
788   }
789   }
790 }
791
792 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
793                                                   EVT) const {
794   return MVT::i64;
795 }
796
797 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
798                                                            unsigned AddrSpace,
799                                                            unsigned Align,
800                                                            bool *Fast) const {
801   if (Subtarget->requiresStrictAlign())
802     return false;
803
804   // FIXME: This is mostly true for Cyclone, but not necessarily others.
805   if (Fast) {
806     // FIXME: Define an attribute for slow unaligned accesses instead of
807     // relying on the CPU type as a proxy.
808     // On Cyclone, unaligned 128-bit stores are slow.
809     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
810             // See comments in performSTORECombine() for more details about
811             // these conditions.
812
813             // Code that uses clang vector extensions can mark that it
814             // wants unaligned accesses to be treated as fast by
815             // underspecifying alignment to be 1 or 2.
816             Align <= 2 ||
817
818             // Disregard v2i64. Memcpy lowering produces those and splitting
819             // them regresses performance on micro-benchmarks and olden/bh.
820             VT == MVT::v2i64;
821   }
822   return true;
823 }
824
825 FastISel *
826 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
827                                       const TargetLibraryInfo *libInfo) const {
828   return AArch64::createFastISel(funcInfo, libInfo);
829 }
830
831 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
832   switch ((AArch64ISD::NodeType)Opcode) {
833   case AArch64ISD::FIRST_NUMBER:      break;
834   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
835   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
836   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
837   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
838   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
839   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
840   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
841   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
842   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
843   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
844   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
845   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
846   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
847   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
848   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
849   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
850   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
851   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
852   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
853   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
854   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
855   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
856   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
857   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
858   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
859   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
860   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
861   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
862   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
863   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
864   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
865   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
866   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
867   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
868   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
869   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
870   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
871   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
872   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
873   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
874   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
875   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
876   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
877   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
878   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
879   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
880   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
881   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
882   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
883   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
884   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
885   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
886   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
887   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
888   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
889   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
890   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
891   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
892   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
893   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
894   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
895   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
896   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
897   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
898   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
899   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
900   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
901   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
902   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
903   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
904   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
905   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
906   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
907   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
908   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
909   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
910   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
911   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
912   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
913   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
914   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
915   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
916   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
917   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
918   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
919   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
920   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
921   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
922   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
923   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
924   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
925   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
926   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
927   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
928   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
929   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
930   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
931   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
932   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
933   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
934   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
935   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
936   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
937   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
938   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
939   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
940   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
941   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
942   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
943   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
944   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
945   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
946   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
947   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
948   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
949   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
950   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
951   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
952   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
953   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
954   }
955   return nullptr;
956 }
957
958 MachineBasicBlock *
959 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
960                                     MachineBasicBlock *MBB) const {
961   // We materialise the F128CSEL pseudo-instruction as some control flow and a
962   // phi node:
963
964   // OrigBB:
965   //     [... previous instrs leading to comparison ...]
966   //     b.ne TrueBB
967   //     b EndBB
968   // TrueBB:
969   //     ; Fallthrough
970   // EndBB:
971   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
972
973   MachineFunction *MF = MBB->getParent();
974   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
975   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
976   DebugLoc DL = MI->getDebugLoc();
977   MachineFunction::iterator It = ++MBB->getIterator();
978
979   unsigned DestReg = MI->getOperand(0).getReg();
980   unsigned IfTrueReg = MI->getOperand(1).getReg();
981   unsigned IfFalseReg = MI->getOperand(2).getReg();
982   unsigned CondCode = MI->getOperand(3).getImm();
983   bool NZCVKilled = MI->getOperand(4).isKill();
984
985   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
986   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
987   MF->insert(It, TrueBB);
988   MF->insert(It, EndBB);
989
990   // Transfer rest of current basic-block to EndBB
991   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
992                 MBB->end());
993   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
994
995   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
996   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
997   MBB->addSuccessor(TrueBB);
998   MBB->addSuccessor(EndBB);
999
1000   // TrueBB falls through to the end.
1001   TrueBB->addSuccessor(EndBB);
1002
1003   if (!NZCVKilled) {
1004     TrueBB->addLiveIn(AArch64::NZCV);
1005     EndBB->addLiveIn(AArch64::NZCV);
1006   }
1007
1008   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1009       .addReg(IfTrueReg)
1010       .addMBB(TrueBB)
1011       .addReg(IfFalseReg)
1012       .addMBB(MBB);
1013
1014   MI->eraseFromParent();
1015   return EndBB;
1016 }
1017
1018 MachineBasicBlock *
1019 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1020                                                  MachineBasicBlock *BB) const {
1021   switch (MI->getOpcode()) {
1022   default:
1023 #ifndef NDEBUG
1024     MI->dump();
1025 #endif
1026     llvm_unreachable("Unexpected instruction for custom inserter!");
1027
1028   case AArch64::F128CSEL:
1029     return EmitF128CSEL(MI, BB);
1030
1031   case TargetOpcode::STACKMAP:
1032   case TargetOpcode::PATCHPOINT:
1033     return emitPatchPoint(MI, BB);
1034   }
1035 }
1036
1037 //===----------------------------------------------------------------------===//
1038 // AArch64 Lowering private implementation.
1039 //===----------------------------------------------------------------------===//
1040
1041 //===----------------------------------------------------------------------===//
1042 // Lowering Code
1043 //===----------------------------------------------------------------------===//
1044
1045 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1046 /// CC
1047 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1048   switch (CC) {
1049   default:
1050     llvm_unreachable("Unknown condition code!");
1051   case ISD::SETNE:
1052     return AArch64CC::NE;
1053   case ISD::SETEQ:
1054     return AArch64CC::EQ;
1055   case ISD::SETGT:
1056     return AArch64CC::GT;
1057   case ISD::SETGE:
1058     return AArch64CC::GE;
1059   case ISD::SETLT:
1060     return AArch64CC::LT;
1061   case ISD::SETLE:
1062     return AArch64CC::LE;
1063   case ISD::SETUGT:
1064     return AArch64CC::HI;
1065   case ISD::SETUGE:
1066     return AArch64CC::HS;
1067   case ISD::SETULT:
1068     return AArch64CC::LO;
1069   case ISD::SETULE:
1070     return AArch64CC::LS;
1071   }
1072 }
1073
1074 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1075 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1076                                   AArch64CC::CondCode &CondCode,
1077                                   AArch64CC::CondCode &CondCode2) {
1078   CondCode2 = AArch64CC::AL;
1079   switch (CC) {
1080   default:
1081     llvm_unreachable("Unknown FP condition!");
1082   case ISD::SETEQ:
1083   case ISD::SETOEQ:
1084     CondCode = AArch64CC::EQ;
1085     break;
1086   case ISD::SETGT:
1087   case ISD::SETOGT:
1088     CondCode = AArch64CC::GT;
1089     break;
1090   case ISD::SETGE:
1091   case ISD::SETOGE:
1092     CondCode = AArch64CC::GE;
1093     break;
1094   case ISD::SETOLT:
1095     CondCode = AArch64CC::MI;
1096     break;
1097   case ISD::SETOLE:
1098     CondCode = AArch64CC::LS;
1099     break;
1100   case ISD::SETONE:
1101     CondCode = AArch64CC::MI;
1102     CondCode2 = AArch64CC::GT;
1103     break;
1104   case ISD::SETO:
1105     CondCode = AArch64CC::VC;
1106     break;
1107   case ISD::SETUO:
1108     CondCode = AArch64CC::VS;
1109     break;
1110   case ISD::SETUEQ:
1111     CondCode = AArch64CC::EQ;
1112     CondCode2 = AArch64CC::VS;
1113     break;
1114   case ISD::SETUGT:
1115     CondCode = AArch64CC::HI;
1116     break;
1117   case ISD::SETUGE:
1118     CondCode = AArch64CC::PL;
1119     break;
1120   case ISD::SETLT:
1121   case ISD::SETULT:
1122     CondCode = AArch64CC::LT;
1123     break;
1124   case ISD::SETLE:
1125   case ISD::SETULE:
1126     CondCode = AArch64CC::LE;
1127     break;
1128   case ISD::SETNE:
1129   case ISD::SETUNE:
1130     CondCode = AArch64CC::NE;
1131     break;
1132   }
1133 }
1134
1135 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1136 /// CC usable with the vector instructions. Fewer operations are available
1137 /// without a real NZCV register, so we have to use less efficient combinations
1138 /// to get the same effect.
1139 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1140                                         AArch64CC::CondCode &CondCode,
1141                                         AArch64CC::CondCode &CondCode2,
1142                                         bool &Invert) {
1143   Invert = false;
1144   switch (CC) {
1145   default:
1146     // Mostly the scalar mappings work fine.
1147     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148     break;
1149   case ISD::SETUO:
1150     Invert = true; // Fallthrough
1151   case ISD::SETO:
1152     CondCode = AArch64CC::MI;
1153     CondCode2 = AArch64CC::GE;
1154     break;
1155   case ISD::SETUEQ:
1156   case ISD::SETULT:
1157   case ISD::SETULE:
1158   case ISD::SETUGT:
1159   case ISD::SETUGE:
1160     // All of the compare-mask comparisons are ordered, but we can switch
1161     // between the two by a double inversion. E.g. ULE == !OGT.
1162     Invert = true;
1163     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1164     break;
1165   }
1166 }
1167
1168 static bool isLegalArithImmed(uint64_t C) {
1169   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1170   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1171 }
1172
1173 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1174                               SDLoc dl, SelectionDAG &DAG) {
1175   EVT VT = LHS.getValueType();
1176
1177   if (VT.isFloatingPoint())
1178     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1179
1180   // The CMP instruction is just an alias for SUBS, and representing it as
1181   // SUBS means that it's possible to get CSE with subtract operations.
1182   // A later phase can perform the optimization of setting the destination
1183   // register to WZR/XZR if it ends up being unused.
1184   unsigned Opcode = AArch64ISD::SUBS;
1185
1186   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1187       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1188       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1189     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1190     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1191     // can be set differently by this operation. It comes down to whether
1192     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1193     // everything is fine. If not then the optimization is wrong. Thus general
1194     // comparisons are only valid if op2 != 0.
1195
1196     // So, finally, the only LLVM-native comparisons that don't mention C and V
1197     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1198     // the absence of information about op2.
1199     Opcode = AArch64ISD::ADDS;
1200     RHS = RHS.getOperand(1);
1201   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1202              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1203              !isUnsignedIntSetCC(CC)) {
1204     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1205     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1206     // of the signed comparisons.
1207     Opcode = AArch64ISD::ANDS;
1208     RHS = LHS.getOperand(1);
1209     LHS = LHS.getOperand(0);
1210   }
1211
1212   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1213       .getValue(1);
1214 }
1215
1216 /// \defgroup AArch64CCMP CMP;CCMP matching
1217 ///
1218 /// These functions deal with the formation of CMP;CCMP;... sequences.
1219 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1220 /// a comparison. They set the NZCV flags to a predefined value if their
1221 /// predicate is false. This allows to express arbitrary conjunctions, for
1222 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1223 /// expressed as:
1224 ///   cmp A
1225 ///   ccmp B, inv(CB), CA
1226 ///   check for CB flags
1227 ///
1228 /// In general we can create code for arbitrary "... (and (and A B) C)"
1229 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1230 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1231 /// negation operations:
1232 /// We can negate the results of a single comparison by inverting the flags
1233 /// used when the predicate fails and inverting the flags tested in the next
1234 /// instruction; We can also negate the results of the whole previous
1235 /// conditional compare sequence by inverting the flags tested in the next
1236 /// instruction. However there is no way to negate the result of a partial
1237 /// sequence.
1238 ///
1239 /// Therefore on encountering an "or" expression we can negate the subtree on
1240 /// one side and have to be able to push the negate to the leafs of the subtree
1241 /// on the other side (see also the comments in code). As complete example:
1242 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1243 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1244 /// is transformed to
1245 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1246 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1247 /// and implemented as:
1248 ///   cmp C
1249 ///   ccmp D, inv(CD), CC
1250 ///   ccmp A, CA, inv(CD)
1251 ///   ccmp B, CB, inv(CA)
1252 ///   check for CB flags
1253 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1254 /// by conditional compare sequences.
1255 /// @{
1256
1257 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1258 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1259                                          ISD::CondCode CC, SDValue CCOp,
1260                                          SDValue Condition, unsigned NZCV,
1261                                          SDLoc DL, SelectionDAG &DAG) {
1262   unsigned Opcode = 0;
1263   if (LHS.getValueType().isFloatingPoint())
1264     Opcode = AArch64ISD::FCCMP;
1265   else if (RHS.getOpcode() == ISD::SUB) {
1266     SDValue SubOp0 = RHS.getOperand(0);
1267     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1268       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1269         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1270         Opcode = AArch64ISD::CCMN;
1271         RHS = RHS.getOperand(1);
1272       }
1273   }
1274   if (Opcode == 0)
1275     Opcode = AArch64ISD::CCMP;
1276
1277   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1278   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1279 }
1280
1281 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1282 /// CanPushNegate is set to true if we can push a negate operation through
1283 /// the tree in a was that we are left with AND operations and negate operations
1284 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1285 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1286 /// brought into such a form.
1287 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1288                                          unsigned Depth = 0) {
1289   if (!Val.hasOneUse())
1290     return false;
1291   unsigned Opcode = Val->getOpcode();
1292   if (Opcode == ISD::SETCC) {
1293     CanPushNegate = true;
1294     return true;
1295   }
1296   // Protect against stack overflow.
1297   if (Depth > 15)
1298     return false;
1299   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1300     SDValue O0 = Val->getOperand(0);
1301     SDValue O1 = Val->getOperand(1);
1302     bool CanPushNegateL;
1303     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1304       return false;
1305     bool CanPushNegateR;
1306     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1307       return false;
1308     // We cannot push a negate through an AND operation (it would become an OR),
1309     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1310     // push the negate through the x/y subtrees.
1311     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1312     return true;
1313   }
1314   return false;
1315 }
1316
1317 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1318 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1319 /// Tries to transform the given i1 producing node @p Val to a series compare
1320 /// and conditional compare operations. @returns an NZCV flags producing node
1321 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1322 /// transformation was not possible.
1323 /// On recursive invocations @p PushNegate may be set to true to have negation
1324 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1325 /// for the comparisons in the current subtree; @p Depth limits the search
1326 /// depth to avoid stack overflow.
1327 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1328     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1329     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1330     unsigned Depth = 0) {
1331   // We're at a tree leaf, produce a conditional comparison operation.
1332   unsigned Opcode = Val->getOpcode();
1333   if (Opcode == ISD::SETCC) {
1334     SDValue LHS = Val->getOperand(0);
1335     SDValue RHS = Val->getOperand(1);
1336     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1337     bool isInteger = LHS.getValueType().isInteger();
1338     if (PushNegate)
1339       CC = getSetCCInverse(CC, isInteger);
1340     SDLoc DL(Val);
1341     // Determine OutCC and handle FP special case.
1342     if (isInteger) {
1343       OutCC = changeIntCCToAArch64CC(CC);
1344     } else {
1345       assert(LHS.getValueType().isFloatingPoint());
1346       AArch64CC::CondCode ExtraCC;
1347       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1348       // Surpisingly some floating point conditions can't be tested with a
1349       // single condition code. Construct an additional comparison in this case.
1350       // See comment below on how we deal with OR conditions.
1351       if (ExtraCC != AArch64CC::AL) {
1352         SDValue ExtraCmp;
1353         if (!CCOp.getNode())
1354           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1355         else {
1356           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1357           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1358           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1359           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1360                                                NZCV, DL, DAG);
1361         }
1362         CCOp = ExtraCmp;
1363         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1364         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1365       }
1366     }
1367
1368     // Produce a normal comparison if we are first in the chain
1369     if (!CCOp.getNode())
1370       return emitComparison(LHS, RHS, CC, DL, DAG);
1371     // Otherwise produce a ccmp.
1372     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1373     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1374     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1375     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1376                                      DAG);
1377   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1378     return SDValue();
1379
1380   assert((Opcode == ISD::OR || !PushNegate)
1381          && "Can only push negate through OR operation");
1382
1383   // Check if both sides can be transformed.
1384   SDValue LHS = Val->getOperand(0);
1385   SDValue RHS = Val->getOperand(1);
1386   bool CanPushNegateL;
1387   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1388     return SDValue();
1389   bool CanPushNegateR;
1390   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1391     return SDValue();
1392
1393   // Do we need to negate our operands?
1394   bool NegateOperands = Opcode == ISD::OR;
1395   // We can negate the results of all previous operations by inverting the
1396   // predicate flags giving us a free negation for one side. For the other side
1397   // we need to be able to push the negation to the leafs of the tree.
1398   if (NegateOperands) {
1399     if (!CanPushNegateL && !CanPushNegateR)
1400       return SDValue();
1401     // Order the side where we can push the negate through to LHS.
1402     if (!CanPushNegateL && CanPushNegateR)
1403       std::swap(LHS, RHS);
1404   } else {
1405     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1406     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1407     if (NeedsNegOutL && NeedsNegOutR)
1408       return SDValue();
1409     // Order the side where we need to negate the output flags to RHS so it
1410     // gets emitted first.
1411     if (NeedsNegOutL)
1412       std::swap(LHS, RHS);
1413   }
1414
1415   // Emit RHS. If we want to negate the tree we only need to push a negate
1416   // through if we are already in a PushNegate case, otherwise we can negate
1417   // the "flags to test" afterwards.
1418   AArch64CC::CondCode RHSCC;
1419   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1420                                                 CCOp, Predicate, Depth+1);
1421   if (NegateOperands && !PushNegate)
1422     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1423   // Emit LHS. We must push the negate through if we need to negate it.
1424   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1425                                                 CmpR, RHSCC, Depth+1);
1426   // If we transformed an OR to and AND then we have to negate the result
1427   // (or absorb a PushNegate resulting in a double negation).
1428   if (Opcode == ISD::OR && !PushNegate)
1429     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1430   return CmpL;
1431 }
1432
1433 /// @}
1434
1435 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1436                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1437   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1438     EVT VT = RHS.getValueType();
1439     uint64_t C = RHSC->getZExtValue();
1440     if (!isLegalArithImmed(C)) {
1441       // Constant does not fit, try adjusting it by one?
1442       switch (CC) {
1443       default:
1444         break;
1445       case ISD::SETLT:
1446       case ISD::SETGE:
1447         if ((VT == MVT::i32 && C != 0x80000000 &&
1448              isLegalArithImmed((uint32_t)(C - 1))) ||
1449             (VT == MVT::i64 && C != 0x80000000ULL &&
1450              isLegalArithImmed(C - 1ULL))) {
1451           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1452           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1453           RHS = DAG.getConstant(C, dl, VT);
1454         }
1455         break;
1456       case ISD::SETULT:
1457       case ISD::SETUGE:
1458         if ((VT == MVT::i32 && C != 0 &&
1459              isLegalArithImmed((uint32_t)(C - 1))) ||
1460             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1461           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1462           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1463           RHS = DAG.getConstant(C, dl, VT);
1464         }
1465         break;
1466       case ISD::SETLE:
1467       case ISD::SETGT:
1468         if ((VT == MVT::i32 && C != INT32_MAX &&
1469              isLegalArithImmed((uint32_t)(C + 1))) ||
1470             (VT == MVT::i64 && C != INT64_MAX &&
1471              isLegalArithImmed(C + 1ULL))) {
1472           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1473           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1474           RHS = DAG.getConstant(C, dl, VT);
1475         }
1476         break;
1477       case ISD::SETULE:
1478       case ISD::SETUGT:
1479         if ((VT == MVT::i32 && C != UINT32_MAX &&
1480              isLegalArithImmed((uint32_t)(C + 1))) ||
1481             (VT == MVT::i64 && C != UINT64_MAX &&
1482              isLegalArithImmed(C + 1ULL))) {
1483           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1484           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1485           RHS = DAG.getConstant(C, dl, VT);
1486         }
1487         break;
1488       }
1489     }
1490   }
1491   SDValue Cmp;
1492   AArch64CC::CondCode AArch64CC;
1493   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1494     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1495
1496     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1497     // For the i8 operand, the largest immediate is 255, so this can be easily
1498     // encoded in the compare instruction. For the i16 operand, however, the
1499     // largest immediate cannot be encoded in the compare.
1500     // Therefore, use a sign extending load and cmn to avoid materializing the
1501     // -1 constant. For example,
1502     // movz w1, #65535
1503     // ldrh w0, [x0, #0]
1504     // cmp w0, w1
1505     // >
1506     // ldrsh w0, [x0, #0]
1507     // cmn w0, #1
1508     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1509     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1510     // ensure both the LHS and RHS are truly zero extended and to make sure the
1511     // transformation is profitable.
1512     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1513         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1514         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1515         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1516       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1517       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1518         SDValue SExt =
1519             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1520                         DAG.getValueType(MVT::i16));
1521         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1522                                                    RHS.getValueType()),
1523                              CC, dl, DAG);
1524         AArch64CC = changeIntCCToAArch64CC(CC);
1525       }
1526     }
1527
1528     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1529       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1530         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1531           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1532       }
1533     }
1534   }
1535
1536   if (!Cmp) {
1537     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1538     AArch64CC = changeIntCCToAArch64CC(CC);
1539   }
1540   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1541   return Cmp;
1542 }
1543
1544 static std::pair<SDValue, SDValue>
1545 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1546   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1547          "Unsupported value type");
1548   SDValue Value, Overflow;
1549   SDLoc DL(Op);
1550   SDValue LHS = Op.getOperand(0);
1551   SDValue RHS = Op.getOperand(1);
1552   unsigned Opc = 0;
1553   switch (Op.getOpcode()) {
1554   default:
1555     llvm_unreachable("Unknown overflow instruction!");
1556   case ISD::SADDO:
1557     Opc = AArch64ISD::ADDS;
1558     CC = AArch64CC::VS;
1559     break;
1560   case ISD::UADDO:
1561     Opc = AArch64ISD::ADDS;
1562     CC = AArch64CC::HS;
1563     break;
1564   case ISD::SSUBO:
1565     Opc = AArch64ISD::SUBS;
1566     CC = AArch64CC::VS;
1567     break;
1568   case ISD::USUBO:
1569     Opc = AArch64ISD::SUBS;
1570     CC = AArch64CC::LO;
1571     break;
1572   // Multiply needs a little bit extra work.
1573   case ISD::SMULO:
1574   case ISD::UMULO: {
1575     CC = AArch64CC::NE;
1576     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1577     if (Op.getValueType() == MVT::i32) {
1578       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1579       // For a 32 bit multiply with overflow check we want the instruction
1580       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1581       // need to generate the following pattern:
1582       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1583       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1584       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1585       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1586       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1587                                 DAG.getConstant(0, DL, MVT::i64));
1588       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1589       // operation. We need to clear out the upper 32 bits, because we used a
1590       // widening multiply that wrote all 64 bits. In the end this should be a
1591       // noop.
1592       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1593       if (IsSigned) {
1594         // The signed overflow check requires more than just a simple check for
1595         // any bit set in the upper 32 bits of the result. These bits could be
1596         // just the sign bits of a negative number. To perform the overflow
1597         // check we have to arithmetic shift right the 32nd bit of the result by
1598         // 31 bits. Then we compare the result to the upper 32 bits.
1599         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1600                                         DAG.getConstant(32, DL, MVT::i64));
1601         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1602         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1603                                         DAG.getConstant(31, DL, MVT::i64));
1604         // It is important that LowerBits is last, otherwise the arithmetic
1605         // shift will not be folded into the compare (SUBS).
1606         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1607         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1608                        .getValue(1);
1609       } else {
1610         // The overflow check for unsigned multiply is easy. We only need to
1611         // check if any of the upper 32 bits are set. This can be done with a
1612         // CMP (shifted register). For that we need to generate the following
1613         // pattern:
1614         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1615         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1616                                         DAG.getConstant(32, DL, MVT::i64));
1617         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1618         Overflow =
1619             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1620                         DAG.getConstant(0, DL, MVT::i64),
1621                         UpperBits).getValue(1);
1622       }
1623       break;
1624     }
1625     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1626     // For the 64 bit multiply
1627     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1628     if (IsSigned) {
1629       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1630       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1631                                       DAG.getConstant(63, DL, MVT::i64));
1632       // It is important that LowerBits is last, otherwise the arithmetic
1633       // shift will not be folded into the compare (SUBS).
1634       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1635       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1636                      .getValue(1);
1637     } else {
1638       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1639       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1640       Overflow =
1641           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1642                       DAG.getConstant(0, DL, MVT::i64),
1643                       UpperBits).getValue(1);
1644     }
1645     break;
1646   }
1647   } // switch (...)
1648
1649   if (Opc) {
1650     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1651
1652     // Emit the AArch64 operation with overflow check.
1653     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1654     Overflow = Value.getValue(1);
1655   }
1656   return std::make_pair(Value, Overflow);
1657 }
1658
1659 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1660                                              RTLIB::Libcall Call) const {
1661   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1662   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1663                      SDLoc(Op)).first;
1664 }
1665
1666 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1667   SDValue Sel = Op.getOperand(0);
1668   SDValue Other = Op.getOperand(1);
1669
1670   // If neither operand is a SELECT_CC, give up.
1671   if (Sel.getOpcode() != ISD::SELECT_CC)
1672     std::swap(Sel, Other);
1673   if (Sel.getOpcode() != ISD::SELECT_CC)
1674     return Op;
1675
1676   // The folding we want to perform is:
1677   // (xor x, (select_cc a, b, cc, 0, -1) )
1678   //   -->
1679   // (csel x, (xor x, -1), cc ...)
1680   //
1681   // The latter will get matched to a CSINV instruction.
1682
1683   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1684   SDValue LHS = Sel.getOperand(0);
1685   SDValue RHS = Sel.getOperand(1);
1686   SDValue TVal = Sel.getOperand(2);
1687   SDValue FVal = Sel.getOperand(3);
1688   SDLoc dl(Sel);
1689
1690   // FIXME: This could be generalized to non-integer comparisons.
1691   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1692     return Op;
1693
1694   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1695   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1696
1697   // The values aren't constants, this isn't the pattern we're looking for.
1698   if (!CFVal || !CTVal)
1699     return Op;
1700
1701   // We can commute the SELECT_CC by inverting the condition.  This
1702   // might be needed to make this fit into a CSINV pattern.
1703   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1704     std::swap(TVal, FVal);
1705     std::swap(CTVal, CFVal);
1706     CC = ISD::getSetCCInverse(CC, true);
1707   }
1708
1709   // If the constants line up, perform the transform!
1710   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1711     SDValue CCVal;
1712     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1713
1714     FVal = Other;
1715     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1716                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1717
1718     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1719                        CCVal, Cmp);
1720   }
1721
1722   return Op;
1723 }
1724
1725 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1726   EVT VT = Op.getValueType();
1727
1728   // Let legalize expand this if it isn't a legal type yet.
1729   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1730     return SDValue();
1731
1732   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1733
1734   unsigned Opc;
1735   bool ExtraOp = false;
1736   switch (Op.getOpcode()) {
1737   default:
1738     llvm_unreachable("Invalid code");
1739   case ISD::ADDC:
1740     Opc = AArch64ISD::ADDS;
1741     break;
1742   case ISD::SUBC:
1743     Opc = AArch64ISD::SUBS;
1744     break;
1745   case ISD::ADDE:
1746     Opc = AArch64ISD::ADCS;
1747     ExtraOp = true;
1748     break;
1749   case ISD::SUBE:
1750     Opc = AArch64ISD::SBCS;
1751     ExtraOp = true;
1752     break;
1753   }
1754
1755   if (!ExtraOp)
1756     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1757   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1758                      Op.getOperand(2));
1759 }
1760
1761 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1762   // Let legalize expand this if it isn't a legal type yet.
1763   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1764     return SDValue();
1765
1766   SDLoc dl(Op);
1767   AArch64CC::CondCode CC;
1768   // The actual operation that sets the overflow or carry flag.
1769   SDValue Value, Overflow;
1770   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1771
1772   // We use 0 and 1 as false and true values.
1773   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1774   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1775
1776   // We use an inverted condition, because the conditional select is inverted
1777   // too. This will allow it to be selected to a single instruction:
1778   // CSINC Wd, WZR, WZR, invert(cond).
1779   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1780   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1781                          CCVal, Overflow);
1782
1783   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1784   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1785 }
1786
1787 // Prefetch operands are:
1788 // 1: Address to prefetch
1789 // 2: bool isWrite
1790 // 3: int locality (0 = no locality ... 3 = extreme locality)
1791 // 4: bool isDataCache
1792 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1793   SDLoc DL(Op);
1794   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1795   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1796   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1797
1798   bool IsStream = !Locality;
1799   // When the locality number is set
1800   if (Locality) {
1801     // The front-end should have filtered out the out-of-range values
1802     assert(Locality <= 3 && "Prefetch locality out-of-range");
1803     // The locality degree is the opposite of the cache speed.
1804     // Put the number the other way around.
1805     // The encoding starts at 0 for level 1
1806     Locality = 3 - Locality;
1807   }
1808
1809   // built the mask value encoding the expected behavior.
1810   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1811                    (!IsData << 3) |     // IsDataCache bit
1812                    (Locality << 1) |    // Cache level bits
1813                    (unsigned)IsStream;  // Stream bit
1814   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1815                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1816 }
1817
1818 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1819                                               SelectionDAG &DAG) const {
1820   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1821
1822   RTLIB::Libcall LC;
1823   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1824
1825   return LowerF128Call(Op, DAG, LC);
1826 }
1827
1828 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1829                                              SelectionDAG &DAG) const {
1830   if (Op.getOperand(0).getValueType() != MVT::f128) {
1831     // It's legal except when f128 is involved
1832     return Op;
1833   }
1834
1835   RTLIB::Libcall LC;
1836   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1837
1838   // FP_ROUND node has a second operand indicating whether it is known to be
1839   // precise. That doesn't take part in the LibCall so we can't directly use
1840   // LowerF128Call.
1841   SDValue SrcVal = Op.getOperand(0);
1842   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1843                      /*isSigned*/ false, SDLoc(Op)).first;
1844 }
1845
1846 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1847   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1848   // Any additional optimization in this function should be recorded
1849   // in the cost tables.
1850   EVT InVT = Op.getOperand(0).getValueType();
1851   EVT VT = Op.getValueType();
1852
1853   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1854     SDLoc dl(Op);
1855     SDValue Cv =
1856         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1857                     Op.getOperand(0));
1858     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1859   }
1860
1861   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1862     SDLoc dl(Op);
1863     MVT ExtVT =
1864         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1865                          VT.getVectorNumElements());
1866     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1867     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1868   }
1869
1870   // Type changing conversions are illegal.
1871   return Op;
1872 }
1873
1874 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1875                                               SelectionDAG &DAG) const {
1876   if (Op.getOperand(0).getValueType().isVector())
1877     return LowerVectorFP_TO_INT(Op, DAG);
1878
1879   // f16 conversions are promoted to f32.
1880   if (Op.getOperand(0).getValueType() == MVT::f16) {
1881     SDLoc dl(Op);
1882     return DAG.getNode(
1883         Op.getOpcode(), dl, Op.getValueType(),
1884         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1885   }
1886
1887   if (Op.getOperand(0).getValueType() != MVT::f128) {
1888     // It's legal except when f128 is involved
1889     return Op;
1890   }
1891
1892   RTLIB::Libcall LC;
1893   if (Op.getOpcode() == ISD::FP_TO_SINT)
1894     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1895   else
1896     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1897
1898   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1899   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1900                      SDLoc(Op)).first;
1901 }
1902
1903 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1904   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1905   // Any additional optimization in this function should be recorded
1906   // in the cost tables.
1907   EVT VT = Op.getValueType();
1908   SDLoc dl(Op);
1909   SDValue In = Op.getOperand(0);
1910   EVT InVT = In.getValueType();
1911
1912   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1913     MVT CastVT =
1914         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1915                          InVT.getVectorNumElements());
1916     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1917     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1918   }
1919
1920   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1921     unsigned CastOpc =
1922         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1923     EVT CastVT = VT.changeVectorElementTypeToInteger();
1924     In = DAG.getNode(CastOpc, dl, CastVT, In);
1925     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1926   }
1927
1928   return Op;
1929 }
1930
1931 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1932                                             SelectionDAG &DAG) const {
1933   if (Op.getValueType().isVector())
1934     return LowerVectorINT_TO_FP(Op, DAG);
1935
1936   // f16 conversions are promoted to f32.
1937   if (Op.getValueType() == MVT::f16) {
1938     SDLoc dl(Op);
1939     return DAG.getNode(
1940         ISD::FP_ROUND, dl, MVT::f16,
1941         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1942         DAG.getIntPtrConstant(0, dl));
1943   }
1944
1945   // i128 conversions are libcalls.
1946   if (Op.getOperand(0).getValueType() == MVT::i128)
1947     return SDValue();
1948
1949   // Other conversions are legal, unless it's to the completely software-based
1950   // fp128.
1951   if (Op.getValueType() != MVT::f128)
1952     return Op;
1953
1954   RTLIB::Libcall LC;
1955   if (Op.getOpcode() == ISD::SINT_TO_FP)
1956     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1957   else
1958     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1959
1960   return LowerF128Call(Op, DAG, LC);
1961 }
1962
1963 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1964                                             SelectionDAG &DAG) const {
1965   // For iOS, we want to call an alternative entry point: __sincos_stret,
1966   // which returns the values in two S / D registers.
1967   SDLoc dl(Op);
1968   SDValue Arg = Op.getOperand(0);
1969   EVT ArgVT = Arg.getValueType();
1970   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1971
1972   ArgListTy Args;
1973   ArgListEntry Entry;
1974
1975   Entry.Node = Arg;
1976   Entry.Ty = ArgTy;
1977   Entry.isSExt = false;
1978   Entry.isZExt = false;
1979   Args.push_back(Entry);
1980
1981   const char *LibcallName =
1982       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1983   SDValue Callee =
1984       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1985
1986   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1987   TargetLowering::CallLoweringInfo CLI(DAG);
1988   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1989     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1990
1991   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1992   return CallResult.first;
1993 }
1994
1995 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1996   if (Op.getValueType() != MVT::f16)
1997     return SDValue();
1998
1999   assert(Op.getOperand(0).getValueType() == MVT::i16);
2000   SDLoc DL(Op);
2001
2002   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2003   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2004   return SDValue(
2005       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2006                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2007       0);
2008 }
2009
2010 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2011   if (OrigVT.getSizeInBits() >= 64)
2012     return OrigVT;
2013
2014   assert(OrigVT.isSimple() && "Expecting a simple value type");
2015
2016   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2017   switch (OrigSimpleTy) {
2018   default: llvm_unreachable("Unexpected Vector Type");
2019   case MVT::v2i8:
2020   case MVT::v2i16:
2021      return MVT::v2i32;
2022   case MVT::v4i8:
2023     return  MVT::v4i16;
2024   }
2025 }
2026
2027 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2028                                                  const EVT &OrigTy,
2029                                                  const EVT &ExtTy,
2030                                                  unsigned ExtOpcode) {
2031   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2032   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2033   // 64-bits we need to insert a new extension so that it will be 64-bits.
2034   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2035   if (OrigTy.getSizeInBits() >= 64)
2036     return N;
2037
2038   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2039   EVT NewVT = getExtensionTo64Bits(OrigTy);
2040
2041   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2042 }
2043
2044 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2045                                    bool isSigned) {
2046   EVT VT = N->getValueType(0);
2047
2048   if (N->getOpcode() != ISD::BUILD_VECTOR)
2049     return false;
2050
2051   for (const SDValue &Elt : N->op_values()) {
2052     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2053       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2054       unsigned HalfSize = EltSize / 2;
2055       if (isSigned) {
2056         if (!isIntN(HalfSize, C->getSExtValue()))
2057           return false;
2058       } else {
2059         if (!isUIntN(HalfSize, C->getZExtValue()))
2060           return false;
2061       }
2062       continue;
2063     }
2064     return false;
2065   }
2066
2067   return true;
2068 }
2069
2070 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2071   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2072     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2073                                              N->getOperand(0)->getValueType(0),
2074                                              N->getValueType(0),
2075                                              N->getOpcode());
2076
2077   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2078   EVT VT = N->getValueType(0);
2079   SDLoc dl(N);
2080   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2081   unsigned NumElts = VT.getVectorNumElements();
2082   MVT TruncVT = MVT::getIntegerVT(EltSize);
2083   SmallVector<SDValue, 8> Ops;
2084   for (unsigned i = 0; i != NumElts; ++i) {
2085     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2086     const APInt &CInt = C->getAPIntValue();
2087     // Element types smaller than 32 bits are not legal, so use i32 elements.
2088     // The values are implicitly truncated so sext vs. zext doesn't matter.
2089     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2090   }
2091   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2092                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2093 }
2094
2095 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2096   if (N->getOpcode() == ISD::SIGN_EXTEND)
2097     return true;
2098   if (isExtendedBUILD_VECTOR(N, DAG, true))
2099     return true;
2100   return false;
2101 }
2102
2103 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2104   if (N->getOpcode() == ISD::ZERO_EXTEND)
2105     return true;
2106   if (isExtendedBUILD_VECTOR(N, DAG, false))
2107     return true;
2108   return false;
2109 }
2110
2111 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2112   unsigned Opcode = N->getOpcode();
2113   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2114     SDNode *N0 = N->getOperand(0).getNode();
2115     SDNode *N1 = N->getOperand(1).getNode();
2116     return N0->hasOneUse() && N1->hasOneUse() &&
2117       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2118   }
2119   return false;
2120 }
2121
2122 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2123   unsigned Opcode = N->getOpcode();
2124   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2125     SDNode *N0 = N->getOperand(0).getNode();
2126     SDNode *N1 = N->getOperand(1).getNode();
2127     return N0->hasOneUse() && N1->hasOneUse() &&
2128       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2129   }
2130   return false;
2131 }
2132
2133 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2134   // Multiplications are only custom-lowered for 128-bit vectors so that
2135   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2136   EVT VT = Op.getValueType();
2137   assert(VT.is128BitVector() && VT.isInteger() &&
2138          "unexpected type for custom-lowering ISD::MUL");
2139   SDNode *N0 = Op.getOperand(0).getNode();
2140   SDNode *N1 = Op.getOperand(1).getNode();
2141   unsigned NewOpc = 0;
2142   bool isMLA = false;
2143   bool isN0SExt = isSignExtended(N0, DAG);
2144   bool isN1SExt = isSignExtended(N1, DAG);
2145   if (isN0SExt && isN1SExt)
2146     NewOpc = AArch64ISD::SMULL;
2147   else {
2148     bool isN0ZExt = isZeroExtended(N0, DAG);
2149     bool isN1ZExt = isZeroExtended(N1, DAG);
2150     if (isN0ZExt && isN1ZExt)
2151       NewOpc = AArch64ISD::UMULL;
2152     else if (isN1SExt || isN1ZExt) {
2153       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2154       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2155       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2156         NewOpc = AArch64ISD::SMULL;
2157         isMLA = true;
2158       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2159         NewOpc =  AArch64ISD::UMULL;
2160         isMLA = true;
2161       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2162         std::swap(N0, N1);
2163         NewOpc =  AArch64ISD::UMULL;
2164         isMLA = true;
2165       }
2166     }
2167
2168     if (!NewOpc) {
2169       if (VT == MVT::v2i64)
2170         // Fall through to expand this.  It is not legal.
2171         return SDValue();
2172       else
2173         // Other vector multiplications are legal.
2174         return Op;
2175     }
2176   }
2177
2178   // Legalize to a S/UMULL instruction
2179   SDLoc DL(Op);
2180   SDValue Op0;
2181   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2182   if (!isMLA) {
2183     Op0 = skipExtensionForVectorMULL(N0, DAG);
2184     assert(Op0.getValueType().is64BitVector() &&
2185            Op1.getValueType().is64BitVector() &&
2186            "unexpected types for extended operands to VMULL");
2187     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2188   }
2189   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2190   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2191   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2192   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2193   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2194   EVT Op1VT = Op1.getValueType();
2195   return DAG.getNode(N0->getOpcode(), DL, VT,
2196                      DAG.getNode(NewOpc, DL, VT,
2197                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2198                      DAG.getNode(NewOpc, DL, VT,
2199                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2200 }
2201
2202 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2203                                                      SelectionDAG &DAG) const {
2204   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2205   SDLoc dl(Op);
2206   switch (IntNo) {
2207   default: return SDValue();    // Don't custom lower most intrinsics.
2208   case Intrinsic::aarch64_thread_pointer: {
2209     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2210     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2211   }
2212   case Intrinsic::aarch64_neon_smax:
2213     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2214                        Op.getOperand(1), Op.getOperand(2));
2215   case Intrinsic::aarch64_neon_umax:
2216     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2217                        Op.getOperand(1), Op.getOperand(2));
2218   case Intrinsic::aarch64_neon_smin:
2219     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2220                        Op.getOperand(1), Op.getOperand(2));
2221   case Intrinsic::aarch64_neon_umin:
2222     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2223                        Op.getOperand(1), Op.getOperand(2));
2224   }
2225 }
2226
2227 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2228                                               SelectionDAG &DAG) const {
2229   switch (Op.getOpcode()) {
2230   default:
2231     llvm_unreachable("unimplemented operand");
2232     return SDValue();
2233   case ISD::BITCAST:
2234     return LowerBITCAST(Op, DAG);
2235   case ISD::GlobalAddress:
2236     return LowerGlobalAddress(Op, DAG);
2237   case ISD::GlobalTLSAddress:
2238     return LowerGlobalTLSAddress(Op, DAG);
2239   case ISD::SETCC:
2240     return LowerSETCC(Op, DAG);
2241   case ISD::BR_CC:
2242     return LowerBR_CC(Op, DAG);
2243   case ISD::SELECT:
2244     return LowerSELECT(Op, DAG);
2245   case ISD::SELECT_CC:
2246     return LowerSELECT_CC(Op, DAG);
2247   case ISD::JumpTable:
2248     return LowerJumpTable(Op, DAG);
2249   case ISD::ConstantPool:
2250     return LowerConstantPool(Op, DAG);
2251   case ISD::BlockAddress:
2252     return LowerBlockAddress(Op, DAG);
2253   case ISD::VASTART:
2254     return LowerVASTART(Op, DAG);
2255   case ISD::VACOPY:
2256     return LowerVACOPY(Op, DAG);
2257   case ISD::VAARG:
2258     return LowerVAARG(Op, DAG);
2259   case ISD::ADDC:
2260   case ISD::ADDE:
2261   case ISD::SUBC:
2262   case ISD::SUBE:
2263     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2264   case ISD::SADDO:
2265   case ISD::UADDO:
2266   case ISD::SSUBO:
2267   case ISD::USUBO:
2268   case ISD::SMULO:
2269   case ISD::UMULO:
2270     return LowerXALUO(Op, DAG);
2271   case ISD::FADD:
2272     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2273   case ISD::FSUB:
2274     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2275   case ISD::FMUL:
2276     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2277   case ISD::FDIV:
2278     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2279   case ISD::FP_ROUND:
2280     return LowerFP_ROUND(Op, DAG);
2281   case ISD::FP_EXTEND:
2282     return LowerFP_EXTEND(Op, DAG);
2283   case ISD::FRAMEADDR:
2284     return LowerFRAMEADDR(Op, DAG);
2285   case ISD::RETURNADDR:
2286     return LowerRETURNADDR(Op, DAG);
2287   case ISD::INSERT_VECTOR_ELT:
2288     return LowerINSERT_VECTOR_ELT(Op, DAG);
2289   case ISD::EXTRACT_VECTOR_ELT:
2290     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2291   case ISD::BUILD_VECTOR:
2292     return LowerBUILD_VECTOR(Op, DAG);
2293   case ISD::VECTOR_SHUFFLE:
2294     return LowerVECTOR_SHUFFLE(Op, DAG);
2295   case ISD::EXTRACT_SUBVECTOR:
2296     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2297   case ISD::SRA:
2298   case ISD::SRL:
2299   case ISD::SHL:
2300     return LowerVectorSRA_SRL_SHL(Op, DAG);
2301   case ISD::SHL_PARTS:
2302     return LowerShiftLeftParts(Op, DAG);
2303   case ISD::SRL_PARTS:
2304   case ISD::SRA_PARTS:
2305     return LowerShiftRightParts(Op, DAG);
2306   case ISD::CTPOP:
2307     return LowerCTPOP(Op, DAG);
2308   case ISD::FCOPYSIGN:
2309     return LowerFCOPYSIGN(Op, DAG);
2310   case ISD::AND:
2311     return LowerVectorAND(Op, DAG);
2312   case ISD::OR:
2313     return LowerVectorOR(Op, DAG);
2314   case ISD::XOR:
2315     return LowerXOR(Op, DAG);
2316   case ISD::PREFETCH:
2317     return LowerPREFETCH(Op, DAG);
2318   case ISD::SINT_TO_FP:
2319   case ISD::UINT_TO_FP:
2320     return LowerINT_TO_FP(Op, DAG);
2321   case ISD::FP_TO_SINT:
2322   case ISD::FP_TO_UINT:
2323     return LowerFP_TO_INT(Op, DAG);
2324   case ISD::FSINCOS:
2325     return LowerFSINCOS(Op, DAG);
2326   case ISD::MUL:
2327     return LowerMUL(Op, DAG);
2328   case ISD::INTRINSIC_WO_CHAIN:
2329     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2330   }
2331 }
2332
2333 /// getFunctionAlignment - Return the Log2 alignment of this function.
2334 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2335   return 2;
2336 }
2337
2338 //===----------------------------------------------------------------------===//
2339 //                      Calling Convention Implementation
2340 //===----------------------------------------------------------------------===//
2341
2342 #include "AArch64GenCallingConv.inc"
2343
2344 /// Selects the correct CCAssignFn for a given CallingConvention value.
2345 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2346                                                      bool IsVarArg) const {
2347   switch (CC) {
2348   default:
2349     llvm_unreachable("Unsupported calling convention.");
2350   case CallingConv::WebKit_JS:
2351     return CC_AArch64_WebKit_JS;
2352   case CallingConv::GHC:
2353     return CC_AArch64_GHC;
2354   case CallingConv::C:
2355   case CallingConv::Fast:
2356     if (!Subtarget->isTargetDarwin())
2357       return CC_AArch64_AAPCS;
2358     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2359   }
2360 }
2361
2362 SDValue AArch64TargetLowering::LowerFormalArguments(
2363     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2364     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2365     SmallVectorImpl<SDValue> &InVals) const {
2366   MachineFunction &MF = DAG.getMachineFunction();
2367   MachineFrameInfo *MFI = MF.getFrameInfo();
2368
2369   // Assign locations to all of the incoming arguments.
2370   SmallVector<CCValAssign, 16> ArgLocs;
2371   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2372                  *DAG.getContext());
2373
2374   // At this point, Ins[].VT may already be promoted to i32. To correctly
2375   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2376   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2377   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2378   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2379   // LocVT.
2380   unsigned NumArgs = Ins.size();
2381   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2382   unsigned CurArgIdx = 0;
2383   for (unsigned i = 0; i != NumArgs; ++i) {
2384     MVT ValVT = Ins[i].VT;
2385     if (Ins[i].isOrigArg()) {
2386       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2387       CurArgIdx = Ins[i].getOrigArgIndex();
2388
2389       // Get type of the original argument.
2390       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2391                                   /*AllowUnknown*/ true);
2392       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2393       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2394       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2395         ValVT = MVT::i8;
2396       else if (ActualMVT == MVT::i16)
2397         ValVT = MVT::i16;
2398     }
2399     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2400     bool Res =
2401         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2402     assert(!Res && "Call operand has unhandled type");
2403     (void)Res;
2404   }
2405   assert(ArgLocs.size() == Ins.size());
2406   SmallVector<SDValue, 16> ArgValues;
2407   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2408     CCValAssign &VA = ArgLocs[i];
2409
2410     if (Ins[i].Flags.isByVal()) {
2411       // Byval is used for HFAs in the PCS, but the system should work in a
2412       // non-compliant manner for larger structs.
2413       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2414       int Size = Ins[i].Flags.getByValSize();
2415       unsigned NumRegs = (Size + 7) / 8;
2416
2417       // FIXME: This works on big-endian for composite byvals, which are the common
2418       // case. It should also work for fundamental types too.
2419       unsigned FrameIdx =
2420         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2421       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2422       InVals.push_back(FrameIdxN);
2423
2424       continue;
2425     }
2426     
2427     if (VA.isRegLoc()) {
2428       // Arguments stored in registers.
2429       EVT RegVT = VA.getLocVT();
2430
2431       SDValue ArgValue;
2432       const TargetRegisterClass *RC;
2433
2434       if (RegVT == MVT::i32)
2435         RC = &AArch64::GPR32RegClass;
2436       else if (RegVT == MVT::i64)
2437         RC = &AArch64::GPR64RegClass;
2438       else if (RegVT == MVT::f16)
2439         RC = &AArch64::FPR16RegClass;
2440       else if (RegVT == MVT::f32)
2441         RC = &AArch64::FPR32RegClass;
2442       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2443         RC = &AArch64::FPR64RegClass;
2444       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2445         RC = &AArch64::FPR128RegClass;
2446       else
2447         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2448
2449       // Transform the arguments in physical registers into virtual ones.
2450       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2451       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2452
2453       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2454       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2455       // truncate to the right size.
2456       switch (VA.getLocInfo()) {
2457       default:
2458         llvm_unreachable("Unknown loc info!");
2459       case CCValAssign::Full:
2460         break;
2461       case CCValAssign::BCvt:
2462         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2463         break;
2464       case CCValAssign::AExt:
2465       case CCValAssign::SExt:
2466       case CCValAssign::ZExt:
2467         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2468         // nodes after our lowering.
2469         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2470         break;
2471       }
2472
2473       InVals.push_back(ArgValue);
2474
2475     } else { // VA.isRegLoc()
2476       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2477       unsigned ArgOffset = VA.getLocMemOffset();
2478       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2479
2480       uint32_t BEAlign = 0;
2481       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2482           !Ins[i].Flags.isInConsecutiveRegs())
2483         BEAlign = 8 - ArgSize;
2484
2485       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2486
2487       // Create load nodes to retrieve arguments from the stack.
2488       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2489       SDValue ArgValue;
2490
2491       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2492       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2493       MVT MemVT = VA.getValVT();
2494
2495       switch (VA.getLocInfo()) {
2496       default:
2497         break;
2498       case CCValAssign::BCvt:
2499         MemVT = VA.getLocVT();
2500         break;
2501       case CCValAssign::SExt:
2502         ExtType = ISD::SEXTLOAD;
2503         break;
2504       case CCValAssign::ZExt:
2505         ExtType = ISD::ZEXTLOAD;
2506         break;
2507       case CCValAssign::AExt:
2508         ExtType = ISD::EXTLOAD;
2509         break;
2510       }
2511
2512       ArgValue = DAG.getExtLoad(
2513           ExtType, DL, VA.getLocVT(), Chain, FIN,
2514           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2515           MemVT, false, false, false, 0);
2516
2517       InVals.push_back(ArgValue);
2518     }
2519   }
2520
2521   // varargs
2522   if (isVarArg) {
2523     if (!Subtarget->isTargetDarwin()) {
2524       // The AAPCS variadic function ABI is identical to the non-variadic
2525       // one. As a result there may be more arguments in registers and we should
2526       // save them for future reference.
2527       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2528     }
2529
2530     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2531     // This will point to the next argument passed via stack.
2532     unsigned StackOffset = CCInfo.getNextStackOffset();
2533     // We currently pass all varargs at 8-byte alignment.
2534     StackOffset = ((StackOffset + 7) & ~7);
2535     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2536   }
2537
2538   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2539   unsigned StackArgSize = CCInfo.getNextStackOffset();
2540   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2541   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2542     // This is a non-standard ABI so by fiat I say we're allowed to make full
2543     // use of the stack area to be popped, which must be aligned to 16 bytes in
2544     // any case:
2545     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2546
2547     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2548     // a multiple of 16.
2549     FuncInfo->setArgumentStackToRestore(StackArgSize);
2550
2551     // This realignment carries over to the available bytes below. Our own
2552     // callers will guarantee the space is free by giving an aligned value to
2553     // CALLSEQ_START.
2554   }
2555   // Even if we're not expected to free up the space, it's useful to know how
2556   // much is there while considering tail calls (because we can reuse it).
2557   FuncInfo->setBytesInStackArgArea(StackArgSize);
2558
2559   return Chain;
2560 }
2561
2562 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2563                                                 SelectionDAG &DAG, SDLoc DL,
2564                                                 SDValue &Chain) const {
2565   MachineFunction &MF = DAG.getMachineFunction();
2566   MachineFrameInfo *MFI = MF.getFrameInfo();
2567   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2568   auto PtrVT = getPointerTy(DAG.getDataLayout());
2569
2570   SmallVector<SDValue, 8> MemOps;
2571
2572   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2573                                           AArch64::X3, AArch64::X4, AArch64::X5,
2574                                           AArch64::X6, AArch64::X7 };
2575   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2576   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2577
2578   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2579   int GPRIdx = 0;
2580   if (GPRSaveSize != 0) {
2581     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2582
2583     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2584
2585     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2586       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2587       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2588       SDValue Store = DAG.getStore(
2589           Val.getValue(1), DL, Val, FIN,
2590           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2591           false, 0);
2592       MemOps.push_back(Store);
2593       FIN =
2594           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2595     }
2596   }
2597   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2598   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2599
2600   if (Subtarget->hasFPARMv8()) {
2601     static const MCPhysReg FPRArgRegs[] = {
2602         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2603         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2604     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2605     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2606
2607     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2608     int FPRIdx = 0;
2609     if (FPRSaveSize != 0) {
2610       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2611
2612       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2613
2614       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2615         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2616         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2617
2618         SDValue Store = DAG.getStore(
2619             Val.getValue(1), DL, Val, FIN,
2620             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2621             false, false, 0);
2622         MemOps.push_back(Store);
2623         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2624                           DAG.getConstant(16, DL, PtrVT));
2625       }
2626     }
2627     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2628     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2629   }
2630
2631   if (!MemOps.empty()) {
2632     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2633   }
2634 }
2635
2636 /// LowerCallResult - Lower the result values of a call into the
2637 /// appropriate copies out of appropriate physical registers.
2638 SDValue AArch64TargetLowering::LowerCallResult(
2639     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2640     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2641     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2642     SDValue ThisVal) const {
2643   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2644                           ? RetCC_AArch64_WebKit_JS
2645                           : RetCC_AArch64_AAPCS;
2646   // Assign locations to each value returned by this call.
2647   SmallVector<CCValAssign, 16> RVLocs;
2648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2649                  *DAG.getContext());
2650   CCInfo.AnalyzeCallResult(Ins, RetCC);
2651
2652   // Copy all of the result registers out of their specified physreg.
2653   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2654     CCValAssign VA = RVLocs[i];
2655
2656     // Pass 'this' value directly from the argument to return value, to avoid
2657     // reg unit interference
2658     if (i == 0 && isThisReturn) {
2659       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2660              "unexpected return calling convention register assignment");
2661       InVals.push_back(ThisVal);
2662       continue;
2663     }
2664
2665     SDValue Val =
2666         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2667     Chain = Val.getValue(1);
2668     InFlag = Val.getValue(2);
2669
2670     switch (VA.getLocInfo()) {
2671     default:
2672       llvm_unreachable("Unknown loc info!");
2673     case CCValAssign::Full:
2674       break;
2675     case CCValAssign::BCvt:
2676       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2677       break;
2678     }
2679
2680     InVals.push_back(Val);
2681   }
2682
2683   return Chain;
2684 }
2685
2686 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2687     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2688     bool isCalleeStructRet, bool isCallerStructRet,
2689     const SmallVectorImpl<ISD::OutputArg> &Outs,
2690     const SmallVectorImpl<SDValue> &OutVals,
2691     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2692   // For CallingConv::C this function knows whether the ABI needs
2693   // changing. That's not true for other conventions so they will have to opt in
2694   // manually.
2695   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2696     return false;
2697
2698   const MachineFunction &MF = DAG.getMachineFunction();
2699   const Function *CallerF = MF.getFunction();
2700   CallingConv::ID CallerCC = CallerF->getCallingConv();
2701   bool CCMatch = CallerCC == CalleeCC;
2702
2703   // Byval parameters hand the function a pointer directly into the stack area
2704   // we want to reuse during a tail call. Working around this *is* possible (see
2705   // X86) but less efficient and uglier in LowerCall.
2706   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2707                                     e = CallerF->arg_end();
2708        i != e; ++i)
2709     if (i->hasByValAttr())
2710       return false;
2711
2712   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2713     if (IsTailCallConvention(CalleeCC) && CCMatch)
2714       return true;
2715     return false;
2716   }
2717
2718   // Externally-defined functions with weak linkage should not be
2719   // tail-called on AArch64 when the OS does not support dynamic
2720   // pre-emption of symbols, as the AAELF spec requires normal calls
2721   // to undefined weak functions to be replaced with a NOP or jump to the
2722   // next instruction. The behaviour of branch instructions in this
2723   // situation (as used for tail calls) is implementation-defined, so we
2724   // cannot rely on the linker replacing the tail call with a return.
2725   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2726     const GlobalValue *GV = G->getGlobal();
2727     const Triple &TT = getTargetMachine().getTargetTriple();
2728     if (GV->hasExternalWeakLinkage() &&
2729         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2730       return false;
2731   }
2732
2733   // Now we search for cases where we can use a tail call without changing the
2734   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2735   // concept.
2736
2737   // I want anyone implementing a new calling convention to think long and hard
2738   // about this assert.
2739   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2740          "Unexpected variadic calling convention");
2741
2742   if (isVarArg && !Outs.empty()) {
2743     // At least two cases here: if caller is fastcc then we can't have any
2744     // memory arguments (we'd be expected to clean up the stack afterwards). If
2745     // caller is C then we could potentially use its argument area.
2746
2747     // FIXME: for now we take the most conservative of these in both cases:
2748     // disallow all variadic memory operands.
2749     SmallVector<CCValAssign, 16> ArgLocs;
2750     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2751                    *DAG.getContext());
2752
2753     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2754     for (const CCValAssign &ArgLoc : ArgLocs)
2755       if (!ArgLoc.isRegLoc())
2756         return false;
2757   }
2758
2759   // If the calling conventions do not match, then we'd better make sure the
2760   // results are returned in the same way as what the caller expects.
2761   if (!CCMatch) {
2762     SmallVector<CCValAssign, 16> RVLocs1;
2763     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2764                     *DAG.getContext());
2765     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2766
2767     SmallVector<CCValAssign, 16> RVLocs2;
2768     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2769                     *DAG.getContext());
2770     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2771
2772     if (RVLocs1.size() != RVLocs2.size())
2773       return false;
2774     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2775       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2776         return false;
2777       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2778         return false;
2779       if (RVLocs1[i].isRegLoc()) {
2780         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2781           return false;
2782       } else {
2783         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2784           return false;
2785       }
2786     }
2787   }
2788
2789   // Nothing more to check if the callee is taking no arguments
2790   if (Outs.empty())
2791     return true;
2792
2793   SmallVector<CCValAssign, 16> ArgLocs;
2794   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2795                  *DAG.getContext());
2796
2797   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2798
2799   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2800
2801   // If the stack arguments for this call would fit into our own save area then
2802   // the call can be made tail.
2803   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2804 }
2805
2806 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2807                                                    SelectionDAG &DAG,
2808                                                    MachineFrameInfo *MFI,
2809                                                    int ClobberedFI) const {
2810   SmallVector<SDValue, 8> ArgChains;
2811   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2812   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2813
2814   // Include the original chain at the beginning of the list. When this is
2815   // used by target LowerCall hooks, this helps legalize find the
2816   // CALLSEQ_BEGIN node.
2817   ArgChains.push_back(Chain);
2818
2819   // Add a chain value for each stack argument corresponding
2820   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2821                             UE = DAG.getEntryNode().getNode()->use_end();
2822        U != UE; ++U)
2823     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2824       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2825         if (FI->getIndex() < 0) {
2826           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2827           int64_t InLastByte = InFirstByte;
2828           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2829
2830           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2831               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2832             ArgChains.push_back(SDValue(L, 1));
2833         }
2834
2835   // Build a tokenfactor for all the chains.
2836   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2837 }
2838
2839 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2840                                                    bool TailCallOpt) const {
2841   return CallCC == CallingConv::Fast && TailCallOpt;
2842 }
2843
2844 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2845   return CallCC == CallingConv::Fast;
2846 }
2847
2848 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2849 /// and add input and output parameter nodes.
2850 SDValue
2851 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2852                                  SmallVectorImpl<SDValue> &InVals) const {
2853   SelectionDAG &DAG = CLI.DAG;
2854   SDLoc &DL = CLI.DL;
2855   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2856   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2857   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2858   SDValue Chain = CLI.Chain;
2859   SDValue Callee = CLI.Callee;
2860   bool &IsTailCall = CLI.IsTailCall;
2861   CallingConv::ID CallConv = CLI.CallConv;
2862   bool IsVarArg = CLI.IsVarArg;
2863
2864   MachineFunction &MF = DAG.getMachineFunction();
2865   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2866   bool IsThisReturn = false;
2867
2868   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2869   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2870   bool IsSibCall = false;
2871
2872   if (IsTailCall) {
2873     // Check if it's really possible to do a tail call.
2874     IsTailCall = isEligibleForTailCallOptimization(
2875         Callee, CallConv, IsVarArg, IsStructRet,
2876         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2877     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2878       report_fatal_error("failed to perform tail call elimination on a call "
2879                          "site marked musttail");
2880
2881     // A sibling call is one where we're under the usual C ABI and not planning
2882     // to change that but can still do a tail call:
2883     if (!TailCallOpt && IsTailCall)
2884       IsSibCall = true;
2885
2886     if (IsTailCall)
2887       ++NumTailCalls;
2888   }
2889
2890   // Analyze operands of the call, assigning locations to each operand.
2891   SmallVector<CCValAssign, 16> ArgLocs;
2892   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2893                  *DAG.getContext());
2894
2895   if (IsVarArg) {
2896     // Handle fixed and variable vector arguments differently.
2897     // Variable vector arguments always go into memory.
2898     unsigned NumArgs = Outs.size();
2899
2900     for (unsigned i = 0; i != NumArgs; ++i) {
2901       MVT ArgVT = Outs[i].VT;
2902       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2903       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2904                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2905       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2906       assert(!Res && "Call operand has unhandled type");
2907       (void)Res;
2908     }
2909   } else {
2910     // At this point, Outs[].VT may already be promoted to i32. To correctly
2911     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2912     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2913     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2914     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2915     // LocVT.
2916     unsigned NumArgs = Outs.size();
2917     for (unsigned i = 0; i != NumArgs; ++i) {
2918       MVT ValVT = Outs[i].VT;
2919       // Get type of the original argument.
2920       EVT ActualVT = getValueType(DAG.getDataLayout(),
2921                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2922                                   /*AllowUnknown*/ true);
2923       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2924       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2925       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2926       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2927         ValVT = MVT::i8;
2928       else if (ActualMVT == MVT::i16)
2929         ValVT = MVT::i16;
2930
2931       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2932       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2933       assert(!Res && "Call operand has unhandled type");
2934       (void)Res;
2935     }
2936   }
2937
2938   // Get a count of how many bytes are to be pushed on the stack.
2939   unsigned NumBytes = CCInfo.getNextStackOffset();
2940
2941   if (IsSibCall) {
2942     // Since we're not changing the ABI to make this a tail call, the memory
2943     // operands are already available in the caller's incoming argument space.
2944     NumBytes = 0;
2945   }
2946
2947   // FPDiff is the byte offset of the call's argument area from the callee's.
2948   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2949   // by this amount for a tail call. In a sibling call it must be 0 because the
2950   // caller will deallocate the entire stack and the callee still expects its
2951   // arguments to begin at SP+0. Completely unused for non-tail calls.
2952   int FPDiff = 0;
2953
2954   if (IsTailCall && !IsSibCall) {
2955     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2956
2957     // Since callee will pop argument stack as a tail call, we must keep the
2958     // popped size 16-byte aligned.
2959     NumBytes = RoundUpToAlignment(NumBytes, 16);
2960
2961     // FPDiff will be negative if this tail call requires more space than we
2962     // would automatically have in our incoming argument space. Positive if we
2963     // can actually shrink the stack.
2964     FPDiff = NumReusableBytes - NumBytes;
2965
2966     // The stack pointer must be 16-byte aligned at all times it's used for a
2967     // memory operation, which in practice means at *all* times and in
2968     // particular across call boundaries. Therefore our own arguments started at
2969     // a 16-byte aligned SP and the delta applied for the tail call should
2970     // satisfy the same constraint.
2971     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2972   }
2973
2974   // Adjust the stack pointer for the new arguments...
2975   // These operations are automatically eliminated by the prolog/epilog pass
2976   if (!IsSibCall)
2977     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2978                                                               true),
2979                                  DL);
2980
2981   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2982                                         getPointerTy(DAG.getDataLayout()));
2983
2984   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2985   SmallVector<SDValue, 8> MemOpChains;
2986   auto PtrVT = getPointerTy(DAG.getDataLayout());
2987
2988   // Walk the register/memloc assignments, inserting copies/loads.
2989   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2990        ++i, ++realArgIdx) {
2991     CCValAssign &VA = ArgLocs[i];
2992     SDValue Arg = OutVals[realArgIdx];
2993     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2994
2995     // Promote the value if needed.
2996     switch (VA.getLocInfo()) {
2997     default:
2998       llvm_unreachable("Unknown loc info!");
2999     case CCValAssign::Full:
3000       break;
3001     case CCValAssign::SExt:
3002       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3003       break;
3004     case CCValAssign::ZExt:
3005       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3006       break;
3007     case CCValAssign::AExt:
3008       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3009         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3010         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3011         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3012       }
3013       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3014       break;
3015     case CCValAssign::BCvt:
3016       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3017       break;
3018     case CCValAssign::FPExt:
3019       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3020       break;
3021     }
3022
3023     if (VA.isRegLoc()) {
3024       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3025         assert(VA.getLocVT() == MVT::i64 &&
3026                "unexpected calling convention register assignment");
3027         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3028                "unexpected use of 'returned'");
3029         IsThisReturn = true;
3030       }
3031       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3032     } else {
3033       assert(VA.isMemLoc());
3034
3035       SDValue DstAddr;
3036       MachinePointerInfo DstInfo;
3037
3038       // FIXME: This works on big-endian for composite byvals, which are the
3039       // common case. It should also work for fundamental types too.
3040       uint32_t BEAlign = 0;
3041       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3042                                         : VA.getValVT().getSizeInBits();
3043       OpSize = (OpSize + 7) / 8;
3044       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3045           !Flags.isInConsecutiveRegs()) {
3046         if (OpSize < 8)
3047           BEAlign = 8 - OpSize;
3048       }
3049       unsigned LocMemOffset = VA.getLocMemOffset();
3050       int32_t Offset = LocMemOffset + BEAlign;
3051       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3052       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3053
3054       if (IsTailCall) {
3055         Offset = Offset + FPDiff;
3056         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3057
3058         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3059         DstInfo =
3060             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3061
3062         // Make sure any stack arguments overlapping with where we're storing
3063         // are loaded before this eventual operation. Otherwise they'll be
3064         // clobbered.
3065         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3066       } else {
3067         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3068
3069         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3070         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3071                                                LocMemOffset);
3072       }
3073
3074       if (Outs[i].Flags.isByVal()) {
3075         SDValue SizeNode =
3076             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3077         SDValue Cpy = DAG.getMemcpy(
3078             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3079             /*isVol = */ false, /*AlwaysInline = */ false,
3080             /*isTailCall = */ false,
3081             DstInfo, MachinePointerInfo());
3082
3083         MemOpChains.push_back(Cpy);
3084       } else {
3085         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3086         // promoted to a legal register type i32, we should truncate Arg back to
3087         // i1/i8/i16.
3088         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3089             VA.getValVT() == MVT::i16)
3090           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3091
3092         SDValue Store =
3093             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3094         MemOpChains.push_back(Store);
3095       }
3096     }
3097   }
3098
3099   if (!MemOpChains.empty())
3100     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3101
3102   // Build a sequence of copy-to-reg nodes chained together with token chain
3103   // and flag operands which copy the outgoing args into the appropriate regs.
3104   SDValue InFlag;
3105   for (auto &RegToPass : RegsToPass) {
3106     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3107                              RegToPass.second, InFlag);
3108     InFlag = Chain.getValue(1);
3109   }
3110
3111   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3112   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3113   // node so that legalize doesn't hack it.
3114   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3115       Subtarget->isTargetMachO()) {
3116     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3117       const GlobalValue *GV = G->getGlobal();
3118       bool InternalLinkage = GV->hasInternalLinkage();
3119       if (InternalLinkage)
3120         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3121       else {
3122         Callee =
3123             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3124         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3125       }
3126     } else if (ExternalSymbolSDNode *S =
3127                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3128       const char *Sym = S->getSymbol();
3129       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3130       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3131     }
3132   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3133     const GlobalValue *GV = G->getGlobal();
3134     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3135   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3136     const char *Sym = S->getSymbol();
3137     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3138   }
3139
3140   // We don't usually want to end the call-sequence here because we would tidy
3141   // the frame up *after* the call, however in the ABI-changing tail-call case
3142   // we've carefully laid out the parameters so that when sp is reset they'll be
3143   // in the correct location.
3144   if (IsTailCall && !IsSibCall) {
3145     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3146                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3147     InFlag = Chain.getValue(1);
3148   }
3149
3150   std::vector<SDValue> Ops;
3151   Ops.push_back(Chain);
3152   Ops.push_back(Callee);
3153
3154   if (IsTailCall) {
3155     // Each tail call may have to adjust the stack by a different amount, so
3156     // this information must travel along with the operation for eventual
3157     // consumption by emitEpilogue.
3158     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3159   }
3160
3161   // Add argument registers to the end of the list so that they are known live
3162   // into the call.
3163   for (auto &RegToPass : RegsToPass)
3164     Ops.push_back(DAG.getRegister(RegToPass.first,
3165                                   RegToPass.second.getValueType()));
3166
3167   // Add a register mask operand representing the call-preserved registers.
3168   const uint32_t *Mask;
3169   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3170   if (IsThisReturn) {
3171     // For 'this' returns, use the X0-preserving mask if applicable
3172     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3173     if (!Mask) {
3174       IsThisReturn = false;
3175       Mask = TRI->getCallPreservedMask(MF, CallConv);
3176     }
3177   } else
3178     Mask = TRI->getCallPreservedMask(MF, CallConv);
3179
3180   assert(Mask && "Missing call preserved mask for calling convention");
3181   Ops.push_back(DAG.getRegisterMask(Mask));
3182
3183   if (InFlag.getNode())
3184     Ops.push_back(InFlag);
3185
3186   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3187
3188   // If we're doing a tall call, use a TC_RETURN here rather than an
3189   // actual call instruction.
3190   if (IsTailCall) {
3191     MF.getFrameInfo()->setHasTailCall();
3192     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3193   }
3194
3195   // Returns a chain and a flag for retval copy to use.
3196   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3197   InFlag = Chain.getValue(1);
3198
3199   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3200                                 ? RoundUpToAlignment(NumBytes, 16)
3201                                 : 0;
3202
3203   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3204                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3205                              InFlag, DL);
3206   if (!Ins.empty())
3207     InFlag = Chain.getValue(1);
3208
3209   // Handle result values, copying them out of physregs into vregs that we
3210   // return.
3211   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3212                          InVals, IsThisReturn,
3213                          IsThisReturn ? OutVals[0] : SDValue());
3214 }
3215
3216 bool AArch64TargetLowering::CanLowerReturn(
3217     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3218     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3219   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3220                           ? RetCC_AArch64_WebKit_JS
3221                           : RetCC_AArch64_AAPCS;
3222   SmallVector<CCValAssign, 16> RVLocs;
3223   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3224   return CCInfo.CheckReturn(Outs, RetCC);
3225 }
3226
3227 SDValue
3228 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3229                                    bool isVarArg,
3230                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3231                                    const SmallVectorImpl<SDValue> &OutVals,
3232                                    SDLoc DL, SelectionDAG &DAG) const {
3233   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3234                           ? RetCC_AArch64_WebKit_JS
3235                           : RetCC_AArch64_AAPCS;
3236   SmallVector<CCValAssign, 16> RVLocs;
3237   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3238                  *DAG.getContext());
3239   CCInfo.AnalyzeReturn(Outs, RetCC);
3240
3241   // Copy the result values into the output registers.
3242   SDValue Flag;
3243   SmallVector<SDValue, 4> RetOps(1, Chain);
3244   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3245        ++i, ++realRVLocIdx) {
3246     CCValAssign &VA = RVLocs[i];
3247     assert(VA.isRegLoc() && "Can only return in registers!");
3248     SDValue Arg = OutVals[realRVLocIdx];
3249
3250     switch (VA.getLocInfo()) {
3251     default:
3252       llvm_unreachable("Unknown loc info!");
3253     case CCValAssign::Full:
3254       if (Outs[i].ArgVT == MVT::i1) {
3255         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3256         // value. This is strictly redundant on Darwin (which uses "zeroext
3257         // i1"), but will be optimised out before ISel.
3258         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3259         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3260       }
3261       break;
3262     case CCValAssign::BCvt:
3263       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3264       break;
3265     }
3266
3267     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3268     Flag = Chain.getValue(1);
3269     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3270   }
3271
3272   RetOps[0] = Chain; // Update chain.
3273
3274   // Add the flag if we have it.
3275   if (Flag.getNode())
3276     RetOps.push_back(Flag);
3277
3278   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3279 }
3280
3281 //===----------------------------------------------------------------------===//
3282 //  Other Lowering Code
3283 //===----------------------------------------------------------------------===//
3284
3285 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3286                                                   SelectionDAG &DAG) const {
3287   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288   SDLoc DL(Op);
3289   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3290   const GlobalValue *GV = GN->getGlobal();
3291   unsigned char OpFlags =
3292       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3293
3294   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3295          "unexpected offset in global node");
3296
3297   // This also catched the large code model case for Darwin.
3298   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3299     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3300     // FIXME: Once remat is capable of dealing with instructions with register
3301     // operands, expand this into two nodes instead of using a wrapper node.
3302     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3303   }
3304
3305   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3306     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3307            "use of MO_CONSTPOOL only supported on small model");
3308     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3309     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3310     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3311     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3312     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3313     SDValue GlobalAddr = DAG.getLoad(
3314         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3315         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3316         /*isVolatile=*/false,
3317         /*isNonTemporal=*/true,
3318         /*isInvariant=*/true, 8);
3319     if (GN->getOffset() != 0)
3320       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3321                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3322     return GlobalAddr;
3323   }
3324
3325   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3326     const unsigned char MO_NC = AArch64II::MO_NC;
3327     return DAG.getNode(
3328         AArch64ISD::WrapperLarge, DL, PtrVT,
3329         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3330         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3331         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3332         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3333   } else {
3334     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3335     // the only correct model on Darwin.
3336     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3337                                             OpFlags | AArch64II::MO_PAGE);
3338     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3339     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3340
3341     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3342     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3343   }
3344 }
3345
3346 /// \brief Convert a TLS address reference into the correct sequence of loads
3347 /// and calls to compute the variable's address (for Darwin, currently) and
3348 /// return an SDValue containing the final node.
3349
3350 /// Darwin only has one TLS scheme which must be capable of dealing with the
3351 /// fully general situation, in the worst case. This means:
3352 ///     + "extern __thread" declaration.
3353 ///     + Defined in a possibly unknown dynamic library.
3354 ///
3355 /// The general system is that each __thread variable has a [3 x i64] descriptor
3356 /// which contains information used by the runtime to calculate the address. The
3357 /// only part of this the compiler needs to know about is the first xword, which
3358 /// contains a function pointer that must be called with the address of the
3359 /// entire descriptor in "x0".
3360 ///
3361 /// Since this descriptor may be in a different unit, in general even the
3362 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3363 /// is:
3364 ///     adrp x0, _var@TLVPPAGE
3365 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3366 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3367 ///                                      ; the function pointer
3368 ///     blr x1                           ; Uses descriptor address in x0
3369 ///     ; Address of _var is now in x0.
3370 ///
3371 /// If the address of _var's descriptor *is* known to the linker, then it can
3372 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3373 /// a slight efficiency gain.
3374 SDValue
3375 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3376                                                    SelectionDAG &DAG) const {
3377   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3378
3379   SDLoc DL(Op);
3380   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3381   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3382
3383   SDValue TLVPAddr =
3384       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3385   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3386
3387   // The first entry in the descriptor is a function pointer that we must call
3388   // to obtain the address of the variable.
3389   SDValue Chain = DAG.getEntryNode();
3390   SDValue FuncTLVGet =
3391       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3392                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3393                   true, true, 8);
3394   Chain = FuncTLVGet.getValue(1);
3395
3396   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3397   MFI->setAdjustsStack(true);
3398
3399   // TLS calls preserve all registers except those that absolutely must be
3400   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3401   // silly).
3402   const uint32_t *Mask =
3403       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3404
3405   // Finally, we can make the call. This is just a degenerate version of a
3406   // normal AArch64 call node: x0 takes the address of the descriptor, and
3407   // returns the address of the variable in this thread.
3408   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3409   Chain =
3410       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3411                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3412                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3413   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3414 }
3415
3416 /// When accessing thread-local variables under either the general-dynamic or
3417 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3418 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3419 /// is a function pointer to carry out the resolution.
3420 ///
3421 /// The sequence is:
3422 ///    adrp  x0, :tlsdesc:var
3423 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3424 ///    add   x0, x0, #:tlsdesc_lo12:var
3425 ///    .tlsdesccall var
3426 ///    blr   x1
3427 ///    (TPIDR_EL0 offset now in x0)
3428 ///
3429 ///  The above sequence must be produced unscheduled, to enable the linker to
3430 ///  optimize/relax this sequence.
3431 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3432 ///  above sequence, and expanded really late in the compilation flow, to ensure
3433 ///  the sequence is produced as per above.
3434 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3435                                                       SelectionDAG &DAG) const {
3436   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3437
3438   SDValue Chain = DAG.getEntryNode();
3439   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3440
3441   SmallVector<SDValue, 2> Ops;
3442   Ops.push_back(Chain);
3443   Ops.push_back(SymAddr);
3444
3445   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3446   SDValue Glue = Chain.getValue(1);
3447
3448   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3449 }
3450
3451 SDValue
3452 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3453                                                 SelectionDAG &DAG) const {
3454   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3455   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3456          "ELF TLS only supported in small memory model");
3457   // Different choices can be made for the maximum size of the TLS area for a
3458   // module. For the small address model, the default TLS size is 16MiB and the
3459   // maximum TLS size is 4GiB.
3460   // FIXME: add -mtls-size command line option and make it control the 16MiB
3461   // vs. 4GiB code sequence generation.
3462   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3463
3464   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3465
3466   if (DAG.getTarget().Options.EmulatedTLS)
3467     return LowerToTLSEmulatedModel(GA, DAG);
3468
3469   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3470     if (Model == TLSModel::LocalDynamic)
3471       Model = TLSModel::GeneralDynamic;
3472   }
3473
3474   SDValue TPOff;
3475   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3476   SDLoc DL(Op);
3477   const GlobalValue *GV = GA->getGlobal();
3478
3479   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3480
3481   if (Model == TLSModel::LocalExec) {
3482     SDValue HiVar = DAG.getTargetGlobalAddress(
3483         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3484     SDValue LoVar = DAG.getTargetGlobalAddress(
3485         GV, DL, PtrVT, 0,
3486         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3487
3488     SDValue TPWithOff_lo =
3489         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3490                                    HiVar,
3491                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3492                 0);
3493     SDValue TPWithOff =
3494         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3495                                    LoVar,
3496                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3497                 0);
3498     return TPWithOff;
3499   } else if (Model == TLSModel::InitialExec) {
3500     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3501     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3502   } else if (Model == TLSModel::LocalDynamic) {
3503     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3504     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3505     // the beginning of the module's TLS region, followed by a DTPREL offset
3506     // calculation.
3507
3508     // These accesses will need deduplicating if there's more than one.
3509     AArch64FunctionInfo *MFI =
3510         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3511     MFI->incNumLocalDynamicTLSAccesses();
3512
3513     // The call needs a relocation too for linker relaxation. It doesn't make
3514     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3515     // the address.
3516     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3517                                                   AArch64II::MO_TLS);
3518
3519     // Now we can calculate the offset from TPIDR_EL0 to this module's
3520     // thread-local area.
3521     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3522
3523     // Now use :dtprel_whatever: operations to calculate this variable's offset
3524     // in its thread-storage area.
3525     SDValue HiVar = DAG.getTargetGlobalAddress(
3526         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3527     SDValue LoVar = DAG.getTargetGlobalAddress(
3528         GV, DL, MVT::i64, 0,
3529         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3530
3531     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3532                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3533                     0);
3534     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3535                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3536                     0);
3537   } else if (Model == TLSModel::GeneralDynamic) {
3538     // The call needs a relocation too for linker relaxation. It doesn't make
3539     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3540     // the address.
3541     SDValue SymAddr =
3542         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3543
3544     // Finally we can make a call to calculate the offset from tpidr_el0.
3545     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3546   } else
3547     llvm_unreachable("Unsupported ELF TLS access model");
3548
3549   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3550 }
3551
3552 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3553                                                      SelectionDAG &DAG) const {
3554   if (Subtarget->isTargetDarwin())
3555     return LowerDarwinGlobalTLSAddress(Op, DAG);
3556   else if (Subtarget->isTargetELF())
3557     return LowerELFGlobalTLSAddress(Op, DAG);
3558
3559   llvm_unreachable("Unexpected platform trying to use TLS");
3560 }
3561 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3562   SDValue Chain = Op.getOperand(0);
3563   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3564   SDValue LHS = Op.getOperand(2);
3565   SDValue RHS = Op.getOperand(3);
3566   SDValue Dest = Op.getOperand(4);
3567   SDLoc dl(Op);
3568
3569   // Handle f128 first, since lowering it will result in comparing the return
3570   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3571   // is expecting to deal with.
3572   if (LHS.getValueType() == MVT::f128) {
3573     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3574
3575     // If softenSetCCOperands returned a scalar, we need to compare the result
3576     // against zero to select between true and false values.
3577     if (!RHS.getNode()) {
3578       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3579       CC = ISD::SETNE;
3580     }
3581   }
3582
3583   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3584   // instruction.
3585   unsigned Opc = LHS.getOpcode();
3586   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3587       cast<ConstantSDNode>(RHS)->isOne() &&
3588       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3589        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3590     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3591            "Unexpected condition code.");
3592     // Only lower legal XALUO ops.
3593     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3594       return SDValue();
3595
3596     // The actual operation with overflow check.
3597     AArch64CC::CondCode OFCC;
3598     SDValue Value, Overflow;
3599     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3600
3601     if (CC == ISD::SETNE)
3602       OFCC = getInvertedCondCode(OFCC);
3603     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3604
3605     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3606                        Overflow);
3607   }
3608
3609   if (LHS.getValueType().isInteger()) {
3610     assert((LHS.getValueType() == RHS.getValueType()) &&
3611            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3612
3613     // If the RHS of the comparison is zero, we can potentially fold this
3614     // to a specialized branch.
3615     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3616     if (RHSC && RHSC->getZExtValue() == 0) {
3617       if (CC == ISD::SETEQ) {
3618         // See if we can use a TBZ to fold in an AND as well.
3619         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3620         // out of bounds, a late MI-layer pass rewrites branches.
3621         // 403.gcc is an example that hits this case.
3622         if (LHS.getOpcode() == ISD::AND &&
3623             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3624             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3625           SDValue Test = LHS.getOperand(0);
3626           uint64_t Mask = LHS.getConstantOperandVal(1);
3627           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3628                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3629                              Dest);
3630         }
3631
3632         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3633       } else if (CC == ISD::SETNE) {
3634         // See if we can use a TBZ to fold in an AND as well.
3635         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3636         // out of bounds, a late MI-layer pass rewrites branches.
3637         // 403.gcc is an example that hits this case.
3638         if (LHS.getOpcode() == ISD::AND &&
3639             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3640             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3641           SDValue Test = LHS.getOperand(0);
3642           uint64_t Mask = LHS.getConstantOperandVal(1);
3643           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3644                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3645                              Dest);
3646         }
3647
3648         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3649       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3650         // Don't combine AND since emitComparison converts the AND to an ANDS
3651         // (a.k.a. TST) and the test in the test bit and branch instruction
3652         // becomes redundant.  This would also increase register pressure.
3653         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3654         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3655                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3656       }
3657     }
3658     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3659         LHS.getOpcode() != ISD::AND) {
3660       // Don't combine AND since emitComparison converts the AND to an ANDS
3661       // (a.k.a. TST) and the test in the test bit and branch instruction
3662       // becomes redundant.  This would also increase register pressure.
3663       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3664       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3665                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3666     }
3667
3668     SDValue CCVal;
3669     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3670     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3671                        Cmp);
3672   }
3673
3674   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3675
3676   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3677   // clean.  Some of them require two branches to implement.
3678   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3679   AArch64CC::CondCode CC1, CC2;
3680   changeFPCCToAArch64CC(CC, CC1, CC2);
3681   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3682   SDValue BR1 =
3683       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3684   if (CC2 != AArch64CC::AL) {
3685     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3686     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3687                        Cmp);
3688   }
3689
3690   return BR1;
3691 }
3692
3693 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3694                                               SelectionDAG &DAG) const {
3695   EVT VT = Op.getValueType();
3696   SDLoc DL(Op);
3697
3698   SDValue In1 = Op.getOperand(0);
3699   SDValue In2 = Op.getOperand(1);
3700   EVT SrcVT = In2.getValueType();
3701
3702   if (SrcVT.bitsLT(VT))
3703     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3704   else if (SrcVT.bitsGT(VT))
3705     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3706
3707   EVT VecVT;
3708   EVT EltVT;
3709   uint64_t EltMask;
3710   SDValue VecVal1, VecVal2;
3711   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3712     EltVT = MVT::i32;
3713     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3714     EltMask = 0x80000000ULL;
3715
3716     if (!VT.isVector()) {
3717       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3718                                           DAG.getUNDEF(VecVT), In1);
3719       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3720                                           DAG.getUNDEF(VecVT), In2);
3721     } else {
3722       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3723       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3724     }
3725   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3726     EltVT = MVT::i64;
3727     VecVT = MVT::v2i64;
3728
3729     // We want to materialize a mask with the high bit set, but the AdvSIMD
3730     // immediate moves cannot materialize that in a single instruction for
3731     // 64-bit elements. Instead, materialize zero and then negate it.
3732     EltMask = 0;
3733
3734     if (!VT.isVector()) {
3735       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3736                                           DAG.getUNDEF(VecVT), In1);
3737       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3738                                           DAG.getUNDEF(VecVT), In2);
3739     } else {
3740       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3741       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3742     }
3743   } else {
3744     llvm_unreachable("Invalid type for copysign!");
3745   }
3746
3747   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3748
3749   // If we couldn't materialize the mask above, then the mask vector will be
3750   // the zero vector, and we need to negate it here.
3751   if (VT == MVT::f64 || VT == MVT::v2f64) {
3752     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3753     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3754     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3755   }
3756
3757   SDValue Sel =
3758       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3759
3760   if (VT == MVT::f32)
3761     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3762   else if (VT == MVT::f64)
3763     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3764   else
3765     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3766 }
3767
3768 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3769   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3770           Attribute::NoImplicitFloat))
3771     return SDValue();
3772
3773   if (!Subtarget->hasNEON())
3774     return SDValue();
3775
3776   // While there is no integer popcount instruction, it can
3777   // be more efficiently lowered to the following sequence that uses
3778   // AdvSIMD registers/instructions as long as the copies to/from
3779   // the AdvSIMD registers are cheap.
3780   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3781   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3782   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3783   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3784   SDValue Val = Op.getOperand(0);
3785   SDLoc DL(Op);
3786   EVT VT = Op.getValueType();
3787
3788   if (VT == MVT::i32)
3789     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3790   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3791
3792   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3793   SDValue UaddLV = DAG.getNode(
3794       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3795       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3796
3797   if (VT == MVT::i64)
3798     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3799   return UaddLV;
3800 }
3801
3802 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3803
3804   if (Op.getValueType().isVector())
3805     return LowerVSETCC(Op, DAG);
3806
3807   SDValue LHS = Op.getOperand(0);
3808   SDValue RHS = Op.getOperand(1);
3809   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3810   SDLoc dl(Op);
3811
3812   // We chose ZeroOrOneBooleanContents, so use zero and one.
3813   EVT VT = Op.getValueType();
3814   SDValue TVal = DAG.getConstant(1, dl, VT);
3815   SDValue FVal = DAG.getConstant(0, dl, VT);
3816
3817   // Handle f128 first, since one possible outcome is a normal integer
3818   // comparison which gets picked up by the next if statement.
3819   if (LHS.getValueType() == MVT::f128) {
3820     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3821
3822     // If softenSetCCOperands returned a scalar, use it.
3823     if (!RHS.getNode()) {
3824       assert(LHS.getValueType() == Op.getValueType() &&
3825              "Unexpected setcc expansion!");
3826       return LHS;
3827     }
3828   }
3829
3830   if (LHS.getValueType().isInteger()) {
3831     SDValue CCVal;
3832     SDValue Cmp =
3833         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3834
3835     // Note that we inverted the condition above, so we reverse the order of
3836     // the true and false operands here.  This will allow the setcc to be
3837     // matched to a single CSINC instruction.
3838     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3839   }
3840
3841   // Now we know we're dealing with FP values.
3842   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3843
3844   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3845   // and do the comparison.
3846   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3847
3848   AArch64CC::CondCode CC1, CC2;
3849   changeFPCCToAArch64CC(CC, CC1, CC2);
3850   if (CC2 == AArch64CC::AL) {
3851     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3852     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3853
3854     // Note that we inverted the condition above, so we reverse the order of
3855     // the true and false operands here.  This will allow the setcc to be
3856     // matched to a single CSINC instruction.
3857     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3858   } else {
3859     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3860     // totally clean.  Some of them require two CSELs to implement.  As is in
3861     // this case, we emit the first CSEL and then emit a second using the output
3862     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3863
3864     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3865     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3866     SDValue CS1 =
3867         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3868
3869     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3870     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3871   }
3872 }
3873
3874 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3875                                               SDValue RHS, SDValue TVal,
3876                                               SDValue FVal, SDLoc dl,
3877                                               SelectionDAG &DAG) const {
3878   // Handle f128 first, because it will result in a comparison of some RTLIB
3879   // call result against zero.
3880   if (LHS.getValueType() == MVT::f128) {
3881     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3882
3883     // If softenSetCCOperands returned a scalar, we need to compare the result
3884     // against zero to select between true and false values.
3885     if (!RHS.getNode()) {
3886       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3887       CC = ISD::SETNE;
3888     }
3889   }
3890
3891   // Handle integers first.
3892   if (LHS.getValueType().isInteger()) {
3893     assert((LHS.getValueType() == RHS.getValueType()) &&
3894            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3895
3896     unsigned Opcode = AArch64ISD::CSEL;
3897
3898     // If both the TVal and the FVal are constants, see if we can swap them in
3899     // order to for a CSINV or CSINC out of them.
3900     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3901     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3902
3903     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3904       std::swap(TVal, FVal);
3905       std::swap(CTVal, CFVal);
3906       CC = ISD::getSetCCInverse(CC, true);
3907     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3908       std::swap(TVal, FVal);
3909       std::swap(CTVal, CFVal);
3910       CC = ISD::getSetCCInverse(CC, true);
3911     } else if (TVal.getOpcode() == ISD::XOR) {
3912       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3913       // with a CSINV rather than a CSEL.
3914       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3915
3916       if (CVal && CVal->isAllOnesValue()) {
3917         std::swap(TVal, FVal);
3918         std::swap(CTVal, CFVal);
3919         CC = ISD::getSetCCInverse(CC, true);
3920       }
3921     } else if (TVal.getOpcode() == ISD::SUB) {
3922       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3923       // that we can match with a CSNEG rather than a CSEL.
3924       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3925
3926       if (CVal && CVal->isNullValue()) {
3927         std::swap(TVal, FVal);
3928         std::swap(CTVal, CFVal);
3929         CC = ISD::getSetCCInverse(CC, true);
3930       }
3931     } else if (CTVal && CFVal) {
3932       const int64_t TrueVal = CTVal->getSExtValue();
3933       const int64_t FalseVal = CFVal->getSExtValue();
3934       bool Swap = false;
3935
3936       // If both TVal and FVal are constants, see if FVal is the
3937       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3938       // instead of a CSEL in that case.
3939       if (TrueVal == ~FalseVal) {
3940         Opcode = AArch64ISD::CSINV;
3941       } else if (TrueVal == -FalseVal) {
3942         Opcode = AArch64ISD::CSNEG;
3943       } else if (TVal.getValueType() == MVT::i32) {
3944         // If our operands are only 32-bit wide, make sure we use 32-bit
3945         // arithmetic for the check whether we can use CSINC. This ensures that
3946         // the addition in the check will wrap around properly in case there is
3947         // an overflow (which would not be the case if we do the check with
3948         // 64-bit arithmetic).
3949         const uint32_t TrueVal32 = CTVal->getZExtValue();
3950         const uint32_t FalseVal32 = CFVal->getZExtValue();
3951
3952         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3953           Opcode = AArch64ISD::CSINC;
3954
3955           if (TrueVal32 > FalseVal32) {
3956             Swap = true;
3957           }
3958         }
3959         // 64-bit check whether we can use CSINC.
3960       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3961         Opcode = AArch64ISD::CSINC;
3962
3963         if (TrueVal > FalseVal) {
3964           Swap = true;
3965         }
3966       }
3967
3968       // Swap TVal and FVal if necessary.
3969       if (Swap) {
3970         std::swap(TVal, FVal);
3971         std::swap(CTVal, CFVal);
3972         CC = ISD::getSetCCInverse(CC, true);
3973       }
3974
3975       if (Opcode != AArch64ISD::CSEL) {
3976         // Drop FVal since we can get its value by simply inverting/negating
3977         // TVal.
3978         FVal = TVal;
3979       }
3980     }
3981
3982     SDValue CCVal;
3983     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3984
3985     EVT VT = TVal.getValueType();
3986     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3987   }
3988
3989   // Now we know we're dealing with FP values.
3990   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3991   assert(LHS.getValueType() == RHS.getValueType());
3992   EVT VT = TVal.getValueType();
3993   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3994
3995   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3996   // clean.  Some of them require two CSELs to implement.
3997   AArch64CC::CondCode CC1, CC2;
3998   changeFPCCToAArch64CC(CC, CC1, CC2);
3999   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4000   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4001
4002   // If we need a second CSEL, emit it, using the output of the first as the
4003   // RHS.  We're effectively OR'ing the two CC's together.
4004   if (CC2 != AArch64CC::AL) {
4005     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4006     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4007   }
4008
4009   // Otherwise, return the output of the first CSEL.
4010   return CS1;
4011 }
4012
4013 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4014                                               SelectionDAG &DAG) const {
4015   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4016   SDValue LHS = Op.getOperand(0);
4017   SDValue RHS = Op.getOperand(1);
4018   SDValue TVal = Op.getOperand(2);
4019   SDValue FVal = Op.getOperand(3);
4020   SDLoc DL(Op);
4021   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4022 }
4023
4024 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4025                                            SelectionDAG &DAG) const {
4026   SDValue CCVal = Op->getOperand(0);
4027   SDValue TVal = Op->getOperand(1);
4028   SDValue FVal = Op->getOperand(2);
4029   SDLoc DL(Op);
4030
4031   unsigned Opc = CCVal.getOpcode();
4032   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4033   // instruction.
4034   if (CCVal.getResNo() == 1 &&
4035       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4036        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4037     // Only lower legal XALUO ops.
4038     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4039       return SDValue();
4040
4041     AArch64CC::CondCode OFCC;
4042     SDValue Value, Overflow;
4043     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4044     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4045
4046     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4047                        CCVal, Overflow);
4048   }
4049
4050   // Lower it the same way as we would lower a SELECT_CC node.
4051   ISD::CondCode CC;
4052   SDValue LHS, RHS;
4053   if (CCVal.getOpcode() == ISD::SETCC) {
4054     LHS = CCVal.getOperand(0);
4055     RHS = CCVal.getOperand(1);
4056     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4057   } else {
4058     LHS = CCVal;
4059     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4060     CC = ISD::SETNE;
4061   }
4062   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4063 }
4064
4065 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4066                                               SelectionDAG &DAG) const {
4067   // Jump table entries as PC relative offsets. No additional tweaking
4068   // is necessary here. Just get the address of the jump table.
4069   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4070   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4071   SDLoc DL(Op);
4072
4073   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4074       !Subtarget->isTargetMachO()) {
4075     const unsigned char MO_NC = AArch64II::MO_NC;
4076     return DAG.getNode(
4077         AArch64ISD::WrapperLarge, DL, PtrVT,
4078         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4079         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4080         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4081         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4082                                AArch64II::MO_G0 | MO_NC));
4083   }
4084
4085   SDValue Hi =
4086       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4087   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4088                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4089   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4090   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4091 }
4092
4093 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4094                                                  SelectionDAG &DAG) const {
4095   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4096   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4097   SDLoc DL(Op);
4098
4099   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4100     // Use the GOT for the large code model on iOS.
4101     if (Subtarget->isTargetMachO()) {
4102       SDValue GotAddr = DAG.getTargetConstantPool(
4103           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4104           AArch64II::MO_GOT);
4105       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4106     }
4107
4108     const unsigned char MO_NC = AArch64II::MO_NC;
4109     return DAG.getNode(
4110         AArch64ISD::WrapperLarge, DL, PtrVT,
4111         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4112                                   CP->getOffset(), AArch64II::MO_G3),
4113         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4114                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4115         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4116                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4117         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4118                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4119   } else {
4120     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4121     // ELF, the only valid one on Darwin.
4122     SDValue Hi =
4123         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4124                                   CP->getOffset(), AArch64II::MO_PAGE);
4125     SDValue Lo = DAG.getTargetConstantPool(
4126         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4127         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4128
4129     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4130     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4131   }
4132 }
4133
4134 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4135                                                SelectionDAG &DAG) const {
4136   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4137   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4138   SDLoc DL(Op);
4139   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4140       !Subtarget->isTargetMachO()) {
4141     const unsigned char MO_NC = AArch64II::MO_NC;
4142     return DAG.getNode(
4143         AArch64ISD::WrapperLarge, DL, PtrVT,
4144         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4145         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4146         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4147         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4148   } else {
4149     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4150     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4151                                                              AArch64II::MO_NC);
4152     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4153     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4154   }
4155 }
4156
4157 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4158                                                  SelectionDAG &DAG) const {
4159   AArch64FunctionInfo *FuncInfo =
4160       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4161
4162   SDLoc DL(Op);
4163   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4164                                  getPointerTy(DAG.getDataLayout()));
4165   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4166   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4167                       MachinePointerInfo(SV), false, false, 0);
4168 }
4169
4170 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4171                                                 SelectionDAG &DAG) const {
4172   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4173   // Standard, section B.3.
4174   MachineFunction &MF = DAG.getMachineFunction();
4175   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4176   auto PtrVT = getPointerTy(DAG.getDataLayout());
4177   SDLoc DL(Op);
4178
4179   SDValue Chain = Op.getOperand(0);
4180   SDValue VAList = Op.getOperand(1);
4181   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4182   SmallVector<SDValue, 4> MemOps;
4183
4184   // void *__stack at offset 0
4185   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4186   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4187                                 MachinePointerInfo(SV), false, false, 8));
4188
4189   // void *__gr_top at offset 8
4190   int GPRSize = FuncInfo->getVarArgsGPRSize();
4191   if (GPRSize > 0) {
4192     SDValue GRTop, GRTopAddr;
4193
4194     GRTopAddr =
4195         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4196
4197     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4198     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4199                         DAG.getConstant(GPRSize, DL, PtrVT));
4200
4201     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4202                                   MachinePointerInfo(SV, 8), false, false, 8));
4203   }
4204
4205   // void *__vr_top at offset 16
4206   int FPRSize = FuncInfo->getVarArgsFPRSize();
4207   if (FPRSize > 0) {
4208     SDValue VRTop, VRTopAddr;
4209     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4210                             DAG.getConstant(16, DL, PtrVT));
4211
4212     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4213     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4214                         DAG.getConstant(FPRSize, DL, PtrVT));
4215
4216     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4217                                   MachinePointerInfo(SV, 16), false, false, 8));
4218   }
4219
4220   // int __gr_offs at offset 24
4221   SDValue GROffsAddr =
4222       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4223   MemOps.push_back(DAG.getStore(Chain, DL,
4224                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4225                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4226                                 false, 4));
4227
4228   // int __vr_offs at offset 28
4229   SDValue VROffsAddr =
4230       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4231   MemOps.push_back(DAG.getStore(Chain, DL,
4232                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4233                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4234                                 false, 4));
4235
4236   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4237 }
4238
4239 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4240                                             SelectionDAG &DAG) const {
4241   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4242                                      : LowerAAPCS_VASTART(Op, DAG);
4243 }
4244
4245 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4246                                            SelectionDAG &DAG) const {
4247   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4248   // pointer.
4249   SDLoc DL(Op);
4250   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4251   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4252   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4253
4254   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4255                        Op.getOperand(2),
4256                        DAG.getConstant(VaListSize, DL, MVT::i32),
4257                        8, false, false, false, MachinePointerInfo(DestSV),
4258                        MachinePointerInfo(SrcSV));
4259 }
4260
4261 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4262   assert(Subtarget->isTargetDarwin() &&
4263          "automatic va_arg instruction only works on Darwin");
4264
4265   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4266   EVT VT = Op.getValueType();
4267   SDLoc DL(Op);
4268   SDValue Chain = Op.getOperand(0);
4269   SDValue Addr = Op.getOperand(1);
4270   unsigned Align = Op.getConstantOperandVal(3);
4271   auto PtrVT = getPointerTy(DAG.getDataLayout());
4272
4273   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4274                                false, false, false, 0);
4275   Chain = VAList.getValue(1);
4276
4277   if (Align > 8) {
4278     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4279     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4280                          DAG.getConstant(Align - 1, DL, PtrVT));
4281     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4282                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4283   }
4284
4285   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4286   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4287
4288   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4289   // up to 64 bits.  At the very least, we have to increase the striding of the
4290   // vaargs list to match this, and for FP values we need to introduce
4291   // FP_ROUND nodes as well.
4292   if (VT.isInteger() && !VT.isVector())
4293     ArgSize = 8;
4294   bool NeedFPTrunc = false;
4295   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4296     ArgSize = 8;
4297     NeedFPTrunc = true;
4298   }
4299
4300   // Increment the pointer, VAList, to the next vaarg
4301   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4302                                DAG.getConstant(ArgSize, DL, PtrVT));
4303   // Store the incremented VAList to the legalized pointer
4304   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4305                                  false, false, 0);
4306
4307   // Load the actual argument out of the pointer VAList
4308   if (NeedFPTrunc) {
4309     // Load the value as an f64.
4310     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4311                                  MachinePointerInfo(), false, false, false, 0);
4312     // Round the value down to an f32.
4313     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4314                                    DAG.getIntPtrConstant(1, DL));
4315     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4316     // Merge the rounded value with the chain output of the load.
4317     return DAG.getMergeValues(Ops, DL);
4318   }
4319
4320   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4321                      false, false, 0);
4322 }
4323
4324 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4325                                               SelectionDAG &DAG) const {
4326   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4327   MFI->setFrameAddressIsTaken(true);
4328
4329   EVT VT = Op.getValueType();
4330   SDLoc DL(Op);
4331   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4332   SDValue FrameAddr =
4333       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4334   while (Depth--)
4335     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4336                             MachinePointerInfo(), false, false, false, 0);
4337   return FrameAddr;
4338 }
4339
4340 // FIXME? Maybe this could be a TableGen attribute on some registers and
4341 // this table could be generated automatically from RegInfo.
4342 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4343                                                   SelectionDAG &DAG) const {
4344   unsigned Reg = StringSwitch<unsigned>(RegName)
4345                        .Case("sp", AArch64::SP)
4346                        .Default(0);
4347   if (Reg)
4348     return Reg;
4349   report_fatal_error(Twine("Invalid register name \""
4350                               + StringRef(RegName)  + "\"."));
4351 }
4352
4353 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4354                                                SelectionDAG &DAG) const {
4355   MachineFunction &MF = DAG.getMachineFunction();
4356   MachineFrameInfo *MFI = MF.getFrameInfo();
4357   MFI->setReturnAddressIsTaken(true);
4358
4359   EVT VT = Op.getValueType();
4360   SDLoc DL(Op);
4361   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4362   if (Depth) {
4363     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4364     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4365     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4366                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4367                        MachinePointerInfo(), false, false, false, 0);
4368   }
4369
4370   // Return LR, which contains the return address. Mark it an implicit live-in.
4371   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4372   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4373 }
4374
4375 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4376 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4377 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4378                                                     SelectionDAG &DAG) const {
4379   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4380   EVT VT = Op.getValueType();
4381   unsigned VTBits = VT.getSizeInBits();
4382   SDLoc dl(Op);
4383   SDValue ShOpLo = Op.getOperand(0);
4384   SDValue ShOpHi = Op.getOperand(1);
4385   SDValue ShAmt = Op.getOperand(2);
4386   SDValue ARMcc;
4387   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4388
4389   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4390
4391   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4392                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4393   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4394   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4395                                    DAG.getConstant(VTBits, dl, MVT::i64));
4396   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4397
4398   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4399                                ISD::SETGE, dl, DAG);
4400   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4401
4402   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4403   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4404   SDValue Lo =
4405       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4406
4407   // AArch64 shifts larger than the register width are wrapped rather than
4408   // clamped, so we can't just emit "hi >> x".
4409   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4410   SDValue TrueValHi = Opc == ISD::SRA
4411                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4412                                         DAG.getConstant(VTBits - 1, dl,
4413                                                         MVT::i64))
4414                           : DAG.getConstant(0, dl, VT);
4415   SDValue Hi =
4416       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4417
4418   SDValue Ops[2] = { Lo, Hi };
4419   return DAG.getMergeValues(Ops, dl);
4420 }
4421
4422 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4423 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4424 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4425                                                  SelectionDAG &DAG) const {
4426   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4427   EVT VT = Op.getValueType();
4428   unsigned VTBits = VT.getSizeInBits();
4429   SDLoc dl(Op);
4430   SDValue ShOpLo = Op.getOperand(0);
4431   SDValue ShOpHi = Op.getOperand(1);
4432   SDValue ShAmt = Op.getOperand(2);
4433   SDValue ARMcc;
4434
4435   assert(Op.getOpcode() == ISD::SHL_PARTS);
4436   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4437                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4438   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4439   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4440                                    DAG.getConstant(VTBits, dl, MVT::i64));
4441   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4442   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4443
4444   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4445
4446   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4447                                ISD::SETGE, dl, DAG);
4448   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4449   SDValue Hi =
4450       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4451
4452   // AArch64 shifts of larger than register sizes are wrapped rather than
4453   // clamped, so we can't just emit "lo << a" if a is too big.
4454   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4455   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4456   SDValue Lo =
4457       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4458
4459   SDValue Ops[2] = { Lo, Hi };
4460   return DAG.getMergeValues(Ops, dl);
4461 }
4462
4463 bool AArch64TargetLowering::isOffsetFoldingLegal(
4464     const GlobalAddressSDNode *GA) const {
4465   // The AArch64 target doesn't support folding offsets into global addresses.
4466   return false;
4467 }
4468
4469 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4470   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4471   // FIXME: We should be able to handle f128 as well with a clever lowering.
4472   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4473     return true;
4474
4475   if (VT == MVT::f64)
4476     return AArch64_AM::getFP64Imm(Imm) != -1;
4477   else if (VT == MVT::f32)
4478     return AArch64_AM::getFP32Imm(Imm) != -1;
4479   return false;
4480 }
4481
4482 //===----------------------------------------------------------------------===//
4483 //                          AArch64 Optimization Hooks
4484 //===----------------------------------------------------------------------===//
4485
4486 //===----------------------------------------------------------------------===//
4487 //                          AArch64 Inline Assembly Support
4488 //===----------------------------------------------------------------------===//
4489
4490 // Table of Constraints
4491 // TODO: This is the current set of constraints supported by ARM for the
4492 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4493 //
4494 // r - A general register
4495 // w - An FP/SIMD register of some size in the range v0-v31
4496 // x - An FP/SIMD register of some size in the range v0-v15
4497 // I - Constant that can be used with an ADD instruction
4498 // J - Constant that can be used with a SUB instruction
4499 // K - Constant that can be used with a 32-bit logical instruction
4500 // L - Constant that can be used with a 64-bit logical instruction
4501 // M - Constant that can be used as a 32-bit MOV immediate
4502 // N - Constant that can be used as a 64-bit MOV immediate
4503 // Q - A memory reference with base register and no offset
4504 // S - A symbolic address
4505 // Y - Floating point constant zero
4506 // Z - Integer constant zero
4507 //
4508 //   Note that general register operands will be output using their 64-bit x
4509 // register name, whatever the size of the variable, unless the asm operand
4510 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4511 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4512 // %q modifier.
4513
4514 /// getConstraintType - Given a constraint letter, return the type of
4515 /// constraint it is for this target.
4516 AArch64TargetLowering::ConstraintType
4517 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4518   if (Constraint.size() == 1) {
4519     switch (Constraint[0]) {
4520     default:
4521       break;
4522     case 'z':
4523       return C_Other;
4524     case 'x':
4525     case 'w':
4526       return C_RegisterClass;
4527     // An address with a single base register. Due to the way we
4528     // currently handle addresses it is the same as 'r'.
4529     case 'Q':
4530       return C_Memory;
4531     }
4532   }
4533   return TargetLowering::getConstraintType(Constraint);
4534 }
4535
4536 /// Examine constraint type and operand type and determine a weight value.
4537 /// This object must already have been set up with the operand type
4538 /// and the current alternative constraint selected.
4539 TargetLowering::ConstraintWeight
4540 AArch64TargetLowering::getSingleConstraintMatchWeight(
4541     AsmOperandInfo &info, const char *constraint) const {
4542   ConstraintWeight weight = CW_Invalid;
4543   Value *CallOperandVal = info.CallOperandVal;
4544   // If we don't have a value, we can't do a match,
4545   // but allow it at the lowest weight.
4546   if (!CallOperandVal)
4547     return CW_Default;
4548   Type *type = CallOperandVal->getType();
4549   // Look at the constraint type.
4550   switch (*constraint) {
4551   default:
4552     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4553     break;
4554   case 'x':
4555   case 'w':
4556     if (type->isFloatingPointTy() || type->isVectorTy())
4557       weight = CW_Register;
4558     break;
4559   case 'z':
4560     weight = CW_Constant;
4561     break;
4562   }
4563   return weight;
4564 }
4565
4566 std::pair<unsigned, const TargetRegisterClass *>
4567 AArch64TargetLowering::getRegForInlineAsmConstraint(
4568     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4569   if (Constraint.size() == 1) {
4570     switch (Constraint[0]) {
4571     case 'r':
4572       if (VT.getSizeInBits() == 64)
4573         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4574       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4575     case 'w':
4576       if (VT == MVT::f32)
4577         return std::make_pair(0U, &AArch64::FPR32RegClass);
4578       if (VT.getSizeInBits() == 64)
4579         return std::make_pair(0U, &AArch64::FPR64RegClass);
4580       if (VT.getSizeInBits() == 128)
4581         return std::make_pair(0U, &AArch64::FPR128RegClass);
4582       break;
4583     // The instructions that this constraint is designed for can
4584     // only take 128-bit registers so just use that regclass.
4585     case 'x':
4586       if (VT.getSizeInBits() == 128)
4587         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4588       break;
4589     }
4590   }
4591   if (StringRef("{cc}").equals_lower(Constraint))
4592     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4593
4594   // Use the default implementation in TargetLowering to convert the register
4595   // constraint into a member of a register class.
4596   std::pair<unsigned, const TargetRegisterClass *> Res;
4597   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4598
4599   // Not found as a standard register?
4600   if (!Res.second) {
4601     unsigned Size = Constraint.size();
4602     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4603         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4604       int RegNo;
4605       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4606       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4607         // v0 - v31 are aliases of q0 - q31.
4608         // By default we'll emit v0-v31 for this unless there's a modifier where
4609         // we'll emit the correct register as well.
4610         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4611         Res.second = &AArch64::FPR128RegClass;
4612       }
4613     }
4614   }
4615
4616   return Res;
4617 }
4618
4619 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4620 /// vector.  If it is invalid, don't add anything to Ops.
4621 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4622     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4623     SelectionDAG &DAG) const {
4624   SDValue Result;
4625
4626   // Currently only support length 1 constraints.
4627   if (Constraint.length() != 1)
4628     return;
4629
4630   char ConstraintLetter = Constraint[0];
4631   switch (ConstraintLetter) {
4632   default:
4633     break;
4634
4635   // This set of constraints deal with valid constants for various instructions.
4636   // Validate and return a target constant for them if we can.
4637   case 'z': {
4638     // 'z' maps to xzr or wzr so it needs an input of 0.
4639     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4640     if (!C || C->getZExtValue() != 0)
4641       return;
4642
4643     if (Op.getValueType() == MVT::i64)
4644       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4645     else
4646       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4647     break;
4648   }
4649
4650   case 'I':
4651   case 'J':
4652   case 'K':
4653   case 'L':
4654   case 'M':
4655   case 'N':
4656     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4657     if (!C)
4658       return;
4659
4660     // Grab the value and do some validation.
4661     uint64_t CVal = C->getZExtValue();
4662     switch (ConstraintLetter) {
4663     // The I constraint applies only to simple ADD or SUB immediate operands:
4664     // i.e. 0 to 4095 with optional shift by 12
4665     // The J constraint applies only to ADD or SUB immediates that would be
4666     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4667     // instruction [or vice versa], in other words -1 to -4095 with optional
4668     // left shift by 12.
4669     case 'I':
4670       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4671         break;
4672       return;
4673     case 'J': {
4674       uint64_t NVal = -C->getSExtValue();
4675       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4676         CVal = C->getSExtValue();
4677         break;
4678       }
4679       return;
4680     }
4681     // The K and L constraints apply *only* to logical immediates, including
4682     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4683     // been removed and MOV should be used). So these constraints have to
4684     // distinguish between bit patterns that are valid 32-bit or 64-bit
4685     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4686     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4687     // versa.
4688     case 'K':
4689       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4690         break;
4691       return;
4692     case 'L':
4693       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4694         break;
4695       return;
4696     // The M and N constraints are a superset of K and L respectively, for use
4697     // with the MOV (immediate) alias. As well as the logical immediates they
4698     // also match 32 or 64-bit immediates that can be loaded either using a
4699     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4700     // (M) or 64-bit 0x1234000000000000 (N) etc.
4701     // As a note some of this code is liberally stolen from the asm parser.
4702     case 'M': {
4703       if (!isUInt<32>(CVal))
4704         return;
4705       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4706         break;
4707       if ((CVal & 0xFFFF) == CVal)
4708         break;
4709       if ((CVal & 0xFFFF0000ULL) == CVal)
4710         break;
4711       uint64_t NCVal = ~(uint32_t)CVal;
4712       if ((NCVal & 0xFFFFULL) == NCVal)
4713         break;
4714       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4715         break;
4716       return;
4717     }
4718     case 'N': {
4719       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4720         break;
4721       if ((CVal & 0xFFFFULL) == CVal)
4722         break;
4723       if ((CVal & 0xFFFF0000ULL) == CVal)
4724         break;
4725       if ((CVal & 0xFFFF00000000ULL) == CVal)
4726         break;
4727       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4728         break;
4729       uint64_t NCVal = ~CVal;
4730       if ((NCVal & 0xFFFFULL) == NCVal)
4731         break;
4732       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4733         break;
4734       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4735         break;
4736       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4737         break;
4738       return;
4739     }
4740     default:
4741       return;
4742     }
4743
4744     // All assembler immediates are 64-bit integers.
4745     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4746     break;
4747   }
4748
4749   if (Result.getNode()) {
4750     Ops.push_back(Result);
4751     return;
4752   }
4753
4754   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4755 }
4756
4757 //===----------------------------------------------------------------------===//
4758 //                     AArch64 Advanced SIMD Support
4759 //===----------------------------------------------------------------------===//
4760
4761 /// WidenVector - Given a value in the V64 register class, produce the
4762 /// equivalent value in the V128 register class.
4763 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4764   EVT VT = V64Reg.getValueType();
4765   unsigned NarrowSize = VT.getVectorNumElements();
4766   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4767   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4768   SDLoc DL(V64Reg);
4769
4770   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4771                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4772 }
4773
4774 /// getExtFactor - Determine the adjustment factor for the position when
4775 /// generating an "extract from vector registers" instruction.
4776 static unsigned getExtFactor(SDValue &V) {
4777   EVT EltType = V.getValueType().getVectorElementType();
4778   return EltType.getSizeInBits() / 8;
4779 }
4780
4781 /// NarrowVector - Given a value in the V128 register class, produce the
4782 /// equivalent value in the V64 register class.
4783 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4784   EVT VT = V128Reg.getValueType();
4785   unsigned WideSize = VT.getVectorNumElements();
4786   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4787   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4788   SDLoc DL(V128Reg);
4789
4790   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4791 }
4792
4793 // Gather data to see if the operation can be modelled as a
4794 // shuffle in combination with VEXTs.
4795 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4796                                                   SelectionDAG &DAG) const {
4797   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4798   SDLoc dl(Op);
4799   EVT VT = Op.getValueType();
4800   unsigned NumElts = VT.getVectorNumElements();
4801
4802   struct ShuffleSourceInfo {
4803     SDValue Vec;
4804     unsigned MinElt;
4805     unsigned MaxElt;
4806
4807     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4808     // be compatible with the shuffle we intend to construct. As a result
4809     // ShuffleVec will be some sliding window into the original Vec.
4810     SDValue ShuffleVec;
4811
4812     // Code should guarantee that element i in Vec starts at element "WindowBase
4813     // + i * WindowScale in ShuffleVec".
4814     int WindowBase;
4815     int WindowScale;
4816
4817     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4818     ShuffleSourceInfo(SDValue Vec)
4819         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4820           WindowScale(1) {}
4821   };
4822
4823   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4824   // node.
4825   SmallVector<ShuffleSourceInfo, 2> Sources;
4826   for (unsigned i = 0; i < NumElts; ++i) {
4827     SDValue V = Op.getOperand(i);
4828     if (V.getOpcode() == ISD::UNDEF)
4829       continue;
4830     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4831       // A shuffle can only come from building a vector from various
4832       // elements of other vectors.
4833       return SDValue();
4834     }
4835
4836     // Add this element source to the list if it's not already there.
4837     SDValue SourceVec = V.getOperand(0);
4838     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4839     if (Source == Sources.end())
4840       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4841
4842     // Update the minimum and maximum lane number seen.
4843     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4844     Source->MinElt = std::min(Source->MinElt, EltNo);
4845     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4846   }
4847
4848   // Currently only do something sane when at most two source vectors
4849   // are involved.
4850   if (Sources.size() > 2)
4851     return SDValue();
4852
4853   // Find out the smallest element size among result and two sources, and use
4854   // it as element size to build the shuffle_vector.
4855   EVT SmallestEltTy = VT.getVectorElementType();
4856   for (auto &Source : Sources) {
4857     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4858     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4859       SmallestEltTy = SrcEltTy;
4860     }
4861   }
4862   unsigned ResMultiplier =
4863       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4864   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4865   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4866
4867   // If the source vector is too wide or too narrow, we may nevertheless be able
4868   // to construct a compatible shuffle either by concatenating it with UNDEF or
4869   // extracting a suitable range of elements.
4870   for (auto &Src : Sources) {
4871     EVT SrcVT = Src.ShuffleVec.getValueType();
4872
4873     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4874       continue;
4875
4876     // This stage of the search produces a source with the same element type as
4877     // the original, but with a total width matching the BUILD_VECTOR output.
4878     EVT EltVT = SrcVT.getVectorElementType();
4879     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4880     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4881
4882     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4883       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4884       // We can pad out the smaller vector for free, so if it's part of a
4885       // shuffle...
4886       Src.ShuffleVec =
4887           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4888                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4889       continue;
4890     }
4891
4892     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4893
4894     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4895       // Span too large for a VEXT to cope
4896       return SDValue();
4897     }
4898
4899     if (Src.MinElt >= NumSrcElts) {
4900       // The extraction can just take the second half
4901       Src.ShuffleVec =
4902           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4903                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4904       Src.WindowBase = -NumSrcElts;
4905     } else if (Src.MaxElt < NumSrcElts) {
4906       // The extraction can just take the first half
4907       Src.ShuffleVec =
4908           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4909                       DAG.getConstant(0, dl, MVT::i64));
4910     } else {
4911       // An actual VEXT is needed
4912       SDValue VEXTSrc1 =
4913           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4914                       DAG.getConstant(0, dl, MVT::i64));
4915       SDValue VEXTSrc2 =
4916           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4917                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4918       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4919
4920       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4921                                    VEXTSrc2,
4922                                    DAG.getConstant(Imm, dl, MVT::i32));
4923       Src.WindowBase = -Src.MinElt;
4924     }
4925   }
4926
4927   // Another possible incompatibility occurs from the vector element types. We
4928   // can fix this by bitcasting the source vectors to the same type we intend
4929   // for the shuffle.
4930   for (auto &Src : Sources) {
4931     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4932     if (SrcEltTy == SmallestEltTy)
4933       continue;
4934     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4935     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4936     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4937     Src.WindowBase *= Src.WindowScale;
4938   }
4939
4940   // Final sanity check before we try to actually produce a shuffle.
4941   DEBUG(
4942     for (auto Src : Sources)
4943       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4944   );
4945
4946   // The stars all align, our next step is to produce the mask for the shuffle.
4947   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4948   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4949   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4950     SDValue Entry = Op.getOperand(i);
4951     if (Entry.getOpcode() == ISD::UNDEF)
4952       continue;
4953
4954     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4955     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4956
4957     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4958     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4959     // segment.
4960     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4961     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4962                                VT.getVectorElementType().getSizeInBits());
4963     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4964
4965     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4966     // starting at the appropriate offset.
4967     int *LaneMask = &Mask[i * ResMultiplier];
4968
4969     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4970     ExtractBase += NumElts * (Src - Sources.begin());
4971     for (int j = 0; j < LanesDefined; ++j)
4972       LaneMask[j] = ExtractBase + j;
4973   }
4974
4975   // Final check before we try to produce nonsense...
4976   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4977     return SDValue();
4978
4979   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4980   for (unsigned i = 0; i < Sources.size(); ++i)
4981     ShuffleOps[i] = Sources[i].ShuffleVec;
4982
4983   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4984                                          ShuffleOps[1], &Mask[0]);
4985   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4986 }
4987
4988 // check if an EXT instruction can handle the shuffle mask when the
4989 // vector sources of the shuffle are the same.
4990 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4991   unsigned NumElts = VT.getVectorNumElements();
4992
4993   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4994   if (M[0] < 0)
4995     return false;
4996
4997   Imm = M[0];
4998
4999   // If this is a VEXT shuffle, the immediate value is the index of the first
5000   // element.  The other shuffle indices must be the successive elements after
5001   // the first one.
5002   unsigned ExpectedElt = Imm;
5003   for (unsigned i = 1; i < NumElts; ++i) {
5004     // Increment the expected index.  If it wraps around, just follow it
5005     // back to index zero and keep going.
5006     ++ExpectedElt;
5007     if (ExpectedElt == NumElts)
5008       ExpectedElt = 0;
5009
5010     if (M[i] < 0)
5011       continue; // ignore UNDEF indices
5012     if (ExpectedElt != static_cast<unsigned>(M[i]))
5013       return false;
5014   }
5015
5016   return true;
5017 }
5018
5019 // check if an EXT instruction can handle the shuffle mask when the
5020 // vector sources of the shuffle are different.
5021 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5022                       unsigned &Imm) {
5023   // Look for the first non-undef element.
5024   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5025       [](int Elt) {return Elt >= 0;});
5026
5027   // Benefit form APInt to handle overflow when calculating expected element.
5028   unsigned NumElts = VT.getVectorNumElements();
5029   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5030   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5031   // The following shuffle indices must be the successive elements after the
5032   // first real element.
5033   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5034       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5035   if (FirstWrongElt != M.end())
5036     return false;
5037
5038   // The index of an EXT is the first element if it is not UNDEF.
5039   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5040   // value of the first element.  E.g. 
5041   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5042   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5043   // ExpectedElt is the last mask index plus 1.
5044   Imm = ExpectedElt.getZExtValue();
5045
5046   // There are two difference cases requiring to reverse input vectors.
5047   // For example, for vector <4 x i32> we have the following cases,
5048   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5049   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5050   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5051   // to reverse two input vectors.
5052   if (Imm < NumElts)
5053     ReverseEXT = true;
5054   else
5055     Imm -= NumElts;
5056
5057   return true;
5058 }
5059
5060 /// isREVMask - Check if a vector shuffle corresponds to a REV
5061 /// instruction with the specified blocksize.  (The order of the elements
5062 /// within each block of the vector is reversed.)
5063 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5064   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5065          "Only possible block sizes for REV are: 16, 32, 64");
5066
5067   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5068   if (EltSz == 64)
5069     return false;
5070
5071   unsigned NumElts = VT.getVectorNumElements();
5072   unsigned BlockElts = M[0] + 1;
5073   // If the first shuffle index is UNDEF, be optimistic.
5074   if (M[0] < 0)
5075     BlockElts = BlockSize / EltSz;
5076
5077   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5078     return false;
5079
5080   for (unsigned i = 0; i < NumElts; ++i) {
5081     if (M[i] < 0)
5082       continue; // ignore UNDEF indices
5083     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5084       return false;
5085   }
5086
5087   return true;
5088 }
5089
5090 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5091   unsigned NumElts = VT.getVectorNumElements();
5092   WhichResult = (M[0] == 0 ? 0 : 1);
5093   unsigned Idx = WhichResult * NumElts / 2;
5094   for (unsigned i = 0; i != NumElts; i += 2) {
5095     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5096         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5097       return false;
5098     Idx += 1;
5099   }
5100
5101   return true;
5102 }
5103
5104 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5105   unsigned NumElts = VT.getVectorNumElements();
5106   WhichResult = (M[0] == 0 ? 0 : 1);
5107   for (unsigned i = 0; i != NumElts; ++i) {
5108     if (M[i] < 0)
5109       continue; // ignore UNDEF indices
5110     if ((unsigned)M[i] != 2 * i + WhichResult)
5111       return false;
5112   }
5113
5114   return true;
5115 }
5116
5117 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5118   unsigned NumElts = VT.getVectorNumElements();
5119   WhichResult = (M[0] == 0 ? 0 : 1);
5120   for (unsigned i = 0; i < NumElts; i += 2) {
5121     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5122         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5123       return false;
5124   }
5125   return true;
5126 }
5127
5128 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5129 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5130 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5131 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5132   unsigned NumElts = VT.getVectorNumElements();
5133   WhichResult = (M[0] == 0 ? 0 : 1);
5134   unsigned Idx = WhichResult * NumElts / 2;
5135   for (unsigned i = 0; i != NumElts; i += 2) {
5136     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5137         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5138       return false;
5139     Idx += 1;
5140   }
5141
5142   return true;
5143 }
5144
5145 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5146 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5147 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5148 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5149   unsigned Half = VT.getVectorNumElements() / 2;
5150   WhichResult = (M[0] == 0 ? 0 : 1);
5151   for (unsigned j = 0; j != 2; ++j) {
5152     unsigned Idx = WhichResult;
5153     for (unsigned i = 0; i != Half; ++i) {
5154       int MIdx = M[i + j * Half];
5155       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5156         return false;
5157       Idx += 2;
5158     }
5159   }
5160
5161   return true;
5162 }
5163
5164 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5165 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5166 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5167 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5168   unsigned NumElts = VT.getVectorNumElements();
5169   WhichResult = (M[0] == 0 ? 0 : 1);
5170   for (unsigned i = 0; i < NumElts; i += 2) {
5171     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5172         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5173       return false;
5174   }
5175   return true;
5176 }
5177
5178 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5179                       bool &DstIsLeft, int &Anomaly) {
5180   if (M.size() != static_cast<size_t>(NumInputElements))
5181     return false;
5182
5183   int NumLHSMatch = 0, NumRHSMatch = 0;
5184   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5185
5186   for (int i = 0; i < NumInputElements; ++i) {
5187     if (M[i] == -1) {
5188       ++NumLHSMatch;
5189       ++NumRHSMatch;
5190       continue;
5191     }
5192
5193     if (M[i] == i)
5194       ++NumLHSMatch;
5195     else
5196       LastLHSMismatch = i;
5197
5198     if (M[i] == i + NumInputElements)
5199       ++NumRHSMatch;
5200     else
5201       LastRHSMismatch = i;
5202   }
5203
5204   if (NumLHSMatch == NumInputElements - 1) {
5205     DstIsLeft = true;
5206     Anomaly = LastLHSMismatch;
5207     return true;
5208   } else if (NumRHSMatch == NumInputElements - 1) {
5209     DstIsLeft = false;
5210     Anomaly = LastRHSMismatch;
5211     return true;
5212   }
5213
5214   return false;
5215 }
5216
5217 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5218   if (VT.getSizeInBits() != 128)
5219     return false;
5220
5221   unsigned NumElts = VT.getVectorNumElements();
5222
5223   for (int I = 0, E = NumElts / 2; I != E; I++) {
5224     if (Mask[I] != I)
5225       return false;
5226   }
5227
5228   int Offset = NumElts / 2;
5229   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5230     if (Mask[I] != I + SplitLHS * Offset)
5231       return false;
5232   }
5233
5234   return true;
5235 }
5236
5237 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5238   SDLoc DL(Op);
5239   EVT VT = Op.getValueType();
5240   SDValue V0 = Op.getOperand(0);
5241   SDValue V1 = Op.getOperand(1);
5242   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5243
5244   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5245       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5246     return SDValue();
5247
5248   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5249
5250   if (!isConcatMask(Mask, VT, SplitV0))
5251     return SDValue();
5252
5253   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5254                                 VT.getVectorNumElements() / 2);
5255   if (SplitV0) {
5256     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5257                      DAG.getConstant(0, DL, MVT::i64));
5258   }
5259   if (V1.getValueType().getSizeInBits() == 128) {
5260     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5261                      DAG.getConstant(0, DL, MVT::i64));
5262   }
5263   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5264 }
5265
5266 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5267 /// the specified operations to build the shuffle.
5268 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5269                                       SDValue RHS, SelectionDAG &DAG,
5270                                       SDLoc dl) {
5271   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5272   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5273   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5274
5275   enum {
5276     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5277     OP_VREV,
5278     OP_VDUP0,
5279     OP_VDUP1,
5280     OP_VDUP2,
5281     OP_VDUP3,
5282     OP_VEXT1,
5283     OP_VEXT2,
5284     OP_VEXT3,
5285     OP_VUZPL, // VUZP, left result
5286     OP_VUZPR, // VUZP, right result
5287     OP_VZIPL, // VZIP, left result
5288     OP_VZIPR, // VZIP, right result
5289     OP_VTRNL, // VTRN, left result
5290     OP_VTRNR  // VTRN, right result
5291   };
5292
5293   if (OpNum == OP_COPY) {
5294     if (LHSID == (1 * 9 + 2) * 9 + 3)
5295       return LHS;
5296     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5297     return RHS;
5298   }
5299
5300   SDValue OpLHS, OpRHS;
5301   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5302   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5303   EVT VT = OpLHS.getValueType();
5304
5305   switch (OpNum) {
5306   default:
5307     llvm_unreachable("Unknown shuffle opcode!");
5308   case OP_VREV:
5309     // VREV divides the vector in half and swaps within the half.
5310     if (VT.getVectorElementType() == MVT::i32 ||
5311         VT.getVectorElementType() == MVT::f32)
5312       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5313     // vrev <4 x i16> -> REV32
5314     if (VT.getVectorElementType() == MVT::i16 ||
5315         VT.getVectorElementType() == MVT::f16)
5316       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5317     // vrev <4 x i8> -> REV16
5318     assert(VT.getVectorElementType() == MVT::i8);
5319     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5320   case OP_VDUP0:
5321   case OP_VDUP1:
5322   case OP_VDUP2:
5323   case OP_VDUP3: {
5324     EVT EltTy = VT.getVectorElementType();
5325     unsigned Opcode;
5326     if (EltTy == MVT::i8)
5327       Opcode = AArch64ISD::DUPLANE8;
5328     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5329       Opcode = AArch64ISD::DUPLANE16;
5330     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5331       Opcode = AArch64ISD::DUPLANE32;
5332     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5333       Opcode = AArch64ISD::DUPLANE64;
5334     else
5335       llvm_unreachable("Invalid vector element type?");
5336
5337     if (VT.getSizeInBits() == 64)
5338       OpLHS = WidenVector(OpLHS, DAG);
5339     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5340     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5341   }
5342   case OP_VEXT1:
5343   case OP_VEXT2:
5344   case OP_VEXT3: {
5345     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5346     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5347                        DAG.getConstant(Imm, dl, MVT::i32));
5348   }
5349   case OP_VUZPL:
5350     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5351                        OpRHS);
5352   case OP_VUZPR:
5353     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5354                        OpRHS);
5355   case OP_VZIPL:
5356     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5357                        OpRHS);
5358   case OP_VZIPR:
5359     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5360                        OpRHS);
5361   case OP_VTRNL:
5362     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5363                        OpRHS);
5364   case OP_VTRNR:
5365     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5366                        OpRHS);
5367   }
5368 }
5369
5370 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5371                            SelectionDAG &DAG) {
5372   // Check to see if we can use the TBL instruction.
5373   SDValue V1 = Op.getOperand(0);
5374   SDValue V2 = Op.getOperand(1);
5375   SDLoc DL(Op);
5376
5377   EVT EltVT = Op.getValueType().getVectorElementType();
5378   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5379
5380   SmallVector<SDValue, 8> TBLMask;
5381   for (int Val : ShuffleMask) {
5382     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5383       unsigned Offset = Byte + Val * BytesPerElt;
5384       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5385     }
5386   }
5387
5388   MVT IndexVT = MVT::v8i8;
5389   unsigned IndexLen = 8;
5390   if (Op.getValueType().getSizeInBits() == 128) {
5391     IndexVT = MVT::v16i8;
5392     IndexLen = 16;
5393   }
5394
5395   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5396   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5397
5398   SDValue Shuffle;
5399   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5400     if (IndexLen == 8)
5401       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5402     Shuffle = DAG.getNode(
5403         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5404         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5405         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5406                     makeArrayRef(TBLMask.data(), IndexLen)));
5407   } else {
5408     if (IndexLen == 8) {
5409       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5410       Shuffle = DAG.getNode(
5411           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5412           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5413           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5414                       makeArrayRef(TBLMask.data(), IndexLen)));
5415     } else {
5416       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5417       // cannot currently represent the register constraints on the input
5418       // table registers.
5419       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5420       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5421       //                               &TBLMask[0], IndexLen));
5422       Shuffle = DAG.getNode(
5423           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5424           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5425           V1Cst, V2Cst,
5426           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5427                       makeArrayRef(TBLMask.data(), IndexLen)));
5428     }
5429   }
5430   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5431 }
5432
5433 static unsigned getDUPLANEOp(EVT EltType) {
5434   if (EltType == MVT::i8)
5435     return AArch64ISD::DUPLANE8;
5436   if (EltType == MVT::i16 || EltType == MVT::f16)
5437     return AArch64ISD::DUPLANE16;
5438   if (EltType == MVT::i32 || EltType == MVT::f32)
5439     return AArch64ISD::DUPLANE32;
5440   if (EltType == MVT::i64 || EltType == MVT::f64)
5441     return AArch64ISD::DUPLANE64;
5442
5443   llvm_unreachable("Invalid vector element type?");
5444 }
5445
5446 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5447                                                    SelectionDAG &DAG) const {
5448   SDLoc dl(Op);
5449   EVT VT = Op.getValueType();
5450
5451   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5452
5453   // Convert shuffles that are directly supported on NEON to target-specific
5454   // DAG nodes, instead of keeping them as shuffles and matching them again
5455   // during code selection.  This is more efficient and avoids the possibility
5456   // of inconsistencies between legalization and selection.
5457   ArrayRef<int> ShuffleMask = SVN->getMask();
5458
5459   SDValue V1 = Op.getOperand(0);
5460   SDValue V2 = Op.getOperand(1);
5461
5462   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5463                                        V1.getValueType().getSimpleVT())) {
5464     int Lane = SVN->getSplatIndex();
5465     // If this is undef splat, generate it via "just" vdup, if possible.
5466     if (Lane == -1)
5467       Lane = 0;
5468
5469     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5470       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5471                          V1.getOperand(0));
5472     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5473     // constant. If so, we can just reference the lane's definition directly.
5474     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5475         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5476       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5477
5478     // Otherwise, duplicate from the lane of the input vector.
5479     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5480
5481     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5482     // to make a vector of the same size as this SHUFFLE. We can ignore the
5483     // extract entirely, and canonicalise the concat using WidenVector.
5484     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5485       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5486       V1 = V1.getOperand(0);
5487     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5488       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5489       Lane -= Idx * VT.getVectorNumElements() / 2;
5490       V1 = WidenVector(V1.getOperand(Idx), DAG);
5491     } else if (VT.getSizeInBits() == 64)
5492       V1 = WidenVector(V1, DAG);
5493
5494     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5495   }
5496
5497   if (isREVMask(ShuffleMask, VT, 64))
5498     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5499   if (isREVMask(ShuffleMask, VT, 32))
5500     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5501   if (isREVMask(ShuffleMask, VT, 16))
5502     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5503
5504   bool ReverseEXT = false;
5505   unsigned Imm;
5506   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5507     if (ReverseEXT)
5508       std::swap(V1, V2);
5509     Imm *= getExtFactor(V1);
5510     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5511                        DAG.getConstant(Imm, dl, MVT::i32));
5512   } else if (V2->getOpcode() == ISD::UNDEF &&
5513              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5514     Imm *= getExtFactor(V1);
5515     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5516                        DAG.getConstant(Imm, dl, MVT::i32));
5517   }
5518
5519   unsigned WhichResult;
5520   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5521     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5522     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5523   }
5524   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5525     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5526     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5527   }
5528   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5529     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5530     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5531   }
5532
5533   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5534     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5535     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5536   }
5537   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5538     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5539     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5540   }
5541   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5542     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5543     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5544   }
5545
5546   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5547   if (Concat.getNode())
5548     return Concat;
5549
5550   bool DstIsLeft;
5551   int Anomaly;
5552   int NumInputElements = V1.getValueType().getVectorNumElements();
5553   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5554     SDValue DstVec = DstIsLeft ? V1 : V2;
5555     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5556
5557     SDValue SrcVec = V1;
5558     int SrcLane = ShuffleMask[Anomaly];
5559     if (SrcLane >= NumInputElements) {
5560       SrcVec = V2;
5561       SrcLane -= VT.getVectorNumElements();
5562     }
5563     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5564
5565     EVT ScalarVT = VT.getVectorElementType();
5566
5567     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5568       ScalarVT = MVT::i32;
5569
5570     return DAG.getNode(
5571         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5572         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5573         DstLaneV);
5574   }
5575
5576   // If the shuffle is not directly supported and it has 4 elements, use
5577   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5578   unsigned NumElts = VT.getVectorNumElements();
5579   if (NumElts == 4) {
5580     unsigned PFIndexes[4];
5581     for (unsigned i = 0; i != 4; ++i) {
5582       if (ShuffleMask[i] < 0)
5583         PFIndexes[i] = 8;
5584       else
5585         PFIndexes[i] = ShuffleMask[i];
5586     }
5587
5588     // Compute the index in the perfect shuffle table.
5589     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5590                             PFIndexes[2] * 9 + PFIndexes[3];
5591     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5592     unsigned Cost = (PFEntry >> 30);
5593
5594     if (Cost <= 4)
5595       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5596   }
5597
5598   return GenerateTBL(Op, ShuffleMask, DAG);
5599 }
5600
5601 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5602                                APInt &UndefBits) {
5603   EVT VT = BVN->getValueType(0);
5604   APInt SplatBits, SplatUndef;
5605   unsigned SplatBitSize;
5606   bool HasAnyUndefs;
5607   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5608     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5609
5610     for (unsigned i = 0; i < NumSplats; ++i) {
5611       CnstBits <<= SplatBitSize;
5612       UndefBits <<= SplatBitSize;
5613       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5614       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5615     }
5616
5617     return true;
5618   }
5619
5620   return false;
5621 }
5622
5623 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5624                                               SelectionDAG &DAG) const {
5625   BuildVectorSDNode *BVN =
5626       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5627   SDValue LHS = Op.getOperand(0);
5628   SDLoc dl(Op);
5629   EVT VT = Op.getValueType();
5630
5631   if (!BVN)
5632     return Op;
5633
5634   APInt CnstBits(VT.getSizeInBits(), 0);
5635   APInt UndefBits(VT.getSizeInBits(), 0);
5636   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5637     // We only have BIC vector immediate instruction, which is and-not.
5638     CnstBits = ~CnstBits;
5639
5640     // We make use of a little bit of goto ickiness in order to avoid having to
5641     // duplicate the immediate matching logic for the undef toggled case.
5642     bool SecondTry = false;
5643   AttemptModImm:
5644
5645     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5646       CnstBits = CnstBits.zextOrTrunc(64);
5647       uint64_t CnstVal = CnstBits.getZExtValue();
5648
5649       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5650         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5651         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5652         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5653                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5654                                   DAG.getConstant(0, dl, MVT::i32));
5655         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5656       }
5657
5658       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5659         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5660         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5661         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5662                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5663                                   DAG.getConstant(8, dl, MVT::i32));
5664         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5665       }
5666
5667       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5668         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5669         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5670         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5671                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5672                                   DAG.getConstant(16, dl, MVT::i32));
5673         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5674       }
5675
5676       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5677         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5678         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5679         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5680                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5681                                   DAG.getConstant(24, dl, MVT::i32));
5682         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5683       }
5684
5685       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5686         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5687         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5688         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5689                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5690                                   DAG.getConstant(0, dl, MVT::i32));
5691         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5692       }
5693
5694       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5695         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5696         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5697         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5698                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5699                                   DAG.getConstant(8, dl, MVT::i32));
5700         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5701       }
5702     }
5703
5704     if (SecondTry)
5705       goto FailedModImm;
5706     SecondTry = true;
5707     CnstBits = ~UndefBits;
5708     goto AttemptModImm;
5709   }
5710
5711 // We can always fall back to a non-immediate AND.
5712 FailedModImm:
5713   return Op;
5714 }
5715
5716 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5717 // consists of only the same constant int value, returned in reference arg
5718 // ConstVal
5719 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5720                                      uint64_t &ConstVal) {
5721   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5722   if (!Bvec)
5723     return false;
5724   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5725   if (!FirstElt)
5726     return false;
5727   EVT VT = Bvec->getValueType(0);
5728   unsigned NumElts = VT.getVectorNumElements();
5729   for (unsigned i = 1; i < NumElts; ++i)
5730     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5731       return false;
5732   ConstVal = FirstElt->getZExtValue();
5733   return true;
5734 }
5735
5736 static unsigned getIntrinsicID(const SDNode *N) {
5737   unsigned Opcode = N->getOpcode();
5738   switch (Opcode) {
5739   default:
5740     return Intrinsic::not_intrinsic;
5741   case ISD::INTRINSIC_WO_CHAIN: {
5742     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5743     if (IID < Intrinsic::num_intrinsics)
5744       return IID;
5745     return Intrinsic::not_intrinsic;
5746   }
5747   }
5748 }
5749
5750 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5751 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5752 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5753 // Also, logical shift right -> sri, with the same structure.
5754 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5755   EVT VT = N->getValueType(0);
5756
5757   if (!VT.isVector())
5758     return SDValue();
5759
5760   SDLoc DL(N);
5761
5762   // Is the first op an AND?
5763   const SDValue And = N->getOperand(0);
5764   if (And.getOpcode() != ISD::AND)
5765     return SDValue();
5766
5767   // Is the second op an shl or lshr?
5768   SDValue Shift = N->getOperand(1);
5769   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5770   // or AArch64ISD::VLSHR vector, #shift
5771   unsigned ShiftOpc = Shift.getOpcode();
5772   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5773     return SDValue();
5774   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5775
5776   // Is the shift amount constant?
5777   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5778   if (!C2node)
5779     return SDValue();
5780
5781   // Is the and mask vector all constant?
5782   uint64_t C1;
5783   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5784     return SDValue();
5785
5786   // Is C1 == ~C2, taking into account how much one can shift elements of a
5787   // particular size?
5788   uint64_t C2 = C2node->getZExtValue();
5789   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5790   if (C2 > ElemSizeInBits)
5791     return SDValue();
5792   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5793   if ((C1 & ElemMask) != (~C2 & ElemMask))
5794     return SDValue();
5795
5796   SDValue X = And.getOperand(0);
5797   SDValue Y = Shift.getOperand(0);
5798
5799   unsigned Intrin =
5800       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5801   SDValue ResultSLI =
5802       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5803                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5804                   Shift.getOperand(1));
5805
5806   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5807   DEBUG(N->dump(&DAG));
5808   DEBUG(dbgs() << "into: \n");
5809   DEBUG(ResultSLI->dump(&DAG));
5810
5811   ++NumShiftInserts;
5812   return ResultSLI;
5813 }
5814
5815 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5816                                              SelectionDAG &DAG) const {
5817   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5818   if (EnableAArch64SlrGeneration) {
5819     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5820     if (Res.getNode())
5821       return Res;
5822   }
5823
5824   BuildVectorSDNode *BVN =
5825       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5826   SDValue LHS = Op.getOperand(1);
5827   SDLoc dl(Op);
5828   EVT VT = Op.getValueType();
5829
5830   // OR commutes, so try swapping the operands.
5831   if (!BVN) {
5832     LHS = Op.getOperand(0);
5833     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5834   }
5835   if (!BVN)
5836     return Op;
5837
5838   APInt CnstBits(VT.getSizeInBits(), 0);
5839   APInt UndefBits(VT.getSizeInBits(), 0);
5840   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5841     // We make use of a little bit of goto ickiness in order to avoid having to
5842     // duplicate the immediate matching logic for the undef toggled case.
5843     bool SecondTry = false;
5844   AttemptModImm:
5845
5846     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5847       CnstBits = CnstBits.zextOrTrunc(64);
5848       uint64_t CnstVal = CnstBits.getZExtValue();
5849
5850       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5851         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5852         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5853         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5854                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5855                                   DAG.getConstant(0, dl, MVT::i32));
5856         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5857       }
5858
5859       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5860         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5861         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5862         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5863                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5864                                   DAG.getConstant(8, dl, MVT::i32));
5865         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5866       }
5867
5868       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5869         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5870         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5871         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5872                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5873                                   DAG.getConstant(16, dl, MVT::i32));
5874         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5875       }
5876
5877       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5878         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5879         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5880         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5881                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5882                                   DAG.getConstant(24, dl, MVT::i32));
5883         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5884       }
5885
5886       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5887         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5888         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5889         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5890                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5891                                   DAG.getConstant(0, dl, MVT::i32));
5892         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5893       }
5894
5895       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5896         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5897         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5898         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5899                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5900                                   DAG.getConstant(8, dl, MVT::i32));
5901         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5902       }
5903     }
5904
5905     if (SecondTry)
5906       goto FailedModImm;
5907     SecondTry = true;
5908     CnstBits = UndefBits;
5909     goto AttemptModImm;
5910   }
5911
5912 // We can always fall back to a non-immediate OR.
5913 FailedModImm:
5914   return Op;
5915 }
5916
5917 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5918 // be truncated to fit element width.
5919 static SDValue NormalizeBuildVector(SDValue Op,
5920                                     SelectionDAG &DAG) {
5921   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5922   SDLoc dl(Op);
5923   EVT VT = Op.getValueType();
5924   EVT EltTy= VT.getVectorElementType();
5925
5926   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5927     return Op;
5928
5929   SmallVector<SDValue, 16> Ops;
5930   for (SDValue Lane : Op->ops()) {
5931     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5932       APInt LowBits(EltTy.getSizeInBits(),
5933                     CstLane->getZExtValue());
5934       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5935     }
5936     Ops.push_back(Lane);
5937   }
5938   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5939 }
5940
5941 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5942                                                  SelectionDAG &DAG) const {
5943   SDLoc dl(Op);
5944   EVT VT = Op.getValueType();
5945   Op = NormalizeBuildVector(Op, DAG);
5946   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5947
5948   APInt CnstBits(VT.getSizeInBits(), 0);
5949   APInt UndefBits(VT.getSizeInBits(), 0);
5950   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5951     // We make use of a little bit of goto ickiness in order to avoid having to
5952     // duplicate the immediate matching logic for the undef toggled case.
5953     bool SecondTry = false;
5954   AttemptModImm:
5955
5956     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5957       CnstBits = CnstBits.zextOrTrunc(64);
5958       uint64_t CnstVal = CnstBits.getZExtValue();
5959
5960       // Certain magic vector constants (used to express things like NOT
5961       // and NEG) are passed through unmodified.  This allows codegen patterns
5962       // for these operations to match.  Special-purpose patterns will lower
5963       // these immediates to MOVIs if it proves necessary.
5964       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5965         return Op;
5966
5967       // The many faces of MOVI...
5968       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5969         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5970         if (VT.getSizeInBits() == 128) {
5971           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5972                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5973           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5974         }
5975
5976         // Support the V64 version via subregister insertion.
5977         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5978                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5979         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5980       }
5981
5982       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5983         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5984         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5985         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5986                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5987                                   DAG.getConstant(0, dl, MVT::i32));
5988         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5989       }
5990
5991       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5992         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5993         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5994         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5995                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5996                                   DAG.getConstant(8, dl, MVT::i32));
5997         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5998       }
5999
6000       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6001         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6002         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6003         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6004                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6005                                   DAG.getConstant(16, dl, MVT::i32));
6006         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6007       }
6008
6009       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6010         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6011         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6012         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6013                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6014                                   DAG.getConstant(24, dl, MVT::i32));
6015         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6016       }
6017
6018       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6019         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6020         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6021         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6022                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6023                                   DAG.getConstant(0, dl, MVT::i32));
6024         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6025       }
6026
6027       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6028         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6029         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6030         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6031                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6032                                   DAG.getConstant(8, dl, MVT::i32));
6033         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6034       }
6035
6036       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6037         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6038         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6039         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6040                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6041                                   DAG.getConstant(264, dl, MVT::i32));
6042         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6043       }
6044
6045       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6046         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6047         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6048         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6049                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6050                                   DAG.getConstant(272, dl, MVT::i32));
6051         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6052       }
6053
6054       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6055         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6056         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6057         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6058                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6059         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6060       }
6061
6062       // The few faces of FMOV...
6063       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6064         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6065         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6066         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6067                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6068         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6069       }
6070
6071       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6072           VT.getSizeInBits() == 128) {
6073         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6074         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6075                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6076         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6077       }
6078
6079       // The many faces of MVNI...
6080       CnstVal = ~CnstVal;
6081       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6082         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6083         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6084         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6085                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6086                                   DAG.getConstant(0, dl, MVT::i32));
6087         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6088       }
6089
6090       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6091         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6092         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6093         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6094                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6095                                   DAG.getConstant(8, dl, MVT::i32));
6096         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6097       }
6098
6099       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6100         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6101         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6102         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6103                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6104                                   DAG.getConstant(16, dl, MVT::i32));
6105         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6106       }
6107
6108       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6109         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6110         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6111         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6112                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6113                                   DAG.getConstant(24, dl, MVT::i32));
6114         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6115       }
6116
6117       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6118         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6119         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6120         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6121                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6122                                   DAG.getConstant(0, dl, MVT::i32));
6123         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6124       }
6125
6126       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6127         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6128         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6129         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6130                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6131                                   DAG.getConstant(8, dl, MVT::i32));
6132         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6133       }
6134
6135       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6136         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6137         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6138         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6139                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6140                                   DAG.getConstant(264, dl, MVT::i32));
6141         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6142       }
6143
6144       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6145         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6146         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6147         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6148                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6149                                   DAG.getConstant(272, dl, MVT::i32));
6150         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6151       }
6152     }
6153
6154     if (SecondTry)
6155       goto FailedModImm;
6156     SecondTry = true;
6157     CnstBits = UndefBits;
6158     goto AttemptModImm;
6159   }
6160 FailedModImm:
6161
6162   // Scan through the operands to find some interesting properties we can
6163   // exploit:
6164   //   1) If only one value is used, we can use a DUP, or
6165   //   2) if only the low element is not undef, we can just insert that, or
6166   //   3) if only one constant value is used (w/ some non-constant lanes),
6167   //      we can splat the constant value into the whole vector then fill
6168   //      in the non-constant lanes.
6169   //   4) FIXME: If different constant values are used, but we can intelligently
6170   //             select the values we'll be overwriting for the non-constant
6171   //             lanes such that we can directly materialize the vector
6172   //             some other way (MOVI, e.g.), we can be sneaky.
6173   unsigned NumElts = VT.getVectorNumElements();
6174   bool isOnlyLowElement = true;
6175   bool usesOnlyOneValue = true;
6176   bool usesOnlyOneConstantValue = true;
6177   bool isConstant = true;
6178   unsigned NumConstantLanes = 0;
6179   SDValue Value;
6180   SDValue ConstantValue;
6181   for (unsigned i = 0; i < NumElts; ++i) {
6182     SDValue V = Op.getOperand(i);
6183     if (V.getOpcode() == ISD::UNDEF)
6184       continue;
6185     if (i > 0)
6186       isOnlyLowElement = false;
6187     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6188       isConstant = false;
6189
6190     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6191       ++NumConstantLanes;
6192       if (!ConstantValue.getNode())
6193         ConstantValue = V;
6194       else if (ConstantValue != V)
6195         usesOnlyOneConstantValue = false;
6196     }
6197
6198     if (!Value.getNode())
6199       Value = V;
6200     else if (V != Value)
6201       usesOnlyOneValue = false;
6202   }
6203
6204   if (!Value.getNode())
6205     return DAG.getUNDEF(VT);
6206
6207   if (isOnlyLowElement)
6208     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6209
6210   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6211   // i32 and try again.
6212   if (usesOnlyOneValue) {
6213     if (!isConstant) {
6214       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6215           Value.getValueType() != VT)
6216         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6217
6218       // This is actually a DUPLANExx operation, which keeps everything vectory.
6219
6220       // DUPLANE works on 128-bit vectors, widen it if necessary.
6221       SDValue Lane = Value.getOperand(1);
6222       Value = Value.getOperand(0);
6223       if (Value.getValueType().getSizeInBits() == 64)
6224         Value = WidenVector(Value, DAG);
6225
6226       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6227       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6228     }
6229
6230     if (VT.getVectorElementType().isFloatingPoint()) {
6231       SmallVector<SDValue, 8> Ops;
6232       EVT EltTy = VT.getVectorElementType();
6233       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6234               "Unsupported floating-point vector type");
6235       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6236       for (unsigned i = 0; i < NumElts; ++i)
6237         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6238       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6239       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6240       Val = LowerBUILD_VECTOR(Val, DAG);
6241       if (Val.getNode())
6242         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6243     }
6244   }
6245
6246   // If there was only one constant value used and for more than one lane,
6247   // start by splatting that value, then replace the non-constant lanes. This
6248   // is better than the default, which will perform a separate initialization
6249   // for each lane.
6250   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6251     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6252     // Now insert the non-constant lanes.
6253     for (unsigned i = 0; i < NumElts; ++i) {
6254       SDValue V = Op.getOperand(i);
6255       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6256       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6257         // Note that type legalization likely mucked about with the VT of the
6258         // source operand, so we may have to convert it here before inserting.
6259         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6260       }
6261     }
6262     return Val;
6263   }
6264
6265   // If all elements are constants and the case above didn't get hit, fall back
6266   // to the default expansion, which will generate a load from the constant
6267   // pool.
6268   if (isConstant)
6269     return SDValue();
6270
6271   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6272   if (NumElts >= 4) {
6273     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6274       return shuffle;
6275   }
6276
6277   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6278   // know the default expansion would otherwise fall back on something even
6279   // worse. For a vector with one or two non-undef values, that's
6280   // scalar_to_vector for the elements followed by a shuffle (provided the
6281   // shuffle is valid for the target) and materialization element by element
6282   // on the stack followed by a load for everything else.
6283   if (!isConstant && !usesOnlyOneValue) {
6284     SDValue Vec = DAG.getUNDEF(VT);
6285     SDValue Op0 = Op.getOperand(0);
6286     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6287     unsigned i = 0;
6288     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6289     // a) Avoid a RMW dependency on the full vector register, and
6290     // b) Allow the register coalescer to fold away the copy if the
6291     //    value is already in an S or D register.
6292     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6293     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6294     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6295         (ElemSize == 32 || ElemSize == 64)) {
6296       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6297       MachineSDNode *N =
6298           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6299                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6300       Vec = SDValue(N, 0);
6301       ++i;
6302     }
6303     for (; i < NumElts; ++i) {
6304       SDValue V = Op.getOperand(i);
6305       if (V.getOpcode() == ISD::UNDEF)
6306         continue;
6307       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6308       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6309     }
6310     return Vec;
6311   }
6312
6313   // Just use the default expansion. We failed to find a better alternative.
6314   return SDValue();
6315 }
6316
6317 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6318                                                       SelectionDAG &DAG) const {
6319   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6320
6321   // Check for non-constant or out of range lane.
6322   EVT VT = Op.getOperand(0).getValueType();
6323   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6324   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6325     return SDValue();
6326
6327
6328   // Insertion/extraction are legal for V128 types.
6329   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6330       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6331       VT == MVT::v8f16)
6332     return Op;
6333
6334   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6335       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6336     return SDValue();
6337
6338   // For V64 types, we perform insertion by expanding the value
6339   // to a V128 type and perform the insertion on that.
6340   SDLoc DL(Op);
6341   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6342   EVT WideTy = WideVec.getValueType();
6343
6344   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6345                              Op.getOperand(1), Op.getOperand(2));
6346   // Re-narrow the resultant vector.
6347   return NarrowVector(Node, DAG);
6348 }
6349
6350 SDValue
6351 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6352                                                SelectionDAG &DAG) const {
6353   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6354
6355   // Check for non-constant or out of range lane.
6356   EVT VT = Op.getOperand(0).getValueType();
6357   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6358   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6359     return SDValue();
6360
6361
6362   // Insertion/extraction are legal for V128 types.
6363   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6364       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6365       VT == MVT::v8f16)
6366     return Op;
6367
6368   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6369       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6370     return SDValue();
6371
6372   // For V64 types, we perform extraction by expanding the value
6373   // to a V128 type and perform the extraction on that.
6374   SDLoc DL(Op);
6375   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6376   EVT WideTy = WideVec.getValueType();
6377
6378   EVT ExtrTy = WideTy.getVectorElementType();
6379   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6380     ExtrTy = MVT::i32;
6381
6382   // For extractions, we just return the result directly.
6383   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6384                      Op.getOperand(1));
6385 }
6386
6387 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6388                                                       SelectionDAG &DAG) const {
6389   EVT VT = Op.getOperand(0).getValueType();
6390   SDLoc dl(Op);
6391   // Just in case...
6392   if (!VT.isVector())
6393     return SDValue();
6394
6395   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6396   if (!Cst)
6397     return SDValue();
6398   unsigned Val = Cst->getZExtValue();
6399
6400   unsigned Size = Op.getValueType().getSizeInBits();
6401   if (Val == 0) {
6402     switch (Size) {
6403     case 8:
6404       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6405                                         Op.getOperand(0));
6406     case 16:
6407       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6408                                         Op.getOperand(0));
6409     case 32:
6410       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6411                                         Op.getOperand(0));
6412     case 64:
6413       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6414                                         Op.getOperand(0));
6415     default:
6416       llvm_unreachable("Unexpected vector type in extract_subvector!");
6417     }
6418   }
6419   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6420   // that directly.
6421   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6422     return Op;
6423
6424   return SDValue();
6425 }
6426
6427 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6428                                                EVT VT) const {
6429   if (VT.getVectorNumElements() == 4 &&
6430       (VT.is128BitVector() || VT.is64BitVector())) {
6431     unsigned PFIndexes[4];
6432     for (unsigned i = 0; i != 4; ++i) {
6433       if (M[i] < 0)
6434         PFIndexes[i] = 8;
6435       else
6436         PFIndexes[i] = M[i];
6437     }
6438
6439     // Compute the index in the perfect shuffle table.
6440     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6441                             PFIndexes[2] * 9 + PFIndexes[3];
6442     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6443     unsigned Cost = (PFEntry >> 30);
6444
6445     if (Cost <= 4)
6446       return true;
6447   }
6448
6449   bool DummyBool;
6450   int DummyInt;
6451   unsigned DummyUnsigned;
6452
6453   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6454           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6455           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6456           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6457           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6458           isZIPMask(M, VT, DummyUnsigned) ||
6459           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6460           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6461           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6462           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6463           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6464 }
6465
6466 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6467 /// operand of a vector shift operation, where all the elements of the
6468 /// build_vector must have the same constant integer value.
6469 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6470   // Ignore bit_converts.
6471   while (Op.getOpcode() == ISD::BITCAST)
6472     Op = Op.getOperand(0);
6473   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6474   APInt SplatBits, SplatUndef;
6475   unsigned SplatBitSize;
6476   bool HasAnyUndefs;
6477   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6478                                     HasAnyUndefs, ElementBits) ||
6479       SplatBitSize > ElementBits)
6480     return false;
6481   Cnt = SplatBits.getSExtValue();
6482   return true;
6483 }
6484
6485 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6486 /// operand of a vector shift left operation.  That value must be in the range:
6487 ///   0 <= Value < ElementBits for a left shift; or
6488 ///   0 <= Value <= ElementBits for a long left shift.
6489 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6490   assert(VT.isVector() && "vector shift count is not a vector type");
6491   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6492   if (!getVShiftImm(Op, ElementBits, Cnt))
6493     return false;
6494   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6495 }
6496
6497 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6498 /// operand of a vector shift right operation. The value must be in the range:
6499 ///   1 <= Value <= ElementBits for a right shift; or
6500 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6501   assert(VT.isVector() && "vector shift count is not a vector type");
6502   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6503   if (!getVShiftImm(Op, ElementBits, Cnt))
6504     return false;
6505   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6506 }
6507
6508 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6509                                                       SelectionDAG &DAG) const {
6510   EVT VT = Op.getValueType();
6511   SDLoc DL(Op);
6512   int64_t Cnt;
6513
6514   if (!Op.getOperand(1).getValueType().isVector())
6515     return Op;
6516   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6517
6518   switch (Op.getOpcode()) {
6519   default:
6520     llvm_unreachable("unexpected shift opcode");
6521
6522   case ISD::SHL:
6523     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6524       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6525                          DAG.getConstant(Cnt, DL, MVT::i32));
6526     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6527                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6528                                        MVT::i32),
6529                        Op.getOperand(0), Op.getOperand(1));
6530   case ISD::SRA:
6531   case ISD::SRL:
6532     // Right shift immediate
6533     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6534       unsigned Opc =
6535           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6536       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6537                          DAG.getConstant(Cnt, DL, MVT::i32));
6538     }
6539
6540     // Right shift register.  Note, there is not a shift right register
6541     // instruction, but the shift left register instruction takes a signed
6542     // value, where negative numbers specify a right shift.
6543     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6544                                                 : Intrinsic::aarch64_neon_ushl;
6545     // negate the shift amount
6546     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6547     SDValue NegShiftLeft =
6548         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6549                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6550                     NegShift);
6551     return NegShiftLeft;
6552   }
6553
6554   return SDValue();
6555 }
6556
6557 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6558                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6559                                     SDLoc dl, SelectionDAG &DAG) {
6560   EVT SrcVT = LHS.getValueType();
6561   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6562          "function only supposed to emit natural comparisons");
6563
6564   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6565   APInt CnstBits(VT.getSizeInBits(), 0);
6566   APInt UndefBits(VT.getSizeInBits(), 0);
6567   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6568   bool IsZero = IsCnst && (CnstBits == 0);
6569
6570   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6571     switch (CC) {
6572     default:
6573       return SDValue();
6574     case AArch64CC::NE: {
6575       SDValue Fcmeq;
6576       if (IsZero)
6577         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6578       else
6579         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6580       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6581     }
6582     case AArch64CC::EQ:
6583       if (IsZero)
6584         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6585       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6586     case AArch64CC::GE:
6587       if (IsZero)
6588         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6589       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6590     case AArch64CC::GT:
6591       if (IsZero)
6592         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6593       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6594     case AArch64CC::LS:
6595       if (IsZero)
6596         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6597       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6598     case AArch64CC::LT:
6599       if (!NoNans)
6600         return SDValue();
6601     // If we ignore NaNs then we can use to the MI implementation.
6602     // Fallthrough.
6603     case AArch64CC::MI:
6604       if (IsZero)
6605         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6606       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6607     }
6608   }
6609
6610   switch (CC) {
6611   default:
6612     return SDValue();
6613   case AArch64CC::NE: {
6614     SDValue Cmeq;
6615     if (IsZero)
6616       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6617     else
6618       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6619     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6620   }
6621   case AArch64CC::EQ:
6622     if (IsZero)
6623       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6624     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6625   case AArch64CC::GE:
6626     if (IsZero)
6627       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6628     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6629   case AArch64CC::GT:
6630     if (IsZero)
6631       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6632     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6633   case AArch64CC::LE:
6634     if (IsZero)
6635       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6636     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6637   case AArch64CC::LS:
6638     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6639   case AArch64CC::LO:
6640     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6641   case AArch64CC::LT:
6642     if (IsZero)
6643       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6644     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6645   case AArch64CC::HI:
6646     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6647   case AArch64CC::HS:
6648     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6649   }
6650 }
6651
6652 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6653                                            SelectionDAG &DAG) const {
6654   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6655   SDValue LHS = Op.getOperand(0);
6656   SDValue RHS = Op.getOperand(1);
6657   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6658   SDLoc dl(Op);
6659
6660   if (LHS.getValueType().getVectorElementType().isInteger()) {
6661     assert(LHS.getValueType() == RHS.getValueType());
6662     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6663     SDValue Cmp =
6664         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6665     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6666   }
6667
6668   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6669          LHS.getValueType().getVectorElementType() == MVT::f64);
6670
6671   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6672   // clean.  Some of them require two branches to implement.
6673   AArch64CC::CondCode CC1, CC2;
6674   bool ShouldInvert;
6675   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6676
6677   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6678   SDValue Cmp =
6679       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6680   if (!Cmp.getNode())
6681     return SDValue();
6682
6683   if (CC2 != AArch64CC::AL) {
6684     SDValue Cmp2 =
6685         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6686     if (!Cmp2.getNode())
6687       return SDValue();
6688
6689     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6690   }
6691
6692   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6693
6694   if (ShouldInvert)
6695     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6696
6697   return Cmp;
6698 }
6699
6700 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6701 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6702 /// specified in the intrinsic calls.
6703 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6704                                                const CallInst &I,
6705                                                unsigned Intrinsic) const {
6706   auto &DL = I.getModule()->getDataLayout();
6707   switch (Intrinsic) {
6708   case Intrinsic::aarch64_neon_ld2:
6709   case Intrinsic::aarch64_neon_ld3:
6710   case Intrinsic::aarch64_neon_ld4:
6711   case Intrinsic::aarch64_neon_ld1x2:
6712   case Intrinsic::aarch64_neon_ld1x3:
6713   case Intrinsic::aarch64_neon_ld1x4:
6714   case Intrinsic::aarch64_neon_ld2lane:
6715   case Intrinsic::aarch64_neon_ld3lane:
6716   case Intrinsic::aarch64_neon_ld4lane:
6717   case Intrinsic::aarch64_neon_ld2r:
6718   case Intrinsic::aarch64_neon_ld3r:
6719   case Intrinsic::aarch64_neon_ld4r: {
6720     Info.opc = ISD::INTRINSIC_W_CHAIN;
6721     // Conservatively set memVT to the entire set of vectors loaded.
6722     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6723     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6724     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6725     Info.offset = 0;
6726     Info.align = 0;
6727     Info.vol = false; // volatile loads with NEON intrinsics not supported
6728     Info.readMem = true;
6729     Info.writeMem = false;
6730     return true;
6731   }
6732   case Intrinsic::aarch64_neon_st2:
6733   case Intrinsic::aarch64_neon_st3:
6734   case Intrinsic::aarch64_neon_st4:
6735   case Intrinsic::aarch64_neon_st1x2:
6736   case Intrinsic::aarch64_neon_st1x3:
6737   case Intrinsic::aarch64_neon_st1x4:
6738   case Intrinsic::aarch64_neon_st2lane:
6739   case Intrinsic::aarch64_neon_st3lane:
6740   case Intrinsic::aarch64_neon_st4lane: {
6741     Info.opc = ISD::INTRINSIC_VOID;
6742     // Conservatively set memVT to the entire set of vectors stored.
6743     unsigned NumElts = 0;
6744     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6745       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6746       if (!ArgTy->isVectorTy())
6747         break;
6748       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6749     }
6750     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6751     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6752     Info.offset = 0;
6753     Info.align = 0;
6754     Info.vol = false; // volatile stores with NEON intrinsics not supported
6755     Info.readMem = false;
6756     Info.writeMem = true;
6757     return true;
6758   }
6759   case Intrinsic::aarch64_ldaxr:
6760   case Intrinsic::aarch64_ldxr: {
6761     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6762     Info.opc = ISD::INTRINSIC_W_CHAIN;
6763     Info.memVT = MVT::getVT(PtrTy->getElementType());
6764     Info.ptrVal = I.getArgOperand(0);
6765     Info.offset = 0;
6766     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6767     Info.vol = true;
6768     Info.readMem = true;
6769     Info.writeMem = false;
6770     return true;
6771   }
6772   case Intrinsic::aarch64_stlxr:
6773   case Intrinsic::aarch64_stxr: {
6774     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6775     Info.opc = ISD::INTRINSIC_W_CHAIN;
6776     Info.memVT = MVT::getVT(PtrTy->getElementType());
6777     Info.ptrVal = I.getArgOperand(1);
6778     Info.offset = 0;
6779     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6780     Info.vol = true;
6781     Info.readMem = false;
6782     Info.writeMem = true;
6783     return true;
6784   }
6785   case Intrinsic::aarch64_ldaxp:
6786   case Intrinsic::aarch64_ldxp: {
6787     Info.opc = ISD::INTRINSIC_W_CHAIN;
6788     Info.memVT = MVT::i128;
6789     Info.ptrVal = I.getArgOperand(0);
6790     Info.offset = 0;
6791     Info.align = 16;
6792     Info.vol = true;
6793     Info.readMem = true;
6794     Info.writeMem = false;
6795     return true;
6796   }
6797   case Intrinsic::aarch64_stlxp:
6798   case Intrinsic::aarch64_stxp: {
6799     Info.opc = ISD::INTRINSIC_W_CHAIN;
6800     Info.memVT = MVT::i128;
6801     Info.ptrVal = I.getArgOperand(2);
6802     Info.offset = 0;
6803     Info.align = 16;
6804     Info.vol = true;
6805     Info.readMem = false;
6806     Info.writeMem = true;
6807     return true;
6808   }
6809   default:
6810     break;
6811   }
6812
6813   return false;
6814 }
6815
6816 // Truncations from 64-bit GPR to 32-bit GPR is free.
6817 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6818   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6819     return false;
6820   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6821   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6822   return NumBits1 > NumBits2;
6823 }
6824 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6825   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6826     return false;
6827   unsigned NumBits1 = VT1.getSizeInBits();
6828   unsigned NumBits2 = VT2.getSizeInBits();
6829   return NumBits1 > NumBits2;
6830 }
6831
6832 /// Check if it is profitable to hoist instruction in then/else to if.
6833 /// Not profitable if I and it's user can form a FMA instruction
6834 /// because we prefer FMSUB/FMADD.
6835 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6836   if (I->getOpcode() != Instruction::FMul)
6837     return true;
6838
6839   if (I->getNumUses() != 1)
6840     return true;
6841
6842   Instruction *User = I->user_back();
6843
6844   if (User &&
6845       !(User->getOpcode() == Instruction::FSub ||
6846         User->getOpcode() == Instruction::FAdd))
6847     return true;
6848
6849   const TargetOptions &Options = getTargetMachine().Options;
6850   const DataLayout &DL = I->getModule()->getDataLayout();
6851   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6852
6853   if (isFMAFasterThanFMulAndFAdd(VT) &&
6854       isOperationLegalOrCustom(ISD::FMA, VT) &&
6855       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6856     return false;
6857
6858   return true;
6859 }
6860
6861 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6862 // 64-bit GPR.
6863 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6864   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6865     return false;
6866   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6867   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6868   return NumBits1 == 32 && NumBits2 == 64;
6869 }
6870 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6871   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6872     return false;
6873   unsigned NumBits1 = VT1.getSizeInBits();
6874   unsigned NumBits2 = VT2.getSizeInBits();
6875   return NumBits1 == 32 && NumBits2 == 64;
6876 }
6877
6878 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6879   EVT VT1 = Val.getValueType();
6880   if (isZExtFree(VT1, VT2)) {
6881     return true;
6882   }
6883
6884   if (Val.getOpcode() != ISD::LOAD)
6885     return false;
6886
6887   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6888   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6889           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6890           VT1.getSizeInBits() <= 32);
6891 }
6892
6893 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6894   if (isa<FPExtInst>(Ext))
6895     return false;
6896
6897   // Vector types are next free.
6898   if (Ext->getType()->isVectorTy())
6899     return false;
6900
6901   for (const Use &U : Ext->uses()) {
6902     // The extension is free if we can fold it with a left shift in an
6903     // addressing mode or an arithmetic operation: add, sub, and cmp.
6904
6905     // Is there a shift?
6906     const Instruction *Instr = cast<Instruction>(U.getUser());
6907
6908     // Is this a constant shift?
6909     switch (Instr->getOpcode()) {
6910     case Instruction::Shl:
6911       if (!isa<ConstantInt>(Instr->getOperand(1)))
6912         return false;
6913       break;
6914     case Instruction::GetElementPtr: {
6915       gep_type_iterator GTI = gep_type_begin(Instr);
6916       auto &DL = Ext->getModule()->getDataLayout();
6917       std::advance(GTI, U.getOperandNo());
6918       Type *IdxTy = *GTI;
6919       // This extension will end up with a shift because of the scaling factor.
6920       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6921       // Get the shift amount based on the scaling factor:
6922       // log2(sizeof(IdxTy)) - log2(8).
6923       uint64_t ShiftAmt =
6924           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6925       // Is the constant foldable in the shift of the addressing mode?
6926       // I.e., shift amount is between 1 and 4 inclusive.
6927       if (ShiftAmt == 0 || ShiftAmt > 4)
6928         return false;
6929       break;
6930     }
6931     case Instruction::Trunc:
6932       // Check if this is a noop.
6933       // trunc(sext ty1 to ty2) to ty1.
6934       if (Instr->getType() == Ext->getOperand(0)->getType())
6935         continue;
6936     // FALL THROUGH.
6937     default:
6938       return false;
6939     }
6940
6941     // At this point we can use the bfm family, so this extension is free
6942     // for that use.
6943   }
6944   return true;
6945 }
6946
6947 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6948                                           unsigned &RequiredAligment) const {
6949   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6950     return false;
6951   // Cyclone supports unaligned accesses.
6952   RequiredAligment = 0;
6953   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6954   return NumBits == 32 || NumBits == 64;
6955 }
6956
6957 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6958                                           unsigned &RequiredAligment) const {
6959   if (!LoadedType.isSimple() ||
6960       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6961     return false;
6962   // Cyclone supports unaligned accesses.
6963   RequiredAligment = 0;
6964   unsigned NumBits = LoadedType.getSizeInBits();
6965   return NumBits == 32 || NumBits == 64;
6966 }
6967
6968 /// \brief Lower an interleaved load into a ldN intrinsic.
6969 ///
6970 /// E.g. Lower an interleaved load (Factor = 2):
6971 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6972 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6973 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6974 ///
6975 ///      Into:
6976 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6977 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6978 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6979 bool AArch64TargetLowering::lowerInterleavedLoad(
6980     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6981     ArrayRef<unsigned> Indices, unsigned Factor) const {
6982   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6983          "Invalid interleave factor");
6984   assert(!Shuffles.empty() && "Empty shufflevector input");
6985   assert(Shuffles.size() == Indices.size() &&
6986          "Unmatched number of shufflevectors and indices");
6987
6988   const DataLayout &DL = LI->getModule()->getDataLayout();
6989
6990   VectorType *VecTy = Shuffles[0]->getType();
6991   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6992
6993   // Skip if we do not have NEON and skip illegal vector types.
6994   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
6995     return false;
6996
6997   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6998   // load integer vectors first and then convert to pointer vectors.
6999   Type *EltTy = VecTy->getVectorElementType();
7000   if (EltTy->isPointerTy())
7001     VecTy =
7002         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7003
7004   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7005   Type *Tys[2] = {VecTy, PtrTy};
7006   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7007                                             Intrinsic::aarch64_neon_ld3,
7008                                             Intrinsic::aarch64_neon_ld4};
7009   Function *LdNFunc =
7010       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7011
7012   IRBuilder<> Builder(LI);
7013   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7014
7015   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7016
7017   // Replace uses of each shufflevector with the corresponding vector loaded
7018   // by ldN.
7019   for (unsigned i = 0; i < Shuffles.size(); i++) {
7020     ShuffleVectorInst *SVI = Shuffles[i];
7021     unsigned Index = Indices[i];
7022
7023     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7024
7025     // Convert the integer vector to pointer vector if the element is pointer.
7026     if (EltTy->isPointerTy())
7027       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7028
7029     SVI->replaceAllUsesWith(SubVec);
7030   }
7031
7032   return true;
7033 }
7034
7035 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7036 ///
7037 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7038 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7039                                    unsigned NumElts) {
7040   SmallVector<Constant *, 16> Mask;
7041   for (unsigned i = 0; i < NumElts; i++)
7042     Mask.push_back(Builder.getInt32(Start + i));
7043
7044   return ConstantVector::get(Mask);
7045 }
7046
7047 /// \brief Lower an interleaved store into a stN intrinsic.
7048 ///
7049 /// E.g. Lower an interleaved store (Factor = 3):
7050 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7051 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7052 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7053 ///
7054 ///      Into:
7055 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7056 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7057 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7058 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7059 ///
7060 /// Note that the new shufflevectors will be removed and we'll only generate one
7061 /// st3 instruction in CodeGen.
7062 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7063                                                   ShuffleVectorInst *SVI,
7064                                                   unsigned Factor) const {
7065   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7066          "Invalid interleave factor");
7067
7068   VectorType *VecTy = SVI->getType();
7069   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7070          "Invalid interleaved store");
7071
7072   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7073   Type *EltTy = VecTy->getVectorElementType();
7074   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7075
7076   const DataLayout &DL = SI->getModule()->getDataLayout();
7077   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7078
7079   // Skip if we do not have NEON and skip illegal vector types.
7080   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7081     return false;
7082
7083   Value *Op0 = SVI->getOperand(0);
7084   Value *Op1 = SVI->getOperand(1);
7085   IRBuilder<> Builder(SI);
7086
7087   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7088   // vectors to integer vectors.
7089   if (EltTy->isPointerTy()) {
7090     Type *IntTy = DL.getIntPtrType(EltTy);
7091     unsigned NumOpElts =
7092         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7093
7094     // Convert to the corresponding integer vector.
7095     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7096     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7097     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7098
7099     SubVecTy = VectorType::get(IntTy, NumSubElts);
7100   }
7101
7102   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7103   Type *Tys[2] = {SubVecTy, PtrTy};
7104   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7105                                              Intrinsic::aarch64_neon_st3,
7106                                              Intrinsic::aarch64_neon_st4};
7107   Function *StNFunc =
7108       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7109
7110   SmallVector<Value *, 5> Ops;
7111
7112   // Split the shufflevector operands into sub vectors for the new stN call.
7113   for (unsigned i = 0; i < Factor; i++)
7114     Ops.push_back(Builder.CreateShuffleVector(
7115         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7116
7117   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7118   Builder.CreateCall(StNFunc, Ops);
7119   return true;
7120 }
7121
7122 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7123                        unsigned AlignCheck) {
7124   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7125           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7126 }
7127
7128 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7129                                                unsigned SrcAlign, bool IsMemset,
7130                                                bool ZeroMemset,
7131                                                bool MemcpyStrSrc,
7132                                                MachineFunction &MF) const {
7133   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7134   // instruction to materialize the v2i64 zero and one store (with restrictive
7135   // addressing mode). Just do two i64 store of zero-registers.
7136   bool Fast;
7137   const Function *F = MF.getFunction();
7138   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7139       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7140       (memOpAlign(SrcAlign, DstAlign, 16) ||
7141        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7142     return MVT::f128;
7143
7144   if (Size >= 8 &&
7145       (memOpAlign(SrcAlign, DstAlign, 8) ||
7146        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7147     return MVT::i64;
7148
7149   if (Size >= 4 &&
7150       (memOpAlign(SrcAlign, DstAlign, 4) ||
7151        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7152     return MVT::i32;
7153
7154   return MVT::Other;
7155 }
7156
7157 // 12-bit optionally shifted immediates are legal for adds.
7158 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7159   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7160     return true;
7161   return false;
7162 }
7163
7164 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7165 // immediates is the same as for an add or a sub.
7166 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7167   if (Immed < 0)
7168     Immed *= -1;
7169   return isLegalAddImmediate(Immed);
7170 }
7171
7172 /// isLegalAddressingMode - Return true if the addressing mode represented
7173 /// by AM is legal for this target, for a load/store of the specified type.
7174 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7175                                                   const AddrMode &AM, Type *Ty,
7176                                                   unsigned AS) const {
7177   // AArch64 has five basic addressing modes:
7178   //  reg
7179   //  reg + 9-bit signed offset
7180   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7181   //  reg1 + reg2
7182   //  reg + SIZE_IN_BYTES * reg
7183
7184   // No global is ever allowed as a base.
7185   if (AM.BaseGV)
7186     return false;
7187
7188   // No reg+reg+imm addressing.
7189   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7190     return false;
7191
7192   // check reg + imm case:
7193   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7194   uint64_t NumBytes = 0;
7195   if (Ty->isSized()) {
7196     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7197     NumBytes = NumBits / 8;
7198     if (!isPowerOf2_64(NumBits))
7199       NumBytes = 0;
7200   }
7201
7202   if (!AM.Scale) {
7203     int64_t Offset = AM.BaseOffs;
7204
7205     // 9-bit signed offset
7206     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7207       return true;
7208
7209     // 12-bit unsigned offset
7210     unsigned shift = Log2_64(NumBytes);
7211     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7212         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7213         (Offset >> shift) << shift == Offset)
7214       return true;
7215     return false;
7216   }
7217
7218   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7219
7220   if (!AM.Scale || AM.Scale == 1 ||
7221       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7222     return true;
7223   return false;
7224 }
7225
7226 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7227                                                 const AddrMode &AM, Type *Ty,
7228                                                 unsigned AS) const {
7229   // Scaling factors are not free at all.
7230   // Operands                     | Rt Latency
7231   // -------------------------------------------
7232   // Rt, [Xn, Xm]                 | 4
7233   // -------------------------------------------
7234   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7235   // Rt, [Xn, Wm, <extend> #imm]  |
7236   if (isLegalAddressingMode(DL, AM, Ty, AS))
7237     // Scale represents reg2 * scale, thus account for 1 if
7238     // it is not equal to 0 or 1.
7239     return AM.Scale != 0 && AM.Scale != 1;
7240   return -1;
7241 }
7242
7243 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7244   VT = VT.getScalarType();
7245
7246   if (!VT.isSimple())
7247     return false;
7248
7249   switch (VT.getSimpleVT().SimpleTy) {
7250   case MVT::f32:
7251   case MVT::f64:
7252     return true;
7253   default:
7254     break;
7255   }
7256
7257   return false;
7258 }
7259
7260 const MCPhysReg *
7261 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7262   // LR is a callee-save register, but we must treat it as clobbered by any call
7263   // site. Hence we include LR in the scratch registers, which are in turn added
7264   // as implicit-defs for stackmaps and patchpoints.
7265   static const MCPhysReg ScratchRegs[] = {
7266     AArch64::X16, AArch64::X17, AArch64::LR, 0
7267   };
7268   return ScratchRegs;
7269 }
7270
7271 bool
7272 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7273   EVT VT = N->getValueType(0);
7274     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7275     // it with shift to let it be lowered to UBFX.
7276   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7277       isa<ConstantSDNode>(N->getOperand(1))) {
7278     uint64_t TruncMask = N->getConstantOperandVal(1);
7279     if (isMask_64(TruncMask) &&
7280       N->getOperand(0).getOpcode() == ISD::SRL &&
7281       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7282       return false;
7283   }
7284   return true;
7285 }
7286
7287 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7288                                                               Type *Ty) const {
7289   assert(Ty->isIntegerTy());
7290
7291   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7292   if (BitSize == 0)
7293     return false;
7294
7295   int64_t Val = Imm.getSExtValue();
7296   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7297     return true;
7298
7299   if ((int64_t)Val < 0)
7300     Val = ~Val;
7301   if (BitSize == 32)
7302     Val &= (1LL << 32) - 1;
7303
7304   unsigned LZ = countLeadingZeros((uint64_t)Val);
7305   unsigned Shift = (63 - LZ) / 16;
7306   // MOVZ is free so return true for one or fewer MOVK.
7307   return Shift < 3;
7308 }
7309
7310 // Generate SUBS and CSEL for integer abs.
7311 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7312   EVT VT = N->getValueType(0);
7313
7314   SDValue N0 = N->getOperand(0);
7315   SDValue N1 = N->getOperand(1);
7316   SDLoc DL(N);
7317
7318   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7319   // and change it to SUB and CSEL.
7320   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7321       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7322       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7323     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7324       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7325         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7326                                   N0.getOperand(0));
7327         // Generate SUBS & CSEL.
7328         SDValue Cmp =
7329             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7330                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7331         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7332                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7333                            SDValue(Cmp.getNode(), 1));
7334       }
7335   return SDValue();
7336 }
7337
7338 // performXorCombine - Attempts to handle integer ABS.
7339 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7340                                  TargetLowering::DAGCombinerInfo &DCI,
7341                                  const AArch64Subtarget *Subtarget) {
7342   if (DCI.isBeforeLegalizeOps())
7343     return SDValue();
7344
7345   return performIntegerAbsCombine(N, DAG);
7346 }
7347
7348 SDValue
7349 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7350                                      SelectionDAG &DAG,
7351                                      std::vector<SDNode *> *Created) const {
7352   // fold (sdiv X, pow2)
7353   EVT VT = N->getValueType(0);
7354   if ((VT != MVT::i32 && VT != MVT::i64) ||
7355       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7356     return SDValue();
7357
7358   SDLoc DL(N);
7359   SDValue N0 = N->getOperand(0);
7360   unsigned Lg2 = Divisor.countTrailingZeros();
7361   SDValue Zero = DAG.getConstant(0, DL, VT);
7362   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7363
7364   // Add (N0 < 0) ? Pow2 - 1 : 0;
7365   SDValue CCVal;
7366   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7367   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7368   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7369
7370   if (Created) {
7371     Created->push_back(Cmp.getNode());
7372     Created->push_back(Add.getNode());
7373     Created->push_back(CSel.getNode());
7374   }
7375
7376   // Divide by pow2.
7377   SDValue SRA =
7378       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7379
7380   // If we're dividing by a positive value, we're done.  Otherwise, we must
7381   // negate the result.
7382   if (Divisor.isNonNegative())
7383     return SRA;
7384
7385   if (Created)
7386     Created->push_back(SRA.getNode());
7387   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7388 }
7389
7390 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7391                                  TargetLowering::DAGCombinerInfo &DCI,
7392                                  const AArch64Subtarget *Subtarget) {
7393   if (DCI.isBeforeLegalizeOps())
7394     return SDValue();
7395
7396   // Multiplication of a power of two plus/minus one can be done more
7397   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7398   // future CPUs have a cheaper MADD instruction, this may need to be
7399   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7400   // 64-bit is 5 cycles, so this is always a win.
7401   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7402     APInt Value = C->getAPIntValue();
7403     EVT VT = N->getValueType(0);
7404     SDLoc DL(N);
7405     if (Value.isNonNegative()) {
7406       // (mul x, 2^N + 1) => (add (shl x, N), x)
7407       APInt VM1 = Value - 1;
7408       if (VM1.isPowerOf2()) {
7409         SDValue ShiftedVal =
7410             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7411                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7412         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7413                            N->getOperand(0));
7414       }
7415       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7416       APInt VP1 = Value + 1;
7417       if (VP1.isPowerOf2()) {
7418         SDValue ShiftedVal =
7419             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7420                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7421         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7422                            N->getOperand(0));
7423       }
7424     } else {
7425       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7426       APInt VNP1 = -Value + 1;
7427       if (VNP1.isPowerOf2()) {
7428         SDValue ShiftedVal =
7429             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7430                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7431         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7432                            ShiftedVal);
7433       }
7434       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7435       APInt VNM1 = -Value - 1;
7436       if (VNM1.isPowerOf2()) {
7437         SDValue ShiftedVal =
7438             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7439                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7440         SDValue Add =
7441             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7442         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7443       }
7444     }
7445   }
7446   return SDValue();
7447 }
7448
7449 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7450                                                          SelectionDAG &DAG) {
7451   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7452   // optimize away operation when it's from a constant.
7453   //
7454   // The general transformation is:
7455   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7456   //       AND(VECTOR_CMP(x,y), constant2)
7457   //    constant2 = UNARYOP(constant)
7458
7459   // Early exit if this isn't a vector operation, the operand of the
7460   // unary operation isn't a bitwise AND, or if the sizes of the operations
7461   // aren't the same.
7462   EVT VT = N->getValueType(0);
7463   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7464       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7465       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7466     return SDValue();
7467
7468   // Now check that the other operand of the AND is a constant. We could
7469   // make the transformation for non-constant splats as well, but it's unclear
7470   // that would be a benefit as it would not eliminate any operations, just
7471   // perform one more step in scalar code before moving to the vector unit.
7472   if (BuildVectorSDNode *BV =
7473           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7474     // Bail out if the vector isn't a constant.
7475     if (!BV->isConstant())
7476       return SDValue();
7477
7478     // Everything checks out. Build up the new and improved node.
7479     SDLoc DL(N);
7480     EVT IntVT = BV->getValueType(0);
7481     // Create a new constant of the appropriate type for the transformed
7482     // DAG.
7483     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7484     // The AND node needs bitcasts to/from an integer vector type around it.
7485     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7486     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7487                                  N->getOperand(0)->getOperand(0), MaskConst);
7488     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7489     return Res;
7490   }
7491
7492   return SDValue();
7493 }
7494
7495 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7496                                      const AArch64Subtarget *Subtarget) {
7497   // First try to optimize away the conversion when it's conditionally from
7498   // a constant. Vectors only.
7499   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7500     return Res;
7501
7502   EVT VT = N->getValueType(0);
7503   if (VT != MVT::f32 && VT != MVT::f64)
7504     return SDValue();
7505
7506   // Only optimize when the source and destination types have the same width.
7507   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7508     return SDValue();
7509
7510   // If the result of an integer load is only used by an integer-to-float
7511   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7512   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7513   SDValue N0 = N->getOperand(0);
7514   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7515       // Do not change the width of a volatile load.
7516       !cast<LoadSDNode>(N0)->isVolatile()) {
7517     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7518     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7519                                LN0->getPointerInfo(), LN0->isVolatile(),
7520                                LN0->isNonTemporal(), LN0->isInvariant(),
7521                                LN0->getAlignment());
7522
7523     // Make sure successors of the original load stay after it by updating them
7524     // to use the new Chain.
7525     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7526
7527     unsigned Opcode =
7528         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7529     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7530   }
7531
7532   return SDValue();
7533 }
7534
7535 /// Fold a floating-point multiply by power of two into floating-point to
7536 /// fixed-point conversion.
7537 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7538                                      const AArch64Subtarget *Subtarget) {
7539   if (!Subtarget->hasNEON())
7540     return SDValue();
7541
7542   SDValue Op = N->getOperand(0);
7543   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7544     return SDValue();
7545
7546   SDValue ConstVec = Op->getOperand(1);
7547   if (!isa<BuildVectorSDNode>(ConstVec))
7548     return SDValue();
7549
7550   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7551   uint32_t FloatBits = FloatTy.getSizeInBits();
7552   if (FloatBits != 32 && FloatBits != 64)
7553     return SDValue();
7554
7555   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7556   uint32_t IntBits = IntTy.getSizeInBits();
7557   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7558     return SDValue();
7559
7560   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7561   if (IntBits > FloatBits)
7562     return SDValue();
7563
7564   BitVector UndefElements;
7565   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7566   int32_t Bits = IntBits == 64 ? 64 : 32;
7567   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7568   if (C == -1 || C == 0 || C > Bits)
7569     return SDValue();
7570
7571   MVT ResTy;
7572   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7573   switch (NumLanes) {
7574   default:
7575     return SDValue();
7576   case 2:
7577     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7578     break;
7579   case 4:
7580     ResTy = MVT::v4i32;
7581     break;
7582   }
7583
7584   SDLoc DL(N);
7585   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7586   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7587                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7588   SDValue FixConv =
7589       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7590                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7591                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7592   // We can handle smaller integers by generating an extra trunc.
7593   if (IntBits < FloatBits)
7594     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7595
7596   return FixConv;
7597 }
7598
7599 /// Fold a floating-point divide by power of two into fixed-point to
7600 /// floating-point conversion.
7601 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7602                                   const AArch64Subtarget *Subtarget) {
7603   if (!Subtarget->hasNEON())
7604     return SDValue();
7605
7606   SDValue Op = N->getOperand(0);
7607   unsigned Opc = Op->getOpcode();
7608   if (!Op.getValueType().isVector() ||
7609       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7610     return SDValue();
7611
7612   SDValue ConstVec = N->getOperand(1);
7613   if (!isa<BuildVectorSDNode>(ConstVec))
7614     return SDValue();
7615
7616   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7617   int32_t IntBits = IntTy.getSizeInBits();
7618   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7619     return SDValue();
7620
7621   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7622   int32_t FloatBits = FloatTy.getSizeInBits();
7623   if (FloatBits != 32 && FloatBits != 64)
7624     return SDValue();
7625
7626   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7627   if (IntBits > FloatBits)
7628     return SDValue();
7629
7630   BitVector UndefElements;
7631   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7632   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7633   if (C == -1 || C == 0 || C > FloatBits)
7634     return SDValue();
7635
7636   MVT ResTy;
7637   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7638   switch (NumLanes) {
7639   default:
7640     return SDValue();
7641   case 2:
7642     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7643     break;
7644   case 4:
7645     ResTy = MVT::v4i32;
7646     break;
7647   }
7648
7649   SDLoc DL(N);
7650   SDValue ConvInput = Op.getOperand(0);
7651   bool IsSigned = Opc == ISD::SINT_TO_FP;
7652   if (IntBits < FloatBits)
7653     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7654                             ResTy, ConvInput);
7655
7656   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7657                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7658   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7659                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7660                      DAG.getConstant(C, DL, MVT::i32));
7661 }
7662
7663 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7664 /// searches for and classifies those shifts.
7665 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7666                          bool &FromHi) {
7667   if (N.getOpcode() == ISD::SHL)
7668     FromHi = false;
7669   else if (N.getOpcode() == ISD::SRL)
7670     FromHi = true;
7671   else
7672     return false;
7673
7674   if (!isa<ConstantSDNode>(N.getOperand(1)))
7675     return false;
7676
7677   ShiftAmount = N->getConstantOperandVal(1);
7678   Src = N->getOperand(0);
7679   return true;
7680 }
7681
7682 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7683 /// registers viewed as a high/low pair. This function looks for the pattern:
7684 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7685 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7686 /// independent.
7687 static SDValue tryCombineToEXTR(SDNode *N,
7688                                 TargetLowering::DAGCombinerInfo &DCI) {
7689   SelectionDAG &DAG = DCI.DAG;
7690   SDLoc DL(N);
7691   EVT VT = N->getValueType(0);
7692
7693   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7694
7695   if (VT != MVT::i32 && VT != MVT::i64)
7696     return SDValue();
7697
7698   SDValue LHS;
7699   uint32_t ShiftLHS = 0;
7700   bool LHSFromHi = 0;
7701   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7702     return SDValue();
7703
7704   SDValue RHS;
7705   uint32_t ShiftRHS = 0;
7706   bool RHSFromHi = 0;
7707   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7708     return SDValue();
7709
7710   // If they're both trying to come from the high part of the register, they're
7711   // not really an EXTR.
7712   if (LHSFromHi == RHSFromHi)
7713     return SDValue();
7714
7715   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7716     return SDValue();
7717
7718   if (LHSFromHi) {
7719     std::swap(LHS, RHS);
7720     std::swap(ShiftLHS, ShiftRHS);
7721   }
7722
7723   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7724                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7725 }
7726
7727 static SDValue tryCombineToBSL(SDNode *N,
7728                                 TargetLowering::DAGCombinerInfo &DCI) {
7729   EVT VT = N->getValueType(0);
7730   SelectionDAG &DAG = DCI.DAG;
7731   SDLoc DL(N);
7732
7733   if (!VT.isVector())
7734     return SDValue();
7735
7736   SDValue N0 = N->getOperand(0);
7737   if (N0.getOpcode() != ISD::AND)
7738     return SDValue();
7739
7740   SDValue N1 = N->getOperand(1);
7741   if (N1.getOpcode() != ISD::AND)
7742     return SDValue();
7743
7744   // We only have to look for constant vectors here since the general, variable
7745   // case can be handled in TableGen.
7746   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7747   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7748   for (int i = 1; i >= 0; --i)
7749     for (int j = 1; j >= 0; --j) {
7750       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7751       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7752       if (!BVN0 || !BVN1)
7753         continue;
7754
7755       bool FoundMatch = true;
7756       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7757         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7758         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7759         if (!CN0 || !CN1 ||
7760             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7761           FoundMatch = false;
7762           break;
7763         }
7764       }
7765
7766       if (FoundMatch)
7767         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7768                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7769     }
7770
7771   return SDValue();
7772 }
7773
7774 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7775                                 const AArch64Subtarget *Subtarget) {
7776   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7777   if (!EnableAArch64ExtrGeneration)
7778     return SDValue();
7779   SelectionDAG &DAG = DCI.DAG;
7780   EVT VT = N->getValueType(0);
7781
7782   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7783     return SDValue();
7784
7785   SDValue Res = tryCombineToEXTR(N, DCI);
7786   if (Res.getNode())
7787     return Res;
7788
7789   Res = tryCombineToBSL(N, DCI);
7790   if (Res.getNode())
7791     return Res;
7792
7793   return SDValue();
7794 }
7795
7796 static SDValue performBitcastCombine(SDNode *N,
7797                                      TargetLowering::DAGCombinerInfo &DCI,
7798                                      SelectionDAG &DAG) {
7799   // Wait 'til after everything is legalized to try this. That way we have
7800   // legal vector types and such.
7801   if (DCI.isBeforeLegalizeOps())
7802     return SDValue();
7803
7804   // Remove extraneous bitcasts around an extract_subvector.
7805   // For example,
7806   //    (v4i16 (bitconvert
7807   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7808   //  becomes
7809   //    (extract_subvector ((v8i16 ...), (i64 4)))
7810
7811   // Only interested in 64-bit vectors as the ultimate result.
7812   EVT VT = N->getValueType(0);
7813   if (!VT.isVector())
7814     return SDValue();
7815   if (VT.getSimpleVT().getSizeInBits() != 64)
7816     return SDValue();
7817   // Is the operand an extract_subvector starting at the beginning or halfway
7818   // point of the vector? A low half may also come through as an
7819   // EXTRACT_SUBREG, so look for that, too.
7820   SDValue Op0 = N->getOperand(0);
7821   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7822       !(Op0->isMachineOpcode() &&
7823         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7824     return SDValue();
7825   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7826   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7827     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7828       return SDValue();
7829   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7830     if (idx != AArch64::dsub)
7831       return SDValue();
7832     // The dsub reference is equivalent to a lane zero subvector reference.
7833     idx = 0;
7834   }
7835   // Look through the bitcast of the input to the extract.
7836   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7837     return SDValue();
7838   SDValue Source = Op0->getOperand(0)->getOperand(0);
7839   // If the source type has twice the number of elements as our destination
7840   // type, we know this is an extract of the high or low half of the vector.
7841   EVT SVT = Source->getValueType(0);
7842   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7843     return SDValue();
7844
7845   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7846
7847   // Create the simplified form to just extract the low or high half of the
7848   // vector directly rather than bothering with the bitcasts.
7849   SDLoc dl(N);
7850   unsigned NumElements = VT.getVectorNumElements();
7851   if (idx) {
7852     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7853     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7854   } else {
7855     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7856     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7857                                       Source, SubReg),
7858                    0);
7859   }
7860 }
7861
7862 static SDValue performConcatVectorsCombine(SDNode *N,
7863                                            TargetLowering::DAGCombinerInfo &DCI,
7864                                            SelectionDAG &DAG) {
7865   SDLoc dl(N);
7866   EVT VT = N->getValueType(0);
7867   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7868
7869   // Optimize concat_vectors of truncated vectors, where the intermediate
7870   // type is illegal, to avoid said illegality,  e.g.,
7871   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7872   //                          (v2i16 (truncate (v2i64)))))
7873   // ->
7874   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7875   //                                    (v4i32 (bitcast (v2i64))),
7876   //                                    <0, 2, 4, 6>)))
7877   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7878   // on both input and result type, so we might generate worse code.
7879   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7880   if (N->getNumOperands() == 2 &&
7881       N0->getOpcode() == ISD::TRUNCATE &&
7882       N1->getOpcode() == ISD::TRUNCATE) {
7883     SDValue N00 = N0->getOperand(0);
7884     SDValue N10 = N1->getOperand(0);
7885     EVT N00VT = N00.getValueType();
7886
7887     if (N00VT == N10.getValueType() &&
7888         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7889         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7890       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7891       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7892       for (size_t i = 0; i < Mask.size(); ++i)
7893         Mask[i] = i * 2;
7894       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7895                          DAG.getVectorShuffle(
7896                              MidVT, dl,
7897                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7898                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7899     }
7900   }
7901
7902   // Wait 'til after everything is legalized to try this. That way we have
7903   // legal vector types and such.
7904   if (DCI.isBeforeLegalizeOps())
7905     return SDValue();
7906
7907   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7908   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7909   // canonicalise to that.
7910   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7911     assert(VT.getVectorElementType().getSizeInBits() == 64);
7912     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7913                        DAG.getConstant(0, dl, MVT::i64));
7914   }
7915
7916   // Canonicalise concat_vectors so that the right-hand vector has as few
7917   // bit-casts as possible before its real operation. The primary matching
7918   // destination for these operations will be the narrowing "2" instructions,
7919   // which depend on the operation being performed on this right-hand vector.
7920   // For example,
7921   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7922   // becomes
7923   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7924
7925   if (N1->getOpcode() != ISD::BITCAST)
7926     return SDValue();
7927   SDValue RHS = N1->getOperand(0);
7928   MVT RHSTy = RHS.getValueType().getSimpleVT();
7929   // If the RHS is not a vector, this is not the pattern we're looking for.
7930   if (!RHSTy.isVector())
7931     return SDValue();
7932
7933   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7934
7935   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7936                                   RHSTy.getVectorNumElements() * 2);
7937   return DAG.getNode(ISD::BITCAST, dl, VT,
7938                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7939                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7940                                  RHS));
7941 }
7942
7943 static SDValue tryCombineFixedPointConvert(SDNode *N,
7944                                            TargetLowering::DAGCombinerInfo &DCI,
7945                                            SelectionDAG &DAG) {
7946   // Wait 'til after everything is legalized to try this. That way we have
7947   // legal vector types and such.
7948   if (DCI.isBeforeLegalizeOps())
7949     return SDValue();
7950   // Transform a scalar conversion of a value from a lane extract into a
7951   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7952   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7953   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7954   //
7955   // The second form interacts better with instruction selection and the
7956   // register allocator to avoid cross-class register copies that aren't
7957   // coalescable due to a lane reference.
7958
7959   // Check the operand and see if it originates from a lane extract.
7960   SDValue Op1 = N->getOperand(1);
7961   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7962     // Yep, no additional predication needed. Perform the transform.
7963     SDValue IID = N->getOperand(0);
7964     SDValue Shift = N->getOperand(2);
7965     SDValue Vec = Op1.getOperand(0);
7966     SDValue Lane = Op1.getOperand(1);
7967     EVT ResTy = N->getValueType(0);
7968     EVT VecResTy;
7969     SDLoc DL(N);
7970
7971     // The vector width should be 128 bits by the time we get here, even
7972     // if it started as 64 bits (the extract_vector handling will have
7973     // done so).
7974     assert(Vec.getValueType().getSizeInBits() == 128 &&
7975            "unexpected vector size on extract_vector_elt!");
7976     if (Vec.getValueType() == MVT::v4i32)
7977       VecResTy = MVT::v4f32;
7978     else if (Vec.getValueType() == MVT::v2i64)
7979       VecResTy = MVT::v2f64;
7980     else
7981       llvm_unreachable("unexpected vector type!");
7982
7983     SDValue Convert =
7984         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7985     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7986   }
7987   return SDValue();
7988 }
7989
7990 // AArch64 high-vector "long" operations are formed by performing the non-high
7991 // version on an extract_subvector of each operand which gets the high half:
7992 //
7993 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7994 //
7995 // However, there are cases which don't have an extract_high explicitly, but
7996 // have another operation that can be made compatible with one for free. For
7997 // example:
7998 //
7999 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8000 //
8001 // This routine does the actual conversion of such DUPs, once outer routines
8002 // have determined that everything else is in order.
8003 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8004 // similarly here.
8005 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8006   switch (N.getOpcode()) {
8007   case AArch64ISD::DUP:
8008   case AArch64ISD::DUPLANE8:
8009   case AArch64ISD::DUPLANE16:
8010   case AArch64ISD::DUPLANE32:
8011   case AArch64ISD::DUPLANE64:
8012   case AArch64ISD::MOVI:
8013   case AArch64ISD::MOVIshift:
8014   case AArch64ISD::MOVIedit:
8015   case AArch64ISD::MOVImsl:
8016   case AArch64ISD::MVNIshift:
8017   case AArch64ISD::MVNImsl:
8018     break;
8019   default:
8020     // FMOV could be supported, but isn't very useful, as it would only occur
8021     // if you passed a bitcast' floating point immediate to an eligible long
8022     // integer op (addl, smull, ...).
8023     return SDValue();
8024   }
8025
8026   MVT NarrowTy = N.getSimpleValueType();
8027   if (!NarrowTy.is64BitVector())
8028     return SDValue();
8029
8030   MVT ElementTy = NarrowTy.getVectorElementType();
8031   unsigned NumElems = NarrowTy.getVectorNumElements();
8032   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8033
8034   SDLoc dl(N);
8035   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8036                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8037                      DAG.getConstant(NumElems, dl, MVT::i64));
8038 }
8039
8040 static bool isEssentiallyExtractSubvector(SDValue N) {
8041   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8042     return true;
8043
8044   return N.getOpcode() == ISD::BITCAST &&
8045          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8046 }
8047
8048 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8049 struct GenericSetCCInfo {
8050   const SDValue *Opnd0;
8051   const SDValue *Opnd1;
8052   ISD::CondCode CC;
8053 };
8054
8055 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8056 struct AArch64SetCCInfo {
8057   const SDValue *Cmp;
8058   AArch64CC::CondCode CC;
8059 };
8060
8061 /// \brief Helper structure to keep track of SetCC information.
8062 union SetCCInfo {
8063   GenericSetCCInfo Generic;
8064   AArch64SetCCInfo AArch64;
8065 };
8066
8067 /// \brief Helper structure to be able to read SetCC information.  If set to
8068 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8069 /// GenericSetCCInfo.
8070 struct SetCCInfoAndKind {
8071   SetCCInfo Info;
8072   bool IsAArch64;
8073 };
8074
8075 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8076 /// an
8077 /// AArch64 lowered one.
8078 /// \p SetCCInfo is filled accordingly.
8079 /// \post SetCCInfo is meanginfull only when this function returns true.
8080 /// \return True when Op is a kind of SET_CC operation.
8081 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8082   // If this is a setcc, this is straight forward.
8083   if (Op.getOpcode() == ISD::SETCC) {
8084     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8085     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8086     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8087     SetCCInfo.IsAArch64 = false;
8088     return true;
8089   }
8090   // Otherwise, check if this is a matching csel instruction.
8091   // In other words:
8092   // - csel 1, 0, cc
8093   // - csel 0, 1, !cc
8094   if (Op.getOpcode() != AArch64ISD::CSEL)
8095     return false;
8096   // Set the information about the operands.
8097   // TODO: we want the operands of the Cmp not the csel
8098   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8099   SetCCInfo.IsAArch64 = true;
8100   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8101       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8102
8103   // Check that the operands matches the constraints:
8104   // (1) Both operands must be constants.
8105   // (2) One must be 1 and the other must be 0.
8106   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8107   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8108
8109   // Check (1).
8110   if (!TValue || !FValue)
8111     return false;
8112
8113   // Check (2).
8114   if (!TValue->isOne()) {
8115     // Update the comparison when we are interested in !cc.
8116     std::swap(TValue, FValue);
8117     SetCCInfo.Info.AArch64.CC =
8118         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8119   }
8120   return TValue->isOne() && FValue->isNullValue();
8121 }
8122
8123 // Returns true if Op is setcc or zext of setcc.
8124 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8125   if (isSetCC(Op, Info))
8126     return true;
8127   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8128     isSetCC(Op->getOperand(0), Info));
8129 }
8130
8131 // The folding we want to perform is:
8132 // (add x, [zext] (setcc cc ...) )
8133 //   -->
8134 // (csel x, (add x, 1), !cc ...)
8135 //
8136 // The latter will get matched to a CSINC instruction.
8137 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8138   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8139   SDValue LHS = Op->getOperand(0);
8140   SDValue RHS = Op->getOperand(1);
8141   SetCCInfoAndKind InfoAndKind;
8142
8143   // If neither operand is a SET_CC, give up.
8144   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8145     std::swap(LHS, RHS);
8146     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8147       return SDValue();
8148   }
8149
8150   // FIXME: This could be generatized to work for FP comparisons.
8151   EVT CmpVT = InfoAndKind.IsAArch64
8152                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8153                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8154   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8155     return SDValue();
8156
8157   SDValue CCVal;
8158   SDValue Cmp;
8159   SDLoc dl(Op);
8160   if (InfoAndKind.IsAArch64) {
8161     CCVal = DAG.getConstant(
8162         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8163         MVT::i32);
8164     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8165   } else
8166     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8167                       *InfoAndKind.Info.Generic.Opnd1,
8168                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8169                       CCVal, DAG, dl);
8170
8171   EVT VT = Op->getValueType(0);
8172   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8173   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8174 }
8175
8176 // The basic add/sub long vector instructions have variants with "2" on the end
8177 // which act on the high-half of their inputs. They are normally matched by
8178 // patterns like:
8179 //
8180 // (add (zeroext (extract_high LHS)),
8181 //      (zeroext (extract_high RHS)))
8182 // -> uaddl2 vD, vN, vM
8183 //
8184 // However, if one of the extracts is something like a duplicate, this
8185 // instruction can still be used profitably. This function puts the DAG into a
8186 // more appropriate form for those patterns to trigger.
8187 static SDValue performAddSubLongCombine(SDNode *N,
8188                                         TargetLowering::DAGCombinerInfo &DCI,
8189                                         SelectionDAG &DAG) {
8190   if (DCI.isBeforeLegalizeOps())
8191     return SDValue();
8192
8193   MVT VT = N->getSimpleValueType(0);
8194   if (!VT.is128BitVector()) {
8195     if (N->getOpcode() == ISD::ADD)
8196       return performSetccAddFolding(N, DAG);
8197     return SDValue();
8198   }
8199
8200   // Make sure both branches are extended in the same way.
8201   SDValue LHS = N->getOperand(0);
8202   SDValue RHS = N->getOperand(1);
8203   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8204        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8205       LHS.getOpcode() != RHS.getOpcode())
8206     return SDValue();
8207
8208   unsigned ExtType = LHS.getOpcode();
8209
8210   // It's not worth doing if at least one of the inputs isn't already an
8211   // extract, but we don't know which it'll be so we have to try both.
8212   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8213     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8214     if (!RHS.getNode())
8215       return SDValue();
8216
8217     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8218   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8219     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8220     if (!LHS.getNode())
8221       return SDValue();
8222
8223     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8224   }
8225
8226   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8227 }
8228
8229 // Massage DAGs which we can use the high-half "long" operations on into
8230 // something isel will recognize better. E.g.
8231 //
8232 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8233 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8234 //                     (extract_high (v2i64 (dup128 scalar)))))
8235 //
8236 static SDValue tryCombineLongOpWithDup(SDNode *N,
8237                                        TargetLowering::DAGCombinerInfo &DCI,
8238                                        SelectionDAG &DAG) {
8239   if (DCI.isBeforeLegalizeOps())
8240     return SDValue();
8241
8242   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8243   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8244   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8245   assert(LHS.getValueType().is64BitVector() &&
8246          RHS.getValueType().is64BitVector() &&
8247          "unexpected shape for long operation");
8248
8249   // Either node could be a DUP, but it's not worth doing both of them (you'd
8250   // just as well use the non-high version) so look for a corresponding extract
8251   // operation on the other "wing".
8252   if (isEssentiallyExtractSubvector(LHS)) {
8253     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8254     if (!RHS.getNode())
8255       return SDValue();
8256   } else if (isEssentiallyExtractSubvector(RHS)) {
8257     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8258     if (!LHS.getNode())
8259       return SDValue();
8260   }
8261
8262   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8263   if (IsIntrinsic)
8264     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8265                        N->getOperand(0), LHS, RHS);
8266   else
8267     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8268                        LHS, RHS);
8269 }
8270
8271 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8272   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8273   unsigned ElemBits = ElemTy.getSizeInBits();
8274
8275   int64_t ShiftAmount;
8276   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8277     APInt SplatValue, SplatUndef;
8278     unsigned SplatBitSize;
8279     bool HasAnyUndefs;
8280     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8281                               HasAnyUndefs, ElemBits) ||
8282         SplatBitSize != ElemBits)
8283       return SDValue();
8284
8285     ShiftAmount = SplatValue.getSExtValue();
8286   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8287     ShiftAmount = CVN->getSExtValue();
8288   } else
8289     return SDValue();
8290
8291   unsigned Opcode;
8292   bool IsRightShift;
8293   switch (IID) {
8294   default:
8295     llvm_unreachable("Unknown shift intrinsic");
8296   case Intrinsic::aarch64_neon_sqshl:
8297     Opcode = AArch64ISD::SQSHL_I;
8298     IsRightShift = false;
8299     break;
8300   case Intrinsic::aarch64_neon_uqshl:
8301     Opcode = AArch64ISD::UQSHL_I;
8302     IsRightShift = false;
8303     break;
8304   case Intrinsic::aarch64_neon_srshl:
8305     Opcode = AArch64ISD::SRSHR_I;
8306     IsRightShift = true;
8307     break;
8308   case Intrinsic::aarch64_neon_urshl:
8309     Opcode = AArch64ISD::URSHR_I;
8310     IsRightShift = true;
8311     break;
8312   case Intrinsic::aarch64_neon_sqshlu:
8313     Opcode = AArch64ISD::SQSHLU_I;
8314     IsRightShift = false;
8315     break;
8316   }
8317
8318   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8319     SDLoc dl(N);
8320     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8321                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8322   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8323     SDLoc dl(N);
8324     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8325                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8326   }
8327
8328   return SDValue();
8329 }
8330
8331 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8332 // the intrinsics must be legal and take an i32, this means there's almost
8333 // certainly going to be a zext in the DAG which we can eliminate.
8334 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8335   SDValue AndN = N->getOperand(2);
8336   if (AndN.getOpcode() != ISD::AND)
8337     return SDValue();
8338
8339   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8340   if (!CMask || CMask->getZExtValue() != Mask)
8341     return SDValue();
8342
8343   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8344                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8345 }
8346
8347 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8348                                            SelectionDAG &DAG) {
8349   SDLoc dl(N);
8350   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8351                      DAG.getNode(Opc, dl,
8352                                  N->getOperand(1).getSimpleValueType(),
8353                                  N->getOperand(1)),
8354                      DAG.getConstant(0, dl, MVT::i64));
8355 }
8356
8357 static SDValue performIntrinsicCombine(SDNode *N,
8358                                        TargetLowering::DAGCombinerInfo &DCI,
8359                                        const AArch64Subtarget *Subtarget) {
8360   SelectionDAG &DAG = DCI.DAG;
8361   unsigned IID = getIntrinsicID(N);
8362   switch (IID) {
8363   default:
8364     break;
8365   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8366   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8367     return tryCombineFixedPointConvert(N, DCI, DAG);
8368   case Intrinsic::aarch64_neon_saddv:
8369     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8370   case Intrinsic::aarch64_neon_uaddv:
8371     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8372   case Intrinsic::aarch64_neon_sminv:
8373     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8374   case Intrinsic::aarch64_neon_uminv:
8375     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8376   case Intrinsic::aarch64_neon_smaxv:
8377     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8378   case Intrinsic::aarch64_neon_umaxv:
8379     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8380   case Intrinsic::aarch64_neon_fmax:
8381     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8382                        N->getOperand(1), N->getOperand(2));
8383   case Intrinsic::aarch64_neon_fmin:
8384     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8385                        N->getOperand(1), N->getOperand(2));
8386   case Intrinsic::aarch64_neon_sabd:
8387     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8388                        N->getOperand(1), N->getOperand(2));
8389   case Intrinsic::aarch64_neon_uabd:
8390     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8391                        N->getOperand(1), N->getOperand(2));
8392   case Intrinsic::aarch64_neon_fmaxnm:
8393     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8394                        N->getOperand(1), N->getOperand(2));
8395   case Intrinsic::aarch64_neon_fminnm:
8396     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8397                        N->getOperand(1), N->getOperand(2));
8398   case Intrinsic::aarch64_neon_smull:
8399   case Intrinsic::aarch64_neon_umull:
8400   case Intrinsic::aarch64_neon_pmull:
8401   case Intrinsic::aarch64_neon_sqdmull:
8402     return tryCombineLongOpWithDup(N, DCI, DAG);
8403   case Intrinsic::aarch64_neon_sqshl:
8404   case Intrinsic::aarch64_neon_uqshl:
8405   case Intrinsic::aarch64_neon_sqshlu:
8406   case Intrinsic::aarch64_neon_srshl:
8407   case Intrinsic::aarch64_neon_urshl:
8408     return tryCombineShiftImm(IID, N, DAG);
8409   case Intrinsic::aarch64_crc32b:
8410   case Intrinsic::aarch64_crc32cb:
8411     return tryCombineCRC32(0xff, N, DAG);
8412   case Intrinsic::aarch64_crc32h:
8413   case Intrinsic::aarch64_crc32ch:
8414     return tryCombineCRC32(0xffff, N, DAG);
8415   }
8416   return SDValue();
8417 }
8418
8419 static SDValue performExtendCombine(SDNode *N,
8420                                     TargetLowering::DAGCombinerInfo &DCI,
8421                                     SelectionDAG &DAG) {
8422   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8423   // we can convert that DUP into another extract_high (of a bigger DUP), which
8424   // helps the backend to decide that an sabdl2 would be useful, saving a real
8425   // extract_high operation.
8426   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8427       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8428        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8429     SDNode *ABDNode = N->getOperand(0).getNode();
8430     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8431     if (!NewABD.getNode())
8432       return SDValue();
8433
8434     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8435                        NewABD);
8436   }
8437
8438   // This is effectively a custom type legalization for AArch64.
8439   //
8440   // Type legalization will split an extend of a small, legal, type to a larger
8441   // illegal type by first splitting the destination type, often creating
8442   // illegal source types, which then get legalized in isel-confusing ways,
8443   // leading to really terrible codegen. E.g.,
8444   //   %result = v8i32 sext v8i8 %value
8445   // becomes
8446   //   %losrc = extract_subreg %value, ...
8447   //   %hisrc = extract_subreg %value, ...
8448   //   %lo = v4i32 sext v4i8 %losrc
8449   //   %hi = v4i32 sext v4i8 %hisrc
8450   // Things go rapidly downhill from there.
8451   //
8452   // For AArch64, the [sz]ext vector instructions can only go up one element
8453   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8454   // take two instructions.
8455   //
8456   // This implies that the most efficient way to do the extend from v8i8
8457   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8458   // the normal splitting to happen for the v8i16->v8i32.
8459
8460   // This is pre-legalization to catch some cases where the default
8461   // type legalization will create ill-tempered code.
8462   if (!DCI.isBeforeLegalizeOps())
8463     return SDValue();
8464
8465   // We're only interested in cleaning things up for non-legal vector types
8466   // here. If both the source and destination are legal, things will just
8467   // work naturally without any fiddling.
8468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8469   EVT ResVT = N->getValueType(0);
8470   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8471     return SDValue();
8472   // If the vector type isn't a simple VT, it's beyond the scope of what
8473   // we're  worried about here. Let legalization do its thing and hope for
8474   // the best.
8475   SDValue Src = N->getOperand(0);
8476   EVT SrcVT = Src->getValueType(0);
8477   if (!ResVT.isSimple() || !SrcVT.isSimple())
8478     return SDValue();
8479
8480   // If the source VT is a 64-bit vector, we can play games and get the
8481   // better results we want.
8482   if (SrcVT.getSizeInBits() != 64)
8483     return SDValue();
8484
8485   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8486   unsigned ElementCount = SrcVT.getVectorNumElements();
8487   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8488   SDLoc DL(N);
8489   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8490
8491   // Now split the rest of the operation into two halves, each with a 64
8492   // bit source.
8493   EVT LoVT, HiVT;
8494   SDValue Lo, Hi;
8495   unsigned NumElements = ResVT.getVectorNumElements();
8496   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8497   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8498                                  ResVT.getVectorElementType(), NumElements / 2);
8499
8500   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8501                                LoVT.getVectorNumElements());
8502   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8503                    DAG.getConstant(0, DL, MVT::i64));
8504   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8505                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8506   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8507   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8508
8509   // Now combine the parts back together so we still have a single result
8510   // like the combiner expects.
8511   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8512 }
8513
8514 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8515 /// value. The load store optimizer pass will merge them to store pair stores.
8516 /// This has better performance than a splat of the scalar followed by a split
8517 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8518 /// followed by an ext.b and two stores.
8519 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8520   SDValue StVal = St->getValue();
8521   EVT VT = StVal.getValueType();
8522
8523   // Don't replace floating point stores, they possibly won't be transformed to
8524   // stp because of the store pair suppress pass.
8525   if (VT.isFloatingPoint())
8526     return SDValue();
8527
8528   // Check for insert vector elements.
8529   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8530     return SDValue();
8531
8532   // We can express a splat as store pair(s) for 2 or 4 elements.
8533   unsigned NumVecElts = VT.getVectorNumElements();
8534   if (NumVecElts != 4 && NumVecElts != 2)
8535     return SDValue();
8536   SDValue SplatVal = StVal.getOperand(1);
8537   unsigned RemainInsertElts = NumVecElts - 1;
8538
8539   // Check that this is a splat.
8540   while (--RemainInsertElts) {
8541     SDValue NextInsertElt = StVal.getOperand(0);
8542     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8543       return SDValue();
8544     if (NextInsertElt.getOperand(1) != SplatVal)
8545       return SDValue();
8546     StVal = NextInsertElt;
8547   }
8548   unsigned OrigAlignment = St->getAlignment();
8549   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8550   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8551
8552   // Create scalar stores. This is at least as good as the code sequence for a
8553   // split unaligned store which is a dup.s, ext.b, and two stores.
8554   // Most of the time the three stores should be replaced by store pair
8555   // instructions (stp).
8556   SDLoc DL(St);
8557   SDValue BasePtr = St->getBasePtr();
8558   SDValue NewST1 =
8559       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8560                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8561
8562   unsigned Offset = EltOffset;
8563   while (--NumVecElts) {
8564     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8565                                     DAG.getConstant(Offset, DL, MVT::i64));
8566     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8567                           St->getPointerInfo(), St->isVolatile(),
8568                           St->isNonTemporal(), Alignment);
8569     Offset += EltOffset;
8570   }
8571   return NewST1;
8572 }
8573
8574 static SDValue performSTORECombine(SDNode *N,
8575                                    TargetLowering::DAGCombinerInfo &DCI,
8576                                    SelectionDAG &DAG,
8577                                    const AArch64Subtarget *Subtarget) {
8578   if (!DCI.isBeforeLegalize())
8579     return SDValue();
8580
8581   StoreSDNode *S = cast<StoreSDNode>(N);
8582   if (S->isVolatile())
8583     return SDValue();
8584
8585   // FIXME: The logic for deciding if an unaligned store should be split should
8586   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8587   // a call to that function here.
8588
8589   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8590   // page boundaries. We want to split such stores.
8591   if (!Subtarget->isCyclone())
8592     return SDValue();
8593
8594   // Don't split at -Oz.
8595   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8596     return SDValue();
8597
8598   SDValue StVal = S->getValue();
8599   EVT VT = StVal.getValueType();
8600
8601   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8602   // those up regresses performance on micro-benchmarks and olden/bh.
8603   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8604     return SDValue();
8605
8606   // Split unaligned 16B stores. They are terrible for performance.
8607   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8608   // extensions can use this to mark that it does not want splitting to happen
8609   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8610   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8611   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8612       S->getAlignment() <= 2)
8613     return SDValue();
8614
8615   // If we get a splat of a scalar convert this vector store to a store of
8616   // scalars. They will be merged into store pairs thereby removing two
8617   // instructions.
8618   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8619     return ReplacedSplat;
8620
8621   SDLoc DL(S);
8622   unsigned NumElts = VT.getVectorNumElements() / 2;
8623   // Split VT into two.
8624   EVT HalfVT =
8625       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8626   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8627                                    DAG.getConstant(0, DL, MVT::i64));
8628   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8629                                    DAG.getConstant(NumElts, DL, MVT::i64));
8630   SDValue BasePtr = S->getBasePtr();
8631   SDValue NewST1 =
8632       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8633                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8634   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8635                                   DAG.getConstant(8, DL, MVT::i64));
8636   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8637                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8638                       S->getAlignment());
8639 }
8640
8641 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8642 /// post-increment LD1R.
8643 static SDValue performPostLD1Combine(SDNode *N,
8644                                      TargetLowering::DAGCombinerInfo &DCI,
8645                                      bool IsLaneOp) {
8646   if (DCI.isBeforeLegalizeOps())
8647     return SDValue();
8648
8649   SelectionDAG &DAG = DCI.DAG;
8650   EVT VT = N->getValueType(0);
8651
8652   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8653   SDNode *LD = N->getOperand(LoadIdx).getNode();
8654   // If it is not LOAD, can not do such combine.
8655   if (LD->getOpcode() != ISD::LOAD)
8656     return SDValue();
8657
8658   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8659   EVT MemVT = LoadSDN->getMemoryVT();
8660   // Check if memory operand is the same type as the vector element.
8661   if (MemVT != VT.getVectorElementType())
8662     return SDValue();
8663
8664   // Check if there are other uses. If so, do not combine as it will introduce
8665   // an extra load.
8666   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8667        ++UI) {
8668     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8669       continue;
8670     if (*UI != N)
8671       return SDValue();
8672   }
8673
8674   SDValue Addr = LD->getOperand(1);
8675   SDValue Vector = N->getOperand(0);
8676   // Search for a use of the address operand that is an increment.
8677   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8678        Addr.getNode()->use_end(); UI != UE; ++UI) {
8679     SDNode *User = *UI;
8680     if (User->getOpcode() != ISD::ADD
8681         || UI.getUse().getResNo() != Addr.getResNo())
8682       continue;
8683
8684     // Check that the add is independent of the load.  Otherwise, folding it
8685     // would create a cycle.
8686     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8687       continue;
8688     // Also check that add is not used in the vector operand.  This would also
8689     // create a cycle.
8690     if (User->isPredecessorOf(Vector.getNode()))
8691       continue;
8692
8693     // If the increment is a constant, it must match the memory ref size.
8694     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8695     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8696       uint32_t IncVal = CInc->getZExtValue();
8697       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8698       if (IncVal != NumBytes)
8699         continue;
8700       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8701     }
8702
8703     // Finally, check that the vector doesn't depend on the load.
8704     // Again, this would create a cycle.
8705     // The load depending on the vector is fine, as that's the case for the
8706     // LD1*post we'll eventually generate anyway.
8707     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8708       continue;
8709
8710     SmallVector<SDValue, 8> Ops;
8711     Ops.push_back(LD->getOperand(0));  // Chain
8712     if (IsLaneOp) {
8713       Ops.push_back(Vector);           // The vector to be inserted
8714       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8715     }
8716     Ops.push_back(Addr);
8717     Ops.push_back(Inc);
8718
8719     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8720     SDVTList SDTys = DAG.getVTList(Tys);
8721     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8722     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8723                                            MemVT,
8724                                            LoadSDN->getMemOperand());
8725
8726     // Update the uses.
8727     SmallVector<SDValue, 2> NewResults;
8728     NewResults.push_back(SDValue(LD, 0));             // The result of load
8729     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8730     DCI.CombineTo(LD, NewResults);
8731     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8732     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8733
8734     break;
8735   }
8736   return SDValue();
8737 }
8738
8739 /// This function handles the log2-shuffle pattern produced by the
8740 /// LoopVectorizer for the across vector reduction. It consists of
8741 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8742 /// are reduced, where s is an induction variable from 0 to
8743 /// log2(NumVectorElements).
8744 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8745                                                      unsigned Op,
8746                                                      SelectionDAG &DAG) {
8747   EVT VTy = OpV->getOperand(0).getValueType();
8748   if (!VTy.isVector())
8749     return SDValue();
8750
8751   int NumVecElts = VTy.getVectorNumElements();
8752   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8753     if (NumVecElts != 4)
8754       return SDValue();
8755   } else {
8756     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8757       return SDValue();
8758   }
8759
8760   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8761   SDValue PreOp = OpV;
8762   // Iterate over each step of the across vector reduction.
8763   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8764     SDValue CurOp = PreOp.getOperand(0);
8765     SDValue Shuffle = PreOp.getOperand(1);
8766     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8767       // Try to swap the 1st and 2nd operand as add and min/max instructions
8768       // are commutative.
8769       CurOp = PreOp.getOperand(1);
8770       Shuffle = PreOp.getOperand(0);
8771       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8772         return SDValue();
8773     }
8774
8775     // Check if the input vector is fed by the operator we want to handle,
8776     // except the last step; the very first input vector is not necessarily
8777     // the same operator we are handling.
8778     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8779       return SDValue();
8780
8781     // Check if it forms one step of the across vector reduction.
8782     // E.g.,
8783     //   %cur = add %1, %0
8784     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8785     //   %pre = add %cur, %shuffle
8786     if (Shuffle.getOperand(0) != CurOp)
8787       return SDValue();
8788
8789     int NumMaskElts = 1 << CurStep;
8790     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8791     // Check mask values in each step.
8792     // We expect the shuffle mask in each step follows a specific pattern
8793     // denoted here by the <M, U> form, where M is a sequence of integers
8794     // starting from NumMaskElts, increasing by 1, and the number integers
8795     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8796     // of undef in U should be NumVecElts - NumMaskElts.
8797     // E.g., for <8 x i16>, mask values in each step should be :
8798     //   step 0 : <1,u,u,u,u,u,u,u>
8799     //   step 1 : <2,3,u,u,u,u,u,u>
8800     //   step 2 : <4,5,6,7,u,u,u,u>
8801     for (int i = 0; i < NumVecElts; ++i)
8802       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8803           (i >= NumMaskElts && !(Mask[i] < 0)))
8804         return SDValue();
8805
8806     PreOp = CurOp;
8807   }
8808   unsigned Opcode;
8809   bool IsIntrinsic = false;
8810
8811   switch (Op) {
8812   default:
8813     llvm_unreachable("Unexpected operator for across vector reduction");
8814   case ISD::ADD:
8815     Opcode = AArch64ISD::UADDV;
8816     break;
8817   case ISD::SMAX:
8818     Opcode = AArch64ISD::SMAXV;
8819     break;
8820   case ISD::UMAX:
8821     Opcode = AArch64ISD::UMAXV;
8822     break;
8823   case ISD::SMIN:
8824     Opcode = AArch64ISD::SMINV;
8825     break;
8826   case ISD::UMIN:
8827     Opcode = AArch64ISD::UMINV;
8828     break;
8829   case ISD::FMAXNUM:
8830     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8831     IsIntrinsic = true;
8832     break;
8833   case ISD::FMINNUM:
8834     Opcode = Intrinsic::aarch64_neon_fminnmv;
8835     IsIntrinsic = true;
8836     break;
8837   }
8838   SDLoc DL(N);
8839
8840   return IsIntrinsic
8841              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8842                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8843              : DAG.getNode(
8844                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8845                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8846                    DAG.getConstant(0, DL, MVT::i64));
8847 }
8848
8849 /// Target-specific DAG combine for the across vector min/max reductions.
8850 /// This function specifically handles the final clean-up step of the vector
8851 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8852 /// pattern, which narrows down and finds the final min/max value from all
8853 /// elements of the vector.
8854 /// For example, for a <16 x i8> vector :
8855 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8856 ///   %smax0 = smax %arr, svn0
8857 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8858 ///   %smax1 = smax %smax0, %svn1
8859 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8860 ///   %smax2 = smax %smax1, svn2
8861 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8862 ///   %sc = setcc %smax2, %svn3, gt
8863 ///   %n0 = extract_vector_elt %sc, #0
8864 ///   %n1 = extract_vector_elt %smax2, #0
8865 ///   %n2 = extract_vector_elt $smax2, #1
8866 ///   %result = select %n0, %n1, n2
8867 ///     becomes :
8868 ///   %1 = smaxv %0
8869 ///   %result = extract_vector_elt %1, 0
8870 static SDValue
8871 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8872                                         const AArch64Subtarget *Subtarget) {
8873   if (!Subtarget->hasNEON())
8874     return SDValue();
8875
8876   SDValue N0 = N->getOperand(0);
8877   SDValue IfTrue = N->getOperand(1);
8878   SDValue IfFalse = N->getOperand(2);
8879
8880   // Check if the SELECT merges up the final result of the min/max
8881   // from a vector.
8882   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8883       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8884       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8885     return SDValue();
8886
8887   // Expect N0 is fed by SETCC.
8888   SDValue SetCC = N0.getOperand(0);
8889   EVT SetCCVT = SetCC.getValueType();
8890   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8891       SetCCVT.getVectorElementType() != MVT::i1)
8892     return SDValue();
8893
8894   SDValue VectorOp = SetCC.getOperand(0);
8895   unsigned Op = VectorOp->getOpcode();
8896   // Check if the input vector is fed by the operator we want to handle.
8897   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8898       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8899     return SDValue();
8900
8901   EVT VTy = VectorOp.getValueType();
8902   if (!VTy.isVector())
8903     return SDValue();
8904
8905   if (VTy.getSizeInBits() < 64)
8906     return SDValue();
8907
8908   EVT EltTy = VTy.getVectorElementType();
8909   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8910     if (EltTy != MVT::f32)
8911       return SDValue();
8912   } else {
8913     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8914       return SDValue();
8915   }
8916
8917   // Check if extracting from the same vector.
8918   // For example,
8919   //   %sc = setcc %vector, %svn1, gt
8920   //   %n0 = extract_vector_elt %sc, #0
8921   //   %n1 = extract_vector_elt %vector, #0
8922   //   %n2 = extract_vector_elt $vector, #1
8923   if (!(VectorOp == IfTrue->getOperand(0) &&
8924         VectorOp == IfFalse->getOperand(0)))
8925     return SDValue();
8926
8927   // Check if the condition code is matched with the operator type.
8928   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8929   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8930       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8931       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8932       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8933       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8934        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8935        CC != ISD::SETGE) ||
8936       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8937        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8938        CC != ISD::SETLE))
8939     return SDValue();
8940
8941   // Expect to check only lane 0 from the vector SETCC.
8942   if (!isa<ConstantSDNode>(N0.getOperand(1)) ||
8943       cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue() != 0)
8944     return SDValue();
8945
8946   // Expect to extract the true value from lane 0.
8947   if (!isa<ConstantSDNode>(IfTrue.getOperand(1)) ||
8948       cast<ConstantSDNode>(IfTrue.getOperand(1))->getZExtValue() != 0)
8949     return SDValue();
8950
8951   // Expect to extract the false value from lane 1.
8952   if (!isa<ConstantSDNode>(IfFalse.getOperand(1)) ||
8953       cast<ConstantSDNode>(IfFalse.getOperand(1))->getZExtValue() != 1)
8954     return SDValue();
8955
8956   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8957 }
8958
8959 /// Target-specific DAG combine for the across vector add reduction.
8960 /// This function specifically handles the final clean-up step of the vector
8961 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8962 /// pattern, which adds all elements of a vector together.
8963 /// For example, for a <4 x i32> vector :
8964 ///   %1 = vector_shuffle %0, <2,3,u,u>
8965 ///   %2 = add %0, %1
8966 ///   %3 = vector_shuffle %2, <1,u,u,u>
8967 ///   %4 = add %2, %3
8968 ///   %result = extract_vector_elt %4, 0
8969 /// becomes :
8970 ///   %0 = uaddv %0
8971 ///   %result = extract_vector_elt %0, 0
8972 static SDValue
8973 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
8974                                      const AArch64Subtarget *Subtarget) {
8975   if (!Subtarget->hasNEON())
8976     return SDValue();
8977   SDValue N0 = N->getOperand(0);
8978   SDValue N1 = N->getOperand(1);
8979
8980   // Check if the input vector is fed by the ADD.
8981   if (N0->getOpcode() != ISD::ADD)
8982     return SDValue();
8983
8984   // The vector extract idx must constant zero because we only expect the final
8985   // result of the reduction is placed in lane 0.
8986   if (!isa<ConstantSDNode>(N1) || cast<ConstantSDNode>(N1)->getZExtValue() != 0)
8987     return SDValue();
8988
8989   EVT VTy = N0.getValueType();
8990   if (!VTy.isVector())
8991     return SDValue();
8992
8993   EVT EltTy = VTy.getVectorElementType();
8994   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8995     return SDValue();
8996
8997   if (VTy.getSizeInBits() < 64)
8998     return SDValue();
8999
9000   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9001 }
9002
9003 /// Target-specific DAG combine function for NEON load/store intrinsics
9004 /// to merge base address updates.
9005 static SDValue performNEONPostLDSTCombine(SDNode *N,
9006                                           TargetLowering::DAGCombinerInfo &DCI,
9007                                           SelectionDAG &DAG) {
9008   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9009     return SDValue();
9010
9011   unsigned AddrOpIdx = N->getNumOperands() - 1;
9012   SDValue Addr = N->getOperand(AddrOpIdx);
9013
9014   // Search for a use of the address operand that is an increment.
9015   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9016        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9017     SDNode *User = *UI;
9018     if (User->getOpcode() != ISD::ADD ||
9019         UI.getUse().getResNo() != Addr.getResNo())
9020       continue;
9021
9022     // Check that the add is independent of the load/store.  Otherwise, folding
9023     // it would create a cycle.
9024     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9025       continue;
9026
9027     // Find the new opcode for the updating load/store.
9028     bool IsStore = false;
9029     bool IsLaneOp = false;
9030     bool IsDupOp = false;
9031     unsigned NewOpc = 0;
9032     unsigned NumVecs = 0;
9033     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9034     switch (IntNo) {
9035     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9036     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9037       NumVecs = 2; break;
9038     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9039       NumVecs = 3; break;
9040     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9041       NumVecs = 4; break;
9042     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9043       NumVecs = 2; IsStore = true; break;
9044     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9045       NumVecs = 3; IsStore = true; break;
9046     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9047       NumVecs = 4; IsStore = true; break;
9048     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9049       NumVecs = 2; break;
9050     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9051       NumVecs = 3; break;
9052     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9053       NumVecs = 4; break;
9054     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9055       NumVecs = 2; IsStore = true; break;
9056     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9057       NumVecs = 3; IsStore = true; break;
9058     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9059       NumVecs = 4; IsStore = true; break;
9060     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9061       NumVecs = 2; IsDupOp = true; break;
9062     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9063       NumVecs = 3; IsDupOp = true; break;
9064     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9065       NumVecs = 4; IsDupOp = true; break;
9066     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9067       NumVecs = 2; IsLaneOp = true; break;
9068     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9069       NumVecs = 3; IsLaneOp = true; break;
9070     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9071       NumVecs = 4; IsLaneOp = true; break;
9072     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9073       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9074     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9075       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9076     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9077       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9078     }
9079
9080     EVT VecTy;
9081     if (IsStore)
9082       VecTy = N->getOperand(2).getValueType();
9083     else
9084       VecTy = N->getValueType(0);
9085
9086     // If the increment is a constant, it must match the memory ref size.
9087     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9088     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9089       uint32_t IncVal = CInc->getZExtValue();
9090       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9091       if (IsLaneOp || IsDupOp)
9092         NumBytes /= VecTy.getVectorNumElements();
9093       if (IncVal != NumBytes)
9094         continue;
9095       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9096     }
9097     SmallVector<SDValue, 8> Ops;
9098     Ops.push_back(N->getOperand(0)); // Incoming chain
9099     // Load lane and store have vector list as input.
9100     if (IsLaneOp || IsStore)
9101       for (unsigned i = 2; i < AddrOpIdx; ++i)
9102         Ops.push_back(N->getOperand(i));
9103     Ops.push_back(Addr); // Base register
9104     Ops.push_back(Inc);
9105
9106     // Return Types.
9107     EVT Tys[6];
9108     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9109     unsigned n;
9110     for (n = 0; n < NumResultVecs; ++n)
9111       Tys[n] = VecTy;
9112     Tys[n++] = MVT::i64;  // Type of write back register
9113     Tys[n] = MVT::Other;  // Type of the chain
9114     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9115
9116     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9117     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9118                                            MemInt->getMemoryVT(),
9119                                            MemInt->getMemOperand());
9120
9121     // Update the uses.
9122     std::vector<SDValue> NewResults;
9123     for (unsigned i = 0; i < NumResultVecs; ++i) {
9124       NewResults.push_back(SDValue(UpdN.getNode(), i));
9125     }
9126     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9127     DCI.CombineTo(N, NewResults);
9128     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9129
9130     break;
9131   }
9132   return SDValue();
9133 }
9134
9135 // Checks to see if the value is the prescribed width and returns information
9136 // about its extension mode.
9137 static
9138 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9139   ExtType = ISD::NON_EXTLOAD;
9140   switch(V.getNode()->getOpcode()) {
9141   default:
9142     return false;
9143   case ISD::LOAD: {
9144     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9145     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9146        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9147       ExtType = LoadNode->getExtensionType();
9148       return true;
9149     }
9150     return false;
9151   }
9152   case ISD::AssertSext: {
9153     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9154     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9155        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9156       ExtType = ISD::SEXTLOAD;
9157       return true;
9158     }
9159     return false;
9160   }
9161   case ISD::AssertZext: {
9162     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9163     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9164        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9165       ExtType = ISD::ZEXTLOAD;
9166       return true;
9167     }
9168     return false;
9169   }
9170   case ISD::Constant:
9171   case ISD::TargetConstant: {
9172     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9173         1LL << (width - 1))
9174       return true;
9175     return false;
9176   }
9177   }
9178
9179   return true;
9180 }
9181
9182 // This function does a whole lot of voodoo to determine if the tests are
9183 // equivalent without and with a mask. Essentially what happens is that given a
9184 // DAG resembling:
9185 //
9186 //  +-------------+ +-------------+ +-------------+ +-------------+
9187 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9188 //  +-------------+ +-------------+ +-------------+ +-------------+
9189 //           |           |           |               |
9190 //           V           V           |    +----------+
9191 //          +-------------+  +----+  |    |
9192 //          |     ADD     |  |0xff|  |    |
9193 //          +-------------+  +----+  |    |
9194 //                  |           |    |    |
9195 //                  V           V    |    |
9196 //                 +-------------+   |    |
9197 //                 |     AND     |   |    |
9198 //                 +-------------+   |    |
9199 //                      |            |    |
9200 //                      +-----+      |    |
9201 //                            |      |    |
9202 //                            V      V    V
9203 //                           +-------------+
9204 //                           |     CMP     |
9205 //                           +-------------+
9206 //
9207 // The AND node may be safely removed for some combinations of inputs. In
9208 // particular we need to take into account the extension type of the Input,
9209 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9210 // width of the input (this can work for any width inputs, the above graph is
9211 // specific to 8 bits.
9212 //
9213 // The specific equations were worked out by generating output tables for each
9214 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9215 // problem was simplified by working with 4 bit inputs, which means we only
9216 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9217 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9218 // patterns present in both extensions (0,7). For every distinct set of
9219 // AddConstant and CompConstants bit patterns we can consider the masked and
9220 // unmasked versions to be equivalent if the result of this function is true for
9221 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9222 //
9223 //   sub      w8, w0, w1
9224 //   and      w10, w8, #0x0f
9225 //   cmp      w8, w2
9226 //   cset     w9, AArch64CC
9227 //   cmp      w10, w2
9228 //   cset     w11, AArch64CC
9229 //   cmp      w9, w11
9230 //   cset     w0, eq
9231 //   ret
9232 //
9233 // Since the above function shows when the outputs are equivalent it defines
9234 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9235 // would be expensive to run during compiles. The equations below were written
9236 // in a test harness that confirmed they gave equivalent outputs to the above
9237 // for all inputs function, so they can be used determine if the removal is
9238 // legal instead.
9239 //
9240 // isEquivalentMaskless() is the code for testing if the AND can be removed
9241 // factored out of the DAG recognition as the DAG can take several forms.
9242
9243 static
9244 bool isEquivalentMaskless(unsigned CC, unsigned width,
9245                           ISD::LoadExtType ExtType, signed AddConstant,
9246                           signed CompConstant) {
9247   // By being careful about our equations and only writing the in term
9248   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9249   // make them generally applicable to all bit widths.
9250   signed MaxUInt = (1 << width);
9251
9252   // For the purposes of these comparisons sign extending the type is
9253   // equivalent to zero extending the add and displacing it by half the integer
9254   // width. Provided we are careful and make sure our equations are valid over
9255   // the whole range we can just adjust the input and avoid writing equations
9256   // for sign extended inputs.
9257   if (ExtType == ISD::SEXTLOAD)
9258     AddConstant -= (1 << (width-1));
9259
9260   switch(CC) {
9261   case AArch64CC::LE:
9262   case AArch64CC::GT: {
9263     if ((AddConstant == 0) ||
9264         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9265         (AddConstant >= 0 && CompConstant < 0) ||
9266         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9267       return true;
9268   } break;
9269   case AArch64CC::LT:
9270   case AArch64CC::GE: {
9271     if ((AddConstant == 0) ||
9272         (AddConstant >= 0 && CompConstant <= 0) ||
9273         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9274       return true;
9275   } break;
9276   case AArch64CC::HI:
9277   case AArch64CC::LS: {
9278     if ((AddConstant >= 0 && CompConstant < 0) ||
9279        (AddConstant <= 0 && CompConstant >= -1 &&
9280         CompConstant < AddConstant + MaxUInt))
9281       return true;
9282   } break;
9283   case AArch64CC::PL:
9284   case AArch64CC::MI: {
9285     if ((AddConstant == 0) ||
9286         (AddConstant > 0 && CompConstant <= 0) ||
9287         (AddConstant < 0 && CompConstant <= AddConstant))
9288       return true;
9289   } break;
9290   case AArch64CC::LO:
9291   case AArch64CC::HS: {
9292     if ((AddConstant >= 0 && CompConstant <= 0) ||
9293         (AddConstant <= 0 && CompConstant >= 0 &&
9294          CompConstant <= AddConstant + MaxUInt))
9295       return true;
9296   } break;
9297   case AArch64CC::EQ:
9298   case AArch64CC::NE: {
9299     if ((AddConstant > 0 && CompConstant < 0) ||
9300         (AddConstant < 0 && CompConstant >= 0 &&
9301          CompConstant < AddConstant + MaxUInt) ||
9302         (AddConstant >= 0 && CompConstant >= 0 &&
9303          CompConstant >= AddConstant) ||
9304         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9305
9306       return true;
9307   } break;
9308   case AArch64CC::VS:
9309   case AArch64CC::VC:
9310   case AArch64CC::AL:
9311   case AArch64CC::NV:
9312     return true;
9313   case AArch64CC::Invalid:
9314     break;
9315   }
9316
9317   return false;
9318 }
9319
9320 static
9321 SDValue performCONDCombine(SDNode *N,
9322                            TargetLowering::DAGCombinerInfo &DCI,
9323                            SelectionDAG &DAG, unsigned CCIndex,
9324                            unsigned CmpIndex) {
9325   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9326   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9327   unsigned CondOpcode = SubsNode->getOpcode();
9328
9329   if (CondOpcode != AArch64ISD::SUBS)
9330     return SDValue();
9331
9332   // There is a SUBS feeding this condition. Is it fed by a mask we can
9333   // use?
9334
9335   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9336   unsigned MaskBits = 0;
9337
9338   if (AndNode->getOpcode() != ISD::AND)
9339     return SDValue();
9340
9341   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9342     uint32_t CNV = CN->getZExtValue();
9343     if (CNV == 255)
9344       MaskBits = 8;
9345     else if (CNV == 65535)
9346       MaskBits = 16;
9347   }
9348
9349   if (!MaskBits)
9350     return SDValue();
9351
9352   SDValue AddValue = AndNode->getOperand(0);
9353
9354   if (AddValue.getOpcode() != ISD::ADD)
9355     return SDValue();
9356
9357   // The basic dag structure is correct, grab the inputs and validate them.
9358
9359   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9360   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9361   SDValue SubsInputValue = SubsNode->getOperand(1);
9362
9363   // The mask is present and the provenance of all the values is a smaller type,
9364   // lets see if the mask is superfluous.
9365
9366   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9367       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9368     return SDValue();
9369
9370   ISD::LoadExtType ExtType;
9371
9372   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9373       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9374       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9375     return SDValue();
9376
9377   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9378                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9379                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9380     return SDValue();
9381
9382   // The AND is not necessary, remove it.
9383
9384   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9385                                SubsNode->getValueType(1));
9386   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9387
9388   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9389   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9390
9391   return SDValue(N, 0);
9392 }
9393
9394 // Optimize compare with zero and branch.
9395 static SDValue performBRCONDCombine(SDNode *N,
9396                                     TargetLowering::DAGCombinerInfo &DCI,
9397                                     SelectionDAG &DAG) {
9398   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9399   if (NV.getNode())
9400     N = NV.getNode();
9401   SDValue Chain = N->getOperand(0);
9402   SDValue Dest = N->getOperand(1);
9403   SDValue CCVal = N->getOperand(2);
9404   SDValue Cmp = N->getOperand(3);
9405
9406   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9407   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9408   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9409     return SDValue();
9410
9411   unsigned CmpOpc = Cmp.getOpcode();
9412   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9413     return SDValue();
9414
9415   // Only attempt folding if there is only one use of the flag and no use of the
9416   // value.
9417   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9418     return SDValue();
9419
9420   SDValue LHS = Cmp.getOperand(0);
9421   SDValue RHS = Cmp.getOperand(1);
9422
9423   assert(LHS.getValueType() == RHS.getValueType() &&
9424          "Expected the value type to be the same for both operands!");
9425   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9426     return SDValue();
9427
9428   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9429     std::swap(LHS, RHS);
9430
9431   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9432     return SDValue();
9433
9434   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9435       LHS.getOpcode() == ISD::SRL)
9436     return SDValue();
9437
9438   // Fold the compare into the branch instruction.
9439   SDValue BR;
9440   if (CC == AArch64CC::EQ)
9441     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9442   else
9443     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9444
9445   // Do not add new nodes to DAG combiner worklist.
9446   DCI.CombineTo(N, BR, false);
9447
9448   return SDValue();
9449 }
9450
9451 // vselect (v1i1 setcc) ->
9452 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9453 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9454 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9455 // such VSELECT.
9456 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9457   SDValue N0 = N->getOperand(0);
9458   EVT CCVT = N0.getValueType();
9459
9460   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9461       CCVT.getVectorElementType() != MVT::i1)
9462     return SDValue();
9463
9464   EVT ResVT = N->getValueType(0);
9465   EVT CmpVT = N0.getOperand(0).getValueType();
9466   // Only combine when the result type is of the same size as the compared
9467   // operands.
9468   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9469     return SDValue();
9470
9471   SDValue IfTrue = N->getOperand(1);
9472   SDValue IfFalse = N->getOperand(2);
9473   SDValue SetCC =
9474       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9475                    N0.getOperand(0), N0.getOperand(1),
9476                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9477   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9478                      IfTrue, IfFalse);
9479 }
9480
9481 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9482 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9483 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9484 /// with a vector one followed by a DUP shuffle on the result.
9485 static SDValue performSelectCombine(SDNode *N,
9486                                     TargetLowering::DAGCombinerInfo &DCI) {
9487   SelectionDAG &DAG = DCI.DAG;
9488   SDValue N0 = N->getOperand(0);
9489   EVT ResVT = N->getValueType(0);
9490
9491   if (N0.getOpcode() != ISD::SETCC)
9492     return SDValue();
9493
9494   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9495   // scalar SetCCResultType. We also don't expect vectors, because we assume
9496   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9497   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9498          "Scalar-SETCC feeding SELECT has unexpected result type!");
9499
9500   // If NumMaskElts == 0, the comparison is larger than select result. The
9501   // largest real NEON comparison is 64-bits per lane, which means the result is
9502   // at most 32-bits and an illegal vector. Just bail out for now.
9503   EVT SrcVT = N0.getOperand(0).getValueType();
9504
9505   // Don't try to do this optimization when the setcc itself has i1 operands.
9506   // There are no legal vectors of i1, so this would be pointless.
9507   if (SrcVT == MVT::i1)
9508     return SDValue();
9509
9510   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9511   if (!ResVT.isVector() || NumMaskElts == 0)
9512     return SDValue();
9513
9514   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9515   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9516
9517   // Also bail out if the vector CCVT isn't the same size as ResVT.
9518   // This can happen if the SETCC operand size doesn't divide the ResVT size
9519   // (e.g., f64 vs v3f32).
9520   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9521     return SDValue();
9522
9523   // Make sure we didn't create illegal types, if we're not supposed to.
9524   assert(DCI.isBeforeLegalize() ||
9525          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9526
9527   // First perform a vector comparison, where lane 0 is the one we're interested
9528   // in.
9529   SDLoc DL(N0);
9530   SDValue LHS =
9531       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9532   SDValue RHS =
9533       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9534   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9535
9536   // Now duplicate the comparison mask we want across all other lanes.
9537   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9538   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9539   Mask = DAG.getNode(ISD::BITCAST, DL,
9540                      ResVT.changeVectorElementTypeToInteger(), Mask);
9541
9542   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9543 }
9544
9545 /// Get rid of unnecessary NVCASTs (that don't change the type).
9546 static SDValue performNVCASTCombine(SDNode *N) {
9547   if (N->getValueType(0) == N->getOperand(0).getValueType())
9548     return N->getOperand(0);
9549
9550   return SDValue();
9551 }
9552
9553 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9554                                                  DAGCombinerInfo &DCI) const {
9555   SelectionDAG &DAG = DCI.DAG;
9556   switch (N->getOpcode()) {
9557   default:
9558     break;
9559   case ISD::ADD:
9560   case ISD::SUB:
9561     return performAddSubLongCombine(N, DCI, DAG);
9562   case ISD::XOR:
9563     return performXorCombine(N, DAG, DCI, Subtarget);
9564   case ISD::MUL:
9565     return performMulCombine(N, DAG, DCI, Subtarget);
9566   case ISD::SINT_TO_FP:
9567   case ISD::UINT_TO_FP:
9568     return performIntToFpCombine(N, DAG, Subtarget);
9569   case ISD::FP_TO_SINT:
9570   case ISD::FP_TO_UINT:
9571     return performFpToIntCombine(N, DAG, Subtarget);
9572   case ISD::FDIV:
9573     return performFDivCombine(N, DAG, Subtarget);
9574   case ISD::OR:
9575     return performORCombine(N, DCI, Subtarget);
9576   case ISD::INTRINSIC_WO_CHAIN:
9577     return performIntrinsicCombine(N, DCI, Subtarget);
9578   case ISD::ANY_EXTEND:
9579   case ISD::ZERO_EXTEND:
9580   case ISD::SIGN_EXTEND:
9581     return performExtendCombine(N, DCI, DAG);
9582   case ISD::BITCAST:
9583     return performBitcastCombine(N, DCI, DAG);
9584   case ISD::CONCAT_VECTORS:
9585     return performConcatVectorsCombine(N, DCI, DAG);
9586   case ISD::SELECT: {
9587     SDValue RV = performSelectCombine(N, DCI);
9588     if (!RV.getNode())
9589       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9590     return RV;
9591   }
9592   case ISD::VSELECT:
9593     return performVSelectCombine(N, DCI.DAG);
9594   case ISD::STORE:
9595     return performSTORECombine(N, DCI, DAG, Subtarget);
9596   case AArch64ISD::BRCOND:
9597     return performBRCONDCombine(N, DCI, DAG);
9598   case AArch64ISD::CSEL:
9599     return performCONDCombine(N, DCI, DAG, 2, 3);
9600   case AArch64ISD::DUP:
9601     return performPostLD1Combine(N, DCI, false);
9602   case AArch64ISD::NVCAST:
9603     return performNVCASTCombine(N);
9604   case ISD::INSERT_VECTOR_ELT:
9605     return performPostLD1Combine(N, DCI, true);
9606   case ISD::EXTRACT_VECTOR_ELT:
9607     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9608   case ISD::INTRINSIC_VOID:
9609   case ISD::INTRINSIC_W_CHAIN:
9610     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9611     case Intrinsic::aarch64_neon_ld2:
9612     case Intrinsic::aarch64_neon_ld3:
9613     case Intrinsic::aarch64_neon_ld4:
9614     case Intrinsic::aarch64_neon_ld1x2:
9615     case Intrinsic::aarch64_neon_ld1x3:
9616     case Intrinsic::aarch64_neon_ld1x4:
9617     case Intrinsic::aarch64_neon_ld2lane:
9618     case Intrinsic::aarch64_neon_ld3lane:
9619     case Intrinsic::aarch64_neon_ld4lane:
9620     case Intrinsic::aarch64_neon_ld2r:
9621     case Intrinsic::aarch64_neon_ld3r:
9622     case Intrinsic::aarch64_neon_ld4r:
9623     case Intrinsic::aarch64_neon_st2:
9624     case Intrinsic::aarch64_neon_st3:
9625     case Intrinsic::aarch64_neon_st4:
9626     case Intrinsic::aarch64_neon_st1x2:
9627     case Intrinsic::aarch64_neon_st1x3:
9628     case Intrinsic::aarch64_neon_st1x4:
9629     case Intrinsic::aarch64_neon_st2lane:
9630     case Intrinsic::aarch64_neon_st3lane:
9631     case Intrinsic::aarch64_neon_st4lane:
9632       return performNEONPostLDSTCombine(N, DCI, DAG);
9633     default:
9634       break;
9635     }
9636   }
9637   return SDValue();
9638 }
9639
9640 // Check if the return value is used as only a return value, as otherwise
9641 // we can't perform a tail-call. In particular, we need to check for
9642 // target ISD nodes that are returns and any other "odd" constructs
9643 // that the generic analysis code won't necessarily catch.
9644 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9645                                                SDValue &Chain) const {
9646   if (N->getNumValues() != 1)
9647     return false;
9648   if (!N->hasNUsesOfValue(1, 0))
9649     return false;
9650
9651   SDValue TCChain = Chain;
9652   SDNode *Copy = *N->use_begin();
9653   if (Copy->getOpcode() == ISD::CopyToReg) {
9654     // If the copy has a glue operand, we conservatively assume it isn't safe to
9655     // perform a tail call.
9656     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9657         MVT::Glue)
9658       return false;
9659     TCChain = Copy->getOperand(0);
9660   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9661     return false;
9662
9663   bool HasRet = false;
9664   for (SDNode *Node : Copy->uses()) {
9665     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9666       return false;
9667     HasRet = true;
9668   }
9669
9670   if (!HasRet)
9671     return false;
9672
9673   Chain = TCChain;
9674   return true;
9675 }
9676
9677 // Return whether the an instruction can potentially be optimized to a tail
9678 // call. This will cause the optimizers to attempt to move, or duplicate,
9679 // return instructions to help enable tail call optimizations for this
9680 // instruction.
9681 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9682   if (!CI->isTailCall())
9683     return false;
9684
9685   return true;
9686 }
9687
9688 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9689                                                    SDValue &Offset,
9690                                                    ISD::MemIndexedMode &AM,
9691                                                    bool &IsInc,
9692                                                    SelectionDAG &DAG) const {
9693   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9694     return false;
9695
9696   Base = Op->getOperand(0);
9697   // All of the indexed addressing mode instructions take a signed
9698   // 9 bit immediate offset.
9699   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9700     int64_t RHSC = (int64_t)RHS->getZExtValue();
9701     if (RHSC >= 256 || RHSC <= -256)
9702       return false;
9703     IsInc = (Op->getOpcode() == ISD::ADD);
9704     Offset = Op->getOperand(1);
9705     return true;
9706   }
9707   return false;
9708 }
9709
9710 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9711                                                       SDValue &Offset,
9712                                                       ISD::MemIndexedMode &AM,
9713                                                       SelectionDAG &DAG) const {
9714   EVT VT;
9715   SDValue Ptr;
9716   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9717     VT = LD->getMemoryVT();
9718     Ptr = LD->getBasePtr();
9719   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9720     VT = ST->getMemoryVT();
9721     Ptr = ST->getBasePtr();
9722   } else
9723     return false;
9724
9725   bool IsInc;
9726   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9727     return false;
9728   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9729   return true;
9730 }
9731
9732 bool AArch64TargetLowering::getPostIndexedAddressParts(
9733     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9734     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9735   EVT VT;
9736   SDValue Ptr;
9737   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9738     VT = LD->getMemoryVT();
9739     Ptr = LD->getBasePtr();
9740   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9741     VT = ST->getMemoryVT();
9742     Ptr = ST->getBasePtr();
9743   } else
9744     return false;
9745
9746   bool IsInc;
9747   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9748     return false;
9749   // Post-indexing updates the base, so it's not a valid transform
9750   // if that's not the same as the load's pointer.
9751   if (Ptr != Base)
9752     return false;
9753   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9754   return true;
9755 }
9756
9757 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9758                                   SelectionDAG &DAG) {
9759   SDLoc DL(N);
9760   SDValue Op = N->getOperand(0);
9761
9762   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9763     return;
9764
9765   Op = SDValue(
9766       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9767                          DAG.getUNDEF(MVT::i32), Op,
9768                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9769       0);
9770   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9771   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9772 }
9773
9774 static void ReplaceReductionResults(SDNode *N,
9775                                     SmallVectorImpl<SDValue> &Results,
9776                                     SelectionDAG &DAG, unsigned InterOp,
9777                                     unsigned AcrossOp) {
9778   EVT LoVT, HiVT;
9779   SDValue Lo, Hi;
9780   SDLoc dl(N);
9781   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9782   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9783   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9784   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9785   Results.push_back(SplitVal);
9786 }
9787
9788 void AArch64TargetLowering::ReplaceNodeResults(
9789     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9790   switch (N->getOpcode()) {
9791   default:
9792     llvm_unreachable("Don't know how to custom expand this");
9793   case ISD::BITCAST:
9794     ReplaceBITCASTResults(N, Results, DAG);
9795     return;
9796   case AArch64ISD::SADDV:
9797     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9798     return;
9799   case AArch64ISD::UADDV:
9800     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9801     return;
9802   case AArch64ISD::SMINV:
9803     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9804     return;
9805   case AArch64ISD::UMINV:
9806     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9807     return;
9808   case AArch64ISD::SMAXV:
9809     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9810     return;
9811   case AArch64ISD::UMAXV:
9812     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9813     return;
9814   case ISD::FP_TO_UINT:
9815   case ISD::FP_TO_SINT:
9816     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9817     // Let normal code take care of it by not adding anything to Results.
9818     return;
9819   }
9820 }
9821
9822 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9823   return true;
9824 }
9825
9826 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9827   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9828   // reciprocal if there are three or more FDIVs.
9829   return 3;
9830 }
9831
9832 TargetLoweringBase::LegalizeTypeAction
9833 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9834   MVT SVT = VT.getSimpleVT();
9835   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9836   // v4i16, v2i32 instead of to promote.
9837   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9838       || SVT == MVT::v1f32)
9839     return TypeWidenVector;
9840
9841   return TargetLoweringBase::getPreferredVectorAction(VT);
9842 }
9843
9844 // Loads and stores less than 128-bits are already atomic; ones above that
9845 // are doomed anyway, so defer to the default libcall and blame the OS when
9846 // things go wrong.
9847 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9848   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9849   return Size == 128;
9850 }
9851
9852 // Loads and stores less than 128-bits are already atomic; ones above that
9853 // are doomed anyway, so defer to the default libcall and blame the OS when
9854 // things go wrong.
9855 TargetLowering::AtomicExpansionKind
9856 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9857   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9858   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9859 }
9860
9861 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9862 TargetLowering::AtomicExpansionKind
9863 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9864   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9865   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9866 }
9867
9868 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9869     AtomicCmpXchgInst *AI) const {
9870   return true;
9871 }
9872
9873 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9874                                              AtomicOrdering Ord) const {
9875   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9876   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9877   bool IsAcquire = isAtLeastAcquire(Ord);
9878
9879   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9880   // intrinsic must return {i64, i64} and we have to recombine them into a
9881   // single i128 here.
9882   if (ValTy->getPrimitiveSizeInBits() == 128) {
9883     Intrinsic::ID Int =
9884         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9885     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9886
9887     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9888     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9889
9890     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9891     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9892     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9893     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9894     return Builder.CreateOr(
9895         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9896   }
9897
9898   Type *Tys[] = { Addr->getType() };
9899   Intrinsic::ID Int =
9900       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9901   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9902
9903   return Builder.CreateTruncOrBitCast(
9904       Builder.CreateCall(Ldxr, Addr),
9905       cast<PointerType>(Addr->getType())->getElementType());
9906 }
9907
9908 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9909     IRBuilder<> &Builder) const {
9910   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9911   Builder.CreateCall(
9912       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9913 }
9914
9915 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9916                                                    Value *Val, Value *Addr,
9917                                                    AtomicOrdering Ord) const {
9918   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9919   bool IsRelease = isAtLeastRelease(Ord);
9920
9921   // Since the intrinsics must have legal type, the i128 intrinsics take two
9922   // parameters: "i64, i64". We must marshal Val into the appropriate form
9923   // before the call.
9924   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9925     Intrinsic::ID Int =
9926         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9927     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9928     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9929
9930     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9931     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9932     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9933     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9934   }
9935
9936   Intrinsic::ID Int =
9937       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9938   Type *Tys[] = { Addr->getType() };
9939   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9940
9941   return Builder.CreateCall(Stxr,
9942                             {Builder.CreateZExtOrBitCast(
9943                                  Val, Stxr->getFunctionType()->getParamType(0)),
9944                              Addr});
9945 }
9946
9947 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9948     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9949   return Ty->isArrayTy();
9950 }
9951
9952 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9953                                                             EVT) const {
9954   return false;
9955 }