Remove templates from CostTableLookup functions. All instantiations had the same...
[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   for (MVT VT : MVT::vector_valuetypes()) {
224     setOperationAction(ISD::ROTL, VT, Expand);
225     setOperationAction(ISD::ROTR, VT, Expand);
226   }
227
228   // AArch64 doesn't have {U|S}MUL_LOHI.
229   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
230   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
231
232
233   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
234   // counterparts, which AArch64 supports directly.
235   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
236   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
237   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
238   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
239
240   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
241   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
242
243   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::SREM, MVT::i32, Expand);
246   setOperationAction(ISD::SREM, MVT::i64, Expand);
247   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
248   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
249   setOperationAction(ISD::UREM, MVT::i32, Expand);
250   setOperationAction(ISD::UREM, MVT::i64, Expand);
251
252   // Custom lower Add/Sub/Mul with overflow.
253   setOperationAction(ISD::SADDO, MVT::i32, Custom);
254   setOperationAction(ISD::SADDO, MVT::i64, Custom);
255   setOperationAction(ISD::UADDO, MVT::i32, Custom);
256   setOperationAction(ISD::UADDO, MVT::i64, Custom);
257   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
258   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
259   setOperationAction(ISD::USUBO, MVT::i32, Custom);
260   setOperationAction(ISD::USUBO, MVT::i64, Custom);
261   setOperationAction(ISD::SMULO, MVT::i32, Custom);
262   setOperationAction(ISD::SMULO, MVT::i64, Custom);
263   setOperationAction(ISD::UMULO, MVT::i32, Custom);
264   setOperationAction(ISD::UMULO, MVT::i64, Custom);
265
266   setOperationAction(ISD::FSIN, MVT::f32, Expand);
267   setOperationAction(ISD::FSIN, MVT::f64, Expand);
268   setOperationAction(ISD::FCOS, MVT::f32, Expand);
269   setOperationAction(ISD::FCOS, MVT::f64, Expand);
270   setOperationAction(ISD::FPOW, MVT::f32, Expand);
271   setOperationAction(ISD::FPOW, MVT::f64, Expand);
272   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
273   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
274
275   // f16 is a storage-only type, always promote it to f32.
276   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
277   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
278   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
279   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
280   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
281   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
282   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
283   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
284   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
285   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
286   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
287   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
288   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
289   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
290   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
291   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
292   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
293   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
294   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
295   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
296   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
297   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
298   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
299   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
300   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
301   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
302   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
303   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
304   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
305   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
306   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
307   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
308   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
309   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
310
311   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
312   // known to be safe.
313   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
314   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
315   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
316   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
317   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
318   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
319   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
321   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
322   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
323   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
324   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
325
326   // Expand all other v4f16 operations.
327   // FIXME: We could generate better code by promoting some operations to
328   // a pair of v4f32s
329   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
330   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
331   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
332   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
333   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
334   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
335   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
336   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
337   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
338   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
339   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
340   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
341   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
342   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
343   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
344   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
345   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
346   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
347   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
348   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
349   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
350   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
351   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
352   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
353   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
354   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
355
356
357   // v8f16 is also a storage-only type, so expand it.
358   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
359   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
360   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
361   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
362   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
363   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
364   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
365   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
366   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
367   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
368   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
369   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
370   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
371   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
372   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
373   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
374   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
375   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
376   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
377   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
378   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
379   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
380   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
381   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
382   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
383   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
384   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
385   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
386   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
387   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
388   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
389
390   // AArch64 has implementations of a lot of rounding-like FP operations.
391   for (MVT Ty : {MVT::f32, MVT::f64}) {
392     setOperationAction(ISD::FFLOOR, Ty, Legal);
393     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
394     setOperationAction(ISD::FCEIL, Ty, Legal);
395     setOperationAction(ISD::FRINT, Ty, Legal);
396     setOperationAction(ISD::FTRUNC, Ty, Legal);
397     setOperationAction(ISD::FROUND, Ty, Legal);
398     setOperationAction(ISD::FMINNUM, Ty, Legal);
399     setOperationAction(ISD::FMAXNUM, Ty, Legal);
400     setOperationAction(ISD::FMINNAN, Ty, Legal);
401     setOperationAction(ISD::FMAXNAN, Ty, Legal);
402   }
403
404   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
405
406   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
407   // This requires the Performance Monitors extension.
408   if (Subtarget->hasPerfMon())
409     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
410
411   if (Subtarget->isTargetMachO()) {
412     // For iOS, we don't want to the normal expansion of a libcall to
413     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
414     // traffic.
415     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
416     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
417   } else {
418     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
419     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
420   }
421
422   // Make floating-point constants legal for the large code model, so they don't
423   // become loads from the constant pool.
424   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
425     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
426     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
427   }
428
429   // AArch64 does not have floating-point extending loads, i1 sign-extending
430   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
431   for (MVT VT : MVT::fp_valuetypes()) {
432     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
433     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
434     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
435     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
436   }
437   for (MVT VT : MVT::integer_valuetypes())
438     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
439
440   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
441   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
443   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
444   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
445   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
446   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
447
448   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
449   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
450
451   // Indexed loads and stores are supported.
452   for (unsigned im = (unsigned)ISD::PRE_INC;
453        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
454     setIndexedLoadAction(im, MVT::i8, Legal);
455     setIndexedLoadAction(im, MVT::i16, Legal);
456     setIndexedLoadAction(im, MVT::i32, Legal);
457     setIndexedLoadAction(im, MVT::i64, Legal);
458     setIndexedLoadAction(im, MVT::f64, Legal);
459     setIndexedLoadAction(im, MVT::f32, Legal);
460     setIndexedLoadAction(im, MVT::f16, Legal);
461     setIndexedStoreAction(im, MVT::i8, Legal);
462     setIndexedStoreAction(im, MVT::i16, Legal);
463     setIndexedStoreAction(im, MVT::i32, Legal);
464     setIndexedStoreAction(im, MVT::i64, Legal);
465     setIndexedStoreAction(im, MVT::f64, Legal);
466     setIndexedStoreAction(im, MVT::f32, Legal);
467     setIndexedStoreAction(im, MVT::f16, Legal);
468   }
469
470   // Trap.
471   setOperationAction(ISD::TRAP, MVT::Other, Legal);
472
473   // We combine OR nodes for bitfield operations.
474   setTargetDAGCombine(ISD::OR);
475
476   // Vector add and sub nodes may conceal a high-half opportunity.
477   // Also, try to fold ADD into CSINC/CSINV..
478   setTargetDAGCombine(ISD::ADD);
479   setTargetDAGCombine(ISD::SUB);
480
481   setTargetDAGCombine(ISD::XOR);
482   setTargetDAGCombine(ISD::SINT_TO_FP);
483   setTargetDAGCombine(ISD::UINT_TO_FP);
484
485   setTargetDAGCombine(ISD::FP_TO_SINT);
486   setTargetDAGCombine(ISD::FP_TO_UINT);
487   setTargetDAGCombine(ISD::FDIV);
488
489   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
490
491   setTargetDAGCombine(ISD::ANY_EXTEND);
492   setTargetDAGCombine(ISD::ZERO_EXTEND);
493   setTargetDAGCombine(ISD::SIGN_EXTEND);
494   setTargetDAGCombine(ISD::BITCAST);
495   setTargetDAGCombine(ISD::CONCAT_VECTORS);
496   setTargetDAGCombine(ISD::STORE);
497
498   setTargetDAGCombine(ISD::MUL);
499
500   setTargetDAGCombine(ISD::SELECT);
501   setTargetDAGCombine(ISD::VSELECT);
502
503   setTargetDAGCombine(ISD::INTRINSIC_VOID);
504   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
505   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
506   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
507
508   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
509   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
510   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
511
512   setStackPointerRegisterToSaveRestore(AArch64::SP);
513
514   setSchedulingPreference(Sched::Hybrid);
515
516   // Enable TBZ/TBNZ
517   MaskAndBranchFoldingIsLegal = true;
518   EnableExtLdPromotion = true;
519
520   setMinFunctionAlignment(2);
521
522   setHasExtractBitsInsn(true);
523
524   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
525
526   if (Subtarget->hasNEON()) {
527     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528     // silliness like this:
529     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
554
555     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
560
561     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
562
563     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564     // elements smaller than i32, so promote the input to i32 first.
565     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
569     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570     // -> v8f16 conversions.
571     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
575     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
580     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
581     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
584
585     // AArch64 doesn't have MUL.2d:
586     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
587     // Custom handling for some quad-vector types to detect MULL.
588     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
589     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
590     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
591
592     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
593     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
594     // Likewise, narrowing and extending vector loads/stores aren't handled
595     // directly.
596     for (MVT VT : MVT::vector_valuetypes()) {
597       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
598
599       setOperationAction(ISD::MULHS, VT, Expand);
600       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
601       setOperationAction(ISD::MULHU, VT, Expand);
602       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
603
604       setOperationAction(ISD::BSWAP, VT, Expand);
605
606       for (MVT InnerVT : MVT::vector_valuetypes()) {
607         setTruncStoreAction(VT, InnerVT, Expand);
608         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
609         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
610         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
611       }
612     }
613
614     // AArch64 has implementations of a lot of rounding-like FP operations.
615     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
616       setOperationAction(ISD::FFLOOR, Ty, Legal);
617       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
618       setOperationAction(ISD::FCEIL, Ty, Legal);
619       setOperationAction(ISD::FRINT, Ty, Legal);
620       setOperationAction(ISD::FTRUNC, Ty, Legal);
621       setOperationAction(ISD::FROUND, Ty, Legal);
622     }
623   }
624
625   // Prefer likely predicted branches to selects on out-of-order cores.
626   if (Subtarget->isCortexA57())
627     PredictableSelectIsExpensive = true;
628 }
629
630 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
631   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
632     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
633     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
634
635     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
636     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
637   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
638     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
639     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
640
641     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
642     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
643   }
644
645   // Mark vector float intrinsics as expand.
646   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
647     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
652     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
653     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
654     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
655     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
656
657     // But we do support custom-lowering for FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
659   }
660
661   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
669   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
670   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
671   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
672   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
673
674   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
675   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
676   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
677   for (MVT InnerVT : MVT::all_valuetypes())
678     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
679
680   // CNT supports only B element sizes.
681   if (VT != MVT::v8i8 && VT != MVT::v16i8)
682     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
683
684   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
685   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
686   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
687   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
688   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
689
690   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
691   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
692
693   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
694   // i64.
695   if (!VT.isFloatingPoint() &&
696       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
697     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
698                             ISD::SABSDIFF, ISD::UABSDIFF})
699       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
700
701   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
702   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
703     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
704                             ISD::FMINNUM, ISD::FMAXNUM})
705       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
706
707   if (Subtarget->isLittleEndian()) {
708     for (unsigned im = (unsigned)ISD::PRE_INC;
709          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
710       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
711       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
712     }
713   }
714 }
715
716 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
717   addRegisterClass(VT, &AArch64::FPR64RegClass);
718   addTypeForNEON(VT, MVT::v2i32);
719 }
720
721 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
722   addRegisterClass(VT, &AArch64::FPR128RegClass);
723   addTypeForNEON(VT, MVT::v4i32);
724 }
725
726 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
727                                               EVT VT) const {
728   if (!VT.isVector())
729     return MVT::i32;
730   return VT.changeVectorElementTypeToInteger();
731 }
732
733 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
734 /// Mask are known to be either zero or one and return them in the
735 /// KnownZero/KnownOne bitsets.
736 void AArch64TargetLowering::computeKnownBitsForTargetNode(
737     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
738     const SelectionDAG &DAG, unsigned Depth) const {
739   switch (Op.getOpcode()) {
740   default:
741     break;
742   case AArch64ISD::CSEL: {
743     APInt KnownZero2, KnownOne2;
744     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
745     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
746     KnownZero &= KnownZero2;
747     KnownOne &= KnownOne2;
748     break;
749   }
750   case ISD::INTRINSIC_W_CHAIN: {
751     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
752     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
753     switch (IntID) {
754     default: return;
755     case Intrinsic::aarch64_ldaxr:
756     case Intrinsic::aarch64_ldxr: {
757       unsigned BitWidth = KnownOne.getBitWidth();
758       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
759       unsigned MemBits = VT.getScalarType().getSizeInBits();
760       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
761       return;
762     }
763     }
764     break;
765   }
766   case ISD::INTRINSIC_WO_CHAIN:
767   case ISD::INTRINSIC_VOID: {
768     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
769     switch (IntNo) {
770     default:
771       break;
772     case Intrinsic::aarch64_neon_umaxv:
773     case Intrinsic::aarch64_neon_uminv: {
774       // Figure out the datatype of the vector operand. The UMINV instruction
775       // will zero extend the result, so we can mark as known zero all the
776       // bits larger than the element datatype. 32-bit or larget doesn't need
777       // this as those are legal types and will be handled by isel directly.
778       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
779       unsigned BitWidth = KnownZero.getBitWidth();
780       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
781         assert(BitWidth >= 8 && "Unexpected width!");
782         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
783         KnownZero |= Mask;
784       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
785         assert(BitWidth >= 16 && "Unexpected width!");
786         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
787         KnownZero |= Mask;
788       }
789       break;
790     } break;
791     }
792   }
793   }
794 }
795
796 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
797                                                   EVT) const {
798   return MVT::i64;
799 }
800
801 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
802                                                            unsigned AddrSpace,
803                                                            unsigned Align,
804                                                            bool *Fast) const {
805   if (Subtarget->requiresStrictAlign())
806     return false;
807
808   // FIXME: This is mostly true for Cyclone, but not necessarily others.
809   if (Fast) {
810     // FIXME: Define an attribute for slow unaligned accesses instead of
811     // relying on the CPU type as a proxy.
812     // On Cyclone, unaligned 128-bit stores are slow.
813     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
814             // See comments in performSTORECombine() for more details about
815             // these conditions.
816
817             // Code that uses clang vector extensions can mark that it
818             // wants unaligned accesses to be treated as fast by
819             // underspecifying alignment to be 1 or 2.
820             Align <= 2 ||
821
822             // Disregard v2i64. Memcpy lowering produces those and splitting
823             // them regresses performance on micro-benchmarks and olden/bh.
824             VT == MVT::v2i64;
825   }
826   return true;
827 }
828
829 FastISel *
830 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
831                                       const TargetLibraryInfo *libInfo) const {
832   return AArch64::createFastISel(funcInfo, libInfo);
833 }
834
835 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
836   switch ((AArch64ISD::NodeType)Opcode) {
837   case AArch64ISD::FIRST_NUMBER:      break;
838   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
839   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
840   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
841   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
842   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
843   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
844   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
845   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
846   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
847   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
848   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
849   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
850   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
851   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
852   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
853   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
854   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
855   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
856   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
857   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
858   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
859   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
860   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
861   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
862   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
863   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
864   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
865   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
866   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
867   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
868   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
869   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
870   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
871   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
872   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
873   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
874   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
875   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
876   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
877   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
878   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
879   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
880   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
881   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
882   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
883   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
884   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
885   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
886   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
887   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
888   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
889   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
890   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
891   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
892   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
893   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
894   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
895   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
896   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
897   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
898   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
899   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
900   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
901   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
902   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
903   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
904   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
905   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
906   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
907   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
908   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
909   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
910   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
911   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
912   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
913   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
914   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
915   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
916   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
917   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
918   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
919   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
920   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
921   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
922   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
923   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
924   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
925   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
926   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
927   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
928   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
929   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
930   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
931   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
932   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
933   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
934   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
935   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
936   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
937   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
938   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
939   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
940   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
941   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
942   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
943   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
944   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
945   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
946   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
947   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
948   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
949   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
950   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
951   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
952   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
953   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
954   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
955   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
956   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
957   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
958   }
959   return nullptr;
960 }
961
962 MachineBasicBlock *
963 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
964                                     MachineBasicBlock *MBB) const {
965   // We materialise the F128CSEL pseudo-instruction as some control flow and a
966   // phi node:
967
968   // OrigBB:
969   //     [... previous instrs leading to comparison ...]
970   //     b.ne TrueBB
971   //     b EndBB
972   // TrueBB:
973   //     ; Fallthrough
974   // EndBB:
975   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
976
977   MachineFunction *MF = MBB->getParent();
978   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
979   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
980   DebugLoc DL = MI->getDebugLoc();
981   MachineFunction::iterator It = ++MBB->getIterator();
982
983   unsigned DestReg = MI->getOperand(0).getReg();
984   unsigned IfTrueReg = MI->getOperand(1).getReg();
985   unsigned IfFalseReg = MI->getOperand(2).getReg();
986   unsigned CondCode = MI->getOperand(3).getImm();
987   bool NZCVKilled = MI->getOperand(4).isKill();
988
989   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
990   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
991   MF->insert(It, TrueBB);
992   MF->insert(It, EndBB);
993
994   // Transfer rest of current basic-block to EndBB
995   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
996                 MBB->end());
997   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
998
999   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1000   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1001   MBB->addSuccessor(TrueBB);
1002   MBB->addSuccessor(EndBB);
1003
1004   // TrueBB falls through to the end.
1005   TrueBB->addSuccessor(EndBB);
1006
1007   if (!NZCVKilled) {
1008     TrueBB->addLiveIn(AArch64::NZCV);
1009     EndBB->addLiveIn(AArch64::NZCV);
1010   }
1011
1012   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1013       .addReg(IfTrueReg)
1014       .addMBB(TrueBB)
1015       .addReg(IfFalseReg)
1016       .addMBB(MBB);
1017
1018   MI->eraseFromParent();
1019   return EndBB;
1020 }
1021
1022 MachineBasicBlock *
1023 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1024                                                  MachineBasicBlock *BB) const {
1025   switch (MI->getOpcode()) {
1026   default:
1027 #ifndef NDEBUG
1028     MI->dump();
1029 #endif
1030     llvm_unreachable("Unexpected instruction for custom inserter!");
1031
1032   case AArch64::F128CSEL:
1033     return EmitF128CSEL(MI, BB);
1034
1035   case TargetOpcode::STACKMAP:
1036   case TargetOpcode::PATCHPOINT:
1037     return emitPatchPoint(MI, BB);
1038   }
1039 }
1040
1041 //===----------------------------------------------------------------------===//
1042 // AArch64 Lowering private implementation.
1043 //===----------------------------------------------------------------------===//
1044
1045 //===----------------------------------------------------------------------===//
1046 // Lowering Code
1047 //===----------------------------------------------------------------------===//
1048
1049 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1050 /// CC
1051 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1052   switch (CC) {
1053   default:
1054     llvm_unreachable("Unknown condition code!");
1055   case ISD::SETNE:
1056     return AArch64CC::NE;
1057   case ISD::SETEQ:
1058     return AArch64CC::EQ;
1059   case ISD::SETGT:
1060     return AArch64CC::GT;
1061   case ISD::SETGE:
1062     return AArch64CC::GE;
1063   case ISD::SETLT:
1064     return AArch64CC::LT;
1065   case ISD::SETLE:
1066     return AArch64CC::LE;
1067   case ISD::SETUGT:
1068     return AArch64CC::HI;
1069   case ISD::SETUGE:
1070     return AArch64CC::HS;
1071   case ISD::SETULT:
1072     return AArch64CC::LO;
1073   case ISD::SETULE:
1074     return AArch64CC::LS;
1075   }
1076 }
1077
1078 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1079 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1080                                   AArch64CC::CondCode &CondCode,
1081                                   AArch64CC::CondCode &CondCode2) {
1082   CondCode2 = AArch64CC::AL;
1083   switch (CC) {
1084   default:
1085     llvm_unreachable("Unknown FP condition!");
1086   case ISD::SETEQ:
1087   case ISD::SETOEQ:
1088     CondCode = AArch64CC::EQ;
1089     break;
1090   case ISD::SETGT:
1091   case ISD::SETOGT:
1092     CondCode = AArch64CC::GT;
1093     break;
1094   case ISD::SETGE:
1095   case ISD::SETOGE:
1096     CondCode = AArch64CC::GE;
1097     break;
1098   case ISD::SETOLT:
1099     CondCode = AArch64CC::MI;
1100     break;
1101   case ISD::SETOLE:
1102     CondCode = AArch64CC::LS;
1103     break;
1104   case ISD::SETONE:
1105     CondCode = AArch64CC::MI;
1106     CondCode2 = AArch64CC::GT;
1107     break;
1108   case ISD::SETO:
1109     CondCode = AArch64CC::VC;
1110     break;
1111   case ISD::SETUO:
1112     CondCode = AArch64CC::VS;
1113     break;
1114   case ISD::SETUEQ:
1115     CondCode = AArch64CC::EQ;
1116     CondCode2 = AArch64CC::VS;
1117     break;
1118   case ISD::SETUGT:
1119     CondCode = AArch64CC::HI;
1120     break;
1121   case ISD::SETUGE:
1122     CondCode = AArch64CC::PL;
1123     break;
1124   case ISD::SETLT:
1125   case ISD::SETULT:
1126     CondCode = AArch64CC::LT;
1127     break;
1128   case ISD::SETLE:
1129   case ISD::SETULE:
1130     CondCode = AArch64CC::LE;
1131     break;
1132   case ISD::SETNE:
1133   case ISD::SETUNE:
1134     CondCode = AArch64CC::NE;
1135     break;
1136   }
1137 }
1138
1139 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1140 /// CC usable with the vector instructions. Fewer operations are available
1141 /// without a real NZCV register, so we have to use less efficient combinations
1142 /// to get the same effect.
1143 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1144                                         AArch64CC::CondCode &CondCode,
1145                                         AArch64CC::CondCode &CondCode2,
1146                                         bool &Invert) {
1147   Invert = false;
1148   switch (CC) {
1149   default:
1150     // Mostly the scalar mappings work fine.
1151     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1152     break;
1153   case ISD::SETUO:
1154     Invert = true; // Fallthrough
1155   case ISD::SETO:
1156     CondCode = AArch64CC::MI;
1157     CondCode2 = AArch64CC::GE;
1158     break;
1159   case ISD::SETUEQ:
1160   case ISD::SETULT:
1161   case ISD::SETULE:
1162   case ISD::SETUGT:
1163   case ISD::SETUGE:
1164     // All of the compare-mask comparisons are ordered, but we can switch
1165     // between the two by a double inversion. E.g. ULE == !OGT.
1166     Invert = true;
1167     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1168     break;
1169   }
1170 }
1171
1172 static bool isLegalArithImmed(uint64_t C) {
1173   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1174   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1175 }
1176
1177 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1178                               SDLoc dl, SelectionDAG &DAG) {
1179   EVT VT = LHS.getValueType();
1180
1181   if (VT.isFloatingPoint())
1182     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1183
1184   // The CMP instruction is just an alias for SUBS, and representing it as
1185   // SUBS means that it's possible to get CSE with subtract operations.
1186   // A later phase can perform the optimization of setting the destination
1187   // register to WZR/XZR if it ends up being unused.
1188   unsigned Opcode = AArch64ISD::SUBS;
1189
1190   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1191       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1192       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1193     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1194     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1195     // can be set differently by this operation. It comes down to whether
1196     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1197     // everything is fine. If not then the optimization is wrong. Thus general
1198     // comparisons are only valid if op2 != 0.
1199
1200     // So, finally, the only LLVM-native comparisons that don't mention C and V
1201     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1202     // the absence of information about op2.
1203     Opcode = AArch64ISD::ADDS;
1204     RHS = RHS.getOperand(1);
1205   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1206              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1207              !isUnsignedIntSetCC(CC)) {
1208     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1209     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1210     // of the signed comparisons.
1211     Opcode = AArch64ISD::ANDS;
1212     RHS = LHS.getOperand(1);
1213     LHS = LHS.getOperand(0);
1214   }
1215
1216   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1217       .getValue(1);
1218 }
1219
1220 /// \defgroup AArch64CCMP CMP;CCMP matching
1221 ///
1222 /// These functions deal with the formation of CMP;CCMP;... sequences.
1223 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1224 /// a comparison. They set the NZCV flags to a predefined value if their
1225 /// predicate is false. This allows to express arbitrary conjunctions, for
1226 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1227 /// expressed as:
1228 ///   cmp A
1229 ///   ccmp B, inv(CB), CA
1230 ///   check for CB flags
1231 ///
1232 /// In general we can create code for arbitrary "... (and (and A B) C)"
1233 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1234 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1235 /// negation operations:
1236 /// We can negate the results of a single comparison by inverting the flags
1237 /// used when the predicate fails and inverting the flags tested in the next
1238 /// instruction; We can also negate the results of the whole previous
1239 /// conditional compare sequence by inverting the flags tested in the next
1240 /// instruction. However there is no way to negate the result of a partial
1241 /// sequence.
1242 ///
1243 /// Therefore on encountering an "or" expression we can negate the subtree on
1244 /// one side and have to be able to push the negate to the leafs of the subtree
1245 /// on the other side (see also the comments in code). As complete example:
1246 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1247 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1248 /// is transformed to
1249 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1250 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1251 /// and implemented as:
1252 ///   cmp C
1253 ///   ccmp D, inv(CD), CC
1254 ///   ccmp A, CA, inv(CD)
1255 ///   ccmp B, CB, inv(CA)
1256 ///   check for CB flags
1257 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1258 /// by conditional compare sequences.
1259 /// @{
1260
1261 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1262 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1263                                          ISD::CondCode CC, SDValue CCOp,
1264                                          SDValue Condition, unsigned NZCV,
1265                                          SDLoc DL, SelectionDAG &DAG) {
1266   unsigned Opcode = 0;
1267   if (LHS.getValueType().isFloatingPoint())
1268     Opcode = AArch64ISD::FCCMP;
1269   else if (RHS.getOpcode() == ISD::SUB) {
1270     SDValue SubOp0 = RHS.getOperand(0);
1271     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1272       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1273         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1274         Opcode = AArch64ISD::CCMN;
1275         RHS = RHS.getOperand(1);
1276       }
1277   }
1278   if (Opcode == 0)
1279     Opcode = AArch64ISD::CCMP;
1280
1281   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1282   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1283 }
1284
1285 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1286 /// CanPushNegate is set to true if we can push a negate operation through
1287 /// the tree in a was that we are left with AND operations and negate operations
1288 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1289 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1290 /// brought into such a form.
1291 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1292                                          unsigned Depth = 0) {
1293   if (!Val.hasOneUse())
1294     return false;
1295   unsigned Opcode = Val->getOpcode();
1296   if (Opcode == ISD::SETCC) {
1297     CanPushNegate = true;
1298     return true;
1299   }
1300   // Protect against stack overflow.
1301   if (Depth > 15)
1302     return false;
1303   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1304     SDValue O0 = Val->getOperand(0);
1305     SDValue O1 = Val->getOperand(1);
1306     bool CanPushNegateL;
1307     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1308       return false;
1309     bool CanPushNegateR;
1310     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1311       return false;
1312     // We cannot push a negate through an AND operation (it would become an OR),
1313     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1314     // push the negate through the x/y subtrees.
1315     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1316     return true;
1317   }
1318   return false;
1319 }
1320
1321 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1322 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1323 /// Tries to transform the given i1 producing node @p Val to a series compare
1324 /// and conditional compare operations. @returns an NZCV flags producing node
1325 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1326 /// transformation was not possible.
1327 /// On recursive invocations @p PushNegate may be set to true to have negation
1328 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1329 /// for the comparisons in the current subtree; @p Depth limits the search
1330 /// depth to avoid stack overflow.
1331 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1332     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1333     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1334     unsigned Depth = 0) {
1335   // We're at a tree leaf, produce a conditional comparison operation.
1336   unsigned Opcode = Val->getOpcode();
1337   if (Opcode == ISD::SETCC) {
1338     SDValue LHS = Val->getOperand(0);
1339     SDValue RHS = Val->getOperand(1);
1340     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1341     bool isInteger = LHS.getValueType().isInteger();
1342     if (PushNegate)
1343       CC = getSetCCInverse(CC, isInteger);
1344     SDLoc DL(Val);
1345     // Determine OutCC and handle FP special case.
1346     if (isInteger) {
1347       OutCC = changeIntCCToAArch64CC(CC);
1348     } else {
1349       assert(LHS.getValueType().isFloatingPoint());
1350       AArch64CC::CondCode ExtraCC;
1351       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1352       // Surpisingly some floating point conditions can't be tested with a
1353       // single condition code. Construct an additional comparison in this case.
1354       // See comment below on how we deal with OR conditions.
1355       if (ExtraCC != AArch64CC::AL) {
1356         SDValue ExtraCmp;
1357         if (!CCOp.getNode())
1358           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1359         else {
1360           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1361           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1362           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1363           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1364                                                NZCV, DL, DAG);
1365         }
1366         CCOp = ExtraCmp;
1367         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1368         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1369       }
1370     }
1371
1372     // Produce a normal comparison if we are first in the chain
1373     if (!CCOp.getNode())
1374       return emitComparison(LHS, RHS, CC, DL, DAG);
1375     // Otherwise produce a ccmp.
1376     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1377     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1378     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1379     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1380                                      DAG);
1381   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1382     return SDValue();
1383
1384   assert((Opcode == ISD::OR || !PushNegate)
1385          && "Can only push negate through OR operation");
1386
1387   // Check if both sides can be transformed.
1388   SDValue LHS = Val->getOperand(0);
1389   SDValue RHS = Val->getOperand(1);
1390   bool CanPushNegateL;
1391   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1392     return SDValue();
1393   bool CanPushNegateR;
1394   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1395     return SDValue();
1396
1397   // Do we need to negate our operands?
1398   bool NegateOperands = Opcode == ISD::OR;
1399   // We can negate the results of all previous operations by inverting the
1400   // predicate flags giving us a free negation for one side. For the other side
1401   // we need to be able to push the negation to the leafs of the tree.
1402   if (NegateOperands) {
1403     if (!CanPushNegateL && !CanPushNegateR)
1404       return SDValue();
1405     // Order the side where we can push the negate through to LHS.
1406     if (!CanPushNegateL && CanPushNegateR)
1407       std::swap(LHS, RHS);
1408   } else {
1409     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1410     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1411     if (NeedsNegOutL && NeedsNegOutR)
1412       return SDValue();
1413     // Order the side where we need to negate the output flags to RHS so it
1414     // gets emitted first.
1415     if (NeedsNegOutL)
1416       std::swap(LHS, RHS);
1417   }
1418
1419   // Emit RHS. If we want to negate the tree we only need to push a negate
1420   // through if we are already in a PushNegate case, otherwise we can negate
1421   // the "flags to test" afterwards.
1422   AArch64CC::CondCode RHSCC;
1423   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1424                                                 CCOp, Predicate, Depth+1);
1425   if (NegateOperands && !PushNegate)
1426     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1427   // Emit LHS. We must push the negate through if we need to negate it.
1428   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1429                                                 CmpR, RHSCC, Depth+1);
1430   // If we transformed an OR to and AND then we have to negate the result
1431   // (or absorb a PushNegate resulting in a double negation).
1432   if (Opcode == ISD::OR && !PushNegate)
1433     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1434   return CmpL;
1435 }
1436
1437 /// @}
1438
1439 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1440                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1441   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1442     EVT VT = RHS.getValueType();
1443     uint64_t C = RHSC->getZExtValue();
1444     if (!isLegalArithImmed(C)) {
1445       // Constant does not fit, try adjusting it by one?
1446       switch (CC) {
1447       default:
1448         break;
1449       case ISD::SETLT:
1450       case ISD::SETGE:
1451         if ((VT == MVT::i32 && C != 0x80000000 &&
1452              isLegalArithImmed((uint32_t)(C - 1))) ||
1453             (VT == MVT::i64 && C != 0x80000000ULL &&
1454              isLegalArithImmed(C - 1ULL))) {
1455           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1456           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1457           RHS = DAG.getConstant(C, dl, VT);
1458         }
1459         break;
1460       case ISD::SETULT:
1461       case ISD::SETUGE:
1462         if ((VT == MVT::i32 && C != 0 &&
1463              isLegalArithImmed((uint32_t)(C - 1))) ||
1464             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1465           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1466           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1467           RHS = DAG.getConstant(C, dl, VT);
1468         }
1469         break;
1470       case ISD::SETLE:
1471       case ISD::SETGT:
1472         if ((VT == MVT::i32 && C != INT32_MAX &&
1473              isLegalArithImmed((uint32_t)(C + 1))) ||
1474             (VT == MVT::i64 && C != INT64_MAX &&
1475              isLegalArithImmed(C + 1ULL))) {
1476           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1477           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1478           RHS = DAG.getConstant(C, dl, VT);
1479         }
1480         break;
1481       case ISD::SETULE:
1482       case ISD::SETUGT:
1483         if ((VT == MVT::i32 && C != UINT32_MAX &&
1484              isLegalArithImmed((uint32_t)(C + 1))) ||
1485             (VT == MVT::i64 && C != UINT64_MAX &&
1486              isLegalArithImmed(C + 1ULL))) {
1487           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1488           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1489           RHS = DAG.getConstant(C, dl, VT);
1490         }
1491         break;
1492       }
1493     }
1494   }
1495   SDValue Cmp;
1496   AArch64CC::CondCode AArch64CC;
1497   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1498     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1499
1500     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1501     // For the i8 operand, the largest immediate is 255, so this can be easily
1502     // encoded in the compare instruction. For the i16 operand, however, the
1503     // largest immediate cannot be encoded in the compare.
1504     // Therefore, use a sign extending load and cmn to avoid materializing the
1505     // -1 constant. For example,
1506     // movz w1, #65535
1507     // ldrh w0, [x0, #0]
1508     // cmp w0, w1
1509     // >
1510     // ldrsh w0, [x0, #0]
1511     // cmn w0, #1
1512     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1513     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1514     // ensure both the LHS and RHS are truly zero extended and to make sure the
1515     // transformation is profitable.
1516     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1517         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1518         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1519         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1520       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1521       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1522         SDValue SExt =
1523             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1524                         DAG.getValueType(MVT::i16));
1525         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1526                                                    RHS.getValueType()),
1527                              CC, dl, DAG);
1528         AArch64CC = changeIntCCToAArch64CC(CC);
1529       }
1530     }
1531
1532     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1533       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1534         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1535           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1536       }
1537     }
1538   }
1539
1540   if (!Cmp) {
1541     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1542     AArch64CC = changeIntCCToAArch64CC(CC);
1543   }
1544   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1545   return Cmp;
1546 }
1547
1548 static std::pair<SDValue, SDValue>
1549 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1550   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1551          "Unsupported value type");
1552   SDValue Value, Overflow;
1553   SDLoc DL(Op);
1554   SDValue LHS = Op.getOperand(0);
1555   SDValue RHS = Op.getOperand(1);
1556   unsigned Opc = 0;
1557   switch (Op.getOpcode()) {
1558   default:
1559     llvm_unreachable("Unknown overflow instruction!");
1560   case ISD::SADDO:
1561     Opc = AArch64ISD::ADDS;
1562     CC = AArch64CC::VS;
1563     break;
1564   case ISD::UADDO:
1565     Opc = AArch64ISD::ADDS;
1566     CC = AArch64CC::HS;
1567     break;
1568   case ISD::SSUBO:
1569     Opc = AArch64ISD::SUBS;
1570     CC = AArch64CC::VS;
1571     break;
1572   case ISD::USUBO:
1573     Opc = AArch64ISD::SUBS;
1574     CC = AArch64CC::LO;
1575     break;
1576   // Multiply needs a little bit extra work.
1577   case ISD::SMULO:
1578   case ISD::UMULO: {
1579     CC = AArch64CC::NE;
1580     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1581     if (Op.getValueType() == MVT::i32) {
1582       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1583       // For a 32 bit multiply with overflow check we want the instruction
1584       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1585       // need to generate the following pattern:
1586       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1587       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1588       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1589       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1590       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1591                                 DAG.getConstant(0, DL, MVT::i64));
1592       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1593       // operation. We need to clear out the upper 32 bits, because we used a
1594       // widening multiply that wrote all 64 bits. In the end this should be a
1595       // noop.
1596       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1597       if (IsSigned) {
1598         // The signed overflow check requires more than just a simple check for
1599         // any bit set in the upper 32 bits of the result. These bits could be
1600         // just the sign bits of a negative number. To perform the overflow
1601         // check we have to arithmetic shift right the 32nd bit of the result by
1602         // 31 bits. Then we compare the result to the upper 32 bits.
1603         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1604                                         DAG.getConstant(32, DL, MVT::i64));
1605         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1606         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1607                                         DAG.getConstant(31, DL, MVT::i64));
1608         // It is important that LowerBits is last, otherwise the arithmetic
1609         // shift will not be folded into the compare (SUBS).
1610         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1611         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1612                        .getValue(1);
1613       } else {
1614         // The overflow check for unsigned multiply is easy. We only need to
1615         // check if any of the upper 32 bits are set. This can be done with a
1616         // CMP (shifted register). For that we need to generate the following
1617         // pattern:
1618         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1619         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1620                                         DAG.getConstant(32, DL, MVT::i64));
1621         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1622         Overflow =
1623             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1624                         DAG.getConstant(0, DL, MVT::i64),
1625                         UpperBits).getValue(1);
1626       }
1627       break;
1628     }
1629     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1630     // For the 64 bit multiply
1631     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1632     if (IsSigned) {
1633       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1634       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1635                                       DAG.getConstant(63, DL, MVT::i64));
1636       // It is important that LowerBits is last, otherwise the arithmetic
1637       // shift will not be folded into the compare (SUBS).
1638       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1639       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1640                      .getValue(1);
1641     } else {
1642       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1643       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1644       Overflow =
1645           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1646                       DAG.getConstant(0, DL, MVT::i64),
1647                       UpperBits).getValue(1);
1648     }
1649     break;
1650   }
1651   } // switch (...)
1652
1653   if (Opc) {
1654     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1655
1656     // Emit the AArch64 operation with overflow check.
1657     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1658     Overflow = Value.getValue(1);
1659   }
1660   return std::make_pair(Value, Overflow);
1661 }
1662
1663 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1664                                              RTLIB::Libcall Call) const {
1665   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1666   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1667 }
1668
1669 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1670   SDValue Sel = Op.getOperand(0);
1671   SDValue Other = Op.getOperand(1);
1672
1673   // If neither operand is a SELECT_CC, give up.
1674   if (Sel.getOpcode() != ISD::SELECT_CC)
1675     std::swap(Sel, Other);
1676   if (Sel.getOpcode() != ISD::SELECT_CC)
1677     return Op;
1678
1679   // The folding we want to perform is:
1680   // (xor x, (select_cc a, b, cc, 0, -1) )
1681   //   -->
1682   // (csel x, (xor x, -1), cc ...)
1683   //
1684   // The latter will get matched to a CSINV instruction.
1685
1686   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1687   SDValue LHS = Sel.getOperand(0);
1688   SDValue RHS = Sel.getOperand(1);
1689   SDValue TVal = Sel.getOperand(2);
1690   SDValue FVal = Sel.getOperand(3);
1691   SDLoc dl(Sel);
1692
1693   // FIXME: This could be generalized to non-integer comparisons.
1694   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1695     return Op;
1696
1697   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1698   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1699
1700   // The values aren't constants, this isn't the pattern we're looking for.
1701   if (!CFVal || !CTVal)
1702     return Op;
1703
1704   // We can commute the SELECT_CC by inverting the condition.  This
1705   // might be needed to make this fit into a CSINV pattern.
1706   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1707     std::swap(TVal, FVal);
1708     std::swap(CTVal, CFVal);
1709     CC = ISD::getSetCCInverse(CC, true);
1710   }
1711
1712   // If the constants line up, perform the transform!
1713   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1714     SDValue CCVal;
1715     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1716
1717     FVal = Other;
1718     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1719                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1720
1721     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1722                        CCVal, Cmp);
1723   }
1724
1725   return Op;
1726 }
1727
1728 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1729   EVT VT = Op.getValueType();
1730
1731   // Let legalize expand this if it isn't a legal type yet.
1732   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1733     return SDValue();
1734
1735   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1736
1737   unsigned Opc;
1738   bool ExtraOp = false;
1739   switch (Op.getOpcode()) {
1740   default:
1741     llvm_unreachable("Invalid code");
1742   case ISD::ADDC:
1743     Opc = AArch64ISD::ADDS;
1744     break;
1745   case ISD::SUBC:
1746     Opc = AArch64ISD::SUBS;
1747     break;
1748   case ISD::ADDE:
1749     Opc = AArch64ISD::ADCS;
1750     ExtraOp = true;
1751     break;
1752   case ISD::SUBE:
1753     Opc = AArch64ISD::SBCS;
1754     ExtraOp = true;
1755     break;
1756   }
1757
1758   if (!ExtraOp)
1759     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1760   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1761                      Op.getOperand(2));
1762 }
1763
1764 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1765   // Let legalize expand this if it isn't a legal type yet.
1766   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1767     return SDValue();
1768
1769   SDLoc dl(Op);
1770   AArch64CC::CondCode CC;
1771   // The actual operation that sets the overflow or carry flag.
1772   SDValue Value, Overflow;
1773   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1774
1775   // We use 0 and 1 as false and true values.
1776   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1777   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1778
1779   // We use an inverted condition, because the conditional select is inverted
1780   // too. This will allow it to be selected to a single instruction:
1781   // CSINC Wd, WZR, WZR, invert(cond).
1782   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1783   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1784                          CCVal, Overflow);
1785
1786   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1787   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1788 }
1789
1790 // Prefetch operands are:
1791 // 1: Address to prefetch
1792 // 2: bool isWrite
1793 // 3: int locality (0 = no locality ... 3 = extreme locality)
1794 // 4: bool isDataCache
1795 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1796   SDLoc DL(Op);
1797   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1798   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1799   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1800
1801   bool IsStream = !Locality;
1802   // When the locality number is set
1803   if (Locality) {
1804     // The front-end should have filtered out the out-of-range values
1805     assert(Locality <= 3 && "Prefetch locality out-of-range");
1806     // The locality degree is the opposite of the cache speed.
1807     // Put the number the other way around.
1808     // The encoding starts at 0 for level 1
1809     Locality = 3 - Locality;
1810   }
1811
1812   // built the mask value encoding the expected behavior.
1813   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1814                    (!IsData << 3) |     // IsDataCache bit
1815                    (Locality << 1) |    // Cache level bits
1816                    (unsigned)IsStream;  // Stream bit
1817   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1818                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1819 }
1820
1821 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1822                                               SelectionDAG &DAG) const {
1823   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1824
1825   RTLIB::Libcall LC;
1826   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1827
1828   return LowerF128Call(Op, DAG, LC);
1829 }
1830
1831 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1832                                              SelectionDAG &DAG) const {
1833   if (Op.getOperand(0).getValueType() != MVT::f128) {
1834     // It's legal except when f128 is involved
1835     return Op;
1836   }
1837
1838   RTLIB::Libcall LC;
1839   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1840
1841   // FP_ROUND node has a second operand indicating whether it is known to be
1842   // precise. That doesn't take part in the LibCall so we can't directly use
1843   // LowerF128Call.
1844   SDValue SrcVal = Op.getOperand(0);
1845   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1846                      SDLoc(Op)).first;
1847 }
1848
1849 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1850   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1851   // Any additional optimization in this function should be recorded
1852   // in the cost tables.
1853   EVT InVT = Op.getOperand(0).getValueType();
1854   EVT VT = Op.getValueType();
1855
1856   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1857     SDLoc dl(Op);
1858     SDValue Cv =
1859         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1860                     Op.getOperand(0));
1861     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1862   }
1863
1864   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1865     SDLoc dl(Op);
1866     MVT ExtVT =
1867         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1868                          VT.getVectorNumElements());
1869     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1870     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1871   }
1872
1873   // Type changing conversions are illegal.
1874   return Op;
1875 }
1876
1877 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1878                                               SelectionDAG &DAG) const {
1879   if (Op.getOperand(0).getValueType().isVector())
1880     return LowerVectorFP_TO_INT(Op, DAG);
1881
1882   // f16 conversions are promoted to f32.
1883   if (Op.getOperand(0).getValueType() == MVT::f16) {
1884     SDLoc dl(Op);
1885     return DAG.getNode(
1886         Op.getOpcode(), dl, Op.getValueType(),
1887         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1888   }
1889
1890   if (Op.getOperand(0).getValueType() != MVT::f128) {
1891     // It's legal except when f128 is involved
1892     return Op;
1893   }
1894
1895   RTLIB::Libcall LC;
1896   if (Op.getOpcode() == ISD::FP_TO_SINT)
1897     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1898   else
1899     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1900
1901   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1902   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1903 }
1904
1905 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1906   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1907   // Any additional optimization in this function should be recorded
1908   // in the cost tables.
1909   EVT VT = Op.getValueType();
1910   SDLoc dl(Op);
1911   SDValue In = Op.getOperand(0);
1912   EVT InVT = In.getValueType();
1913
1914   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1915     MVT CastVT =
1916         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1917                          InVT.getVectorNumElements());
1918     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1919     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1920   }
1921
1922   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1923     unsigned CastOpc =
1924         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1925     EVT CastVT = VT.changeVectorElementTypeToInteger();
1926     In = DAG.getNode(CastOpc, dl, CastVT, In);
1927     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1928   }
1929
1930   return Op;
1931 }
1932
1933 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1934                                             SelectionDAG &DAG) const {
1935   if (Op.getValueType().isVector())
1936     return LowerVectorINT_TO_FP(Op, DAG);
1937
1938   // f16 conversions are promoted to f32.
1939   if (Op.getValueType() == MVT::f16) {
1940     SDLoc dl(Op);
1941     return DAG.getNode(
1942         ISD::FP_ROUND, dl, MVT::f16,
1943         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1944         DAG.getIntPtrConstant(0, dl));
1945   }
1946
1947   // i128 conversions are libcalls.
1948   if (Op.getOperand(0).getValueType() == MVT::i128)
1949     return SDValue();
1950
1951   // Other conversions are legal, unless it's to the completely software-based
1952   // fp128.
1953   if (Op.getValueType() != MVT::f128)
1954     return Op;
1955
1956   RTLIB::Libcall LC;
1957   if (Op.getOpcode() == ISD::SINT_TO_FP)
1958     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1959   else
1960     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1961
1962   return LowerF128Call(Op, DAG, LC);
1963 }
1964
1965 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1966                                             SelectionDAG &DAG) const {
1967   // For iOS, we want to call an alternative entry point: __sincos_stret,
1968   // which returns the values in two S / D registers.
1969   SDLoc dl(Op);
1970   SDValue Arg = Op.getOperand(0);
1971   EVT ArgVT = Arg.getValueType();
1972   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1973
1974   ArgListTy Args;
1975   ArgListEntry Entry;
1976
1977   Entry.Node = Arg;
1978   Entry.Ty = ArgTy;
1979   Entry.isSExt = false;
1980   Entry.isZExt = false;
1981   Args.push_back(Entry);
1982
1983   const char *LibcallName =
1984       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1985   SDValue Callee =
1986       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1987
1988   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1989   TargetLowering::CallLoweringInfo CLI(DAG);
1990   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1991     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1992
1993   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1994   return CallResult.first;
1995 }
1996
1997 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1998   if (Op.getValueType() != MVT::f16)
1999     return SDValue();
2000
2001   assert(Op.getOperand(0).getValueType() == MVT::i16);
2002   SDLoc DL(Op);
2003
2004   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2005   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2006   return SDValue(
2007       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2008                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2009       0);
2010 }
2011
2012 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2013   if (OrigVT.getSizeInBits() >= 64)
2014     return OrigVT;
2015
2016   assert(OrigVT.isSimple() && "Expecting a simple value type");
2017
2018   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2019   switch (OrigSimpleTy) {
2020   default: llvm_unreachable("Unexpected Vector Type");
2021   case MVT::v2i8:
2022   case MVT::v2i16:
2023      return MVT::v2i32;
2024   case MVT::v4i8:
2025     return  MVT::v4i16;
2026   }
2027 }
2028
2029 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2030                                                  const EVT &OrigTy,
2031                                                  const EVT &ExtTy,
2032                                                  unsigned ExtOpcode) {
2033   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2034   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2035   // 64-bits we need to insert a new extension so that it will be 64-bits.
2036   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2037   if (OrigTy.getSizeInBits() >= 64)
2038     return N;
2039
2040   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2041   EVT NewVT = getExtensionTo64Bits(OrigTy);
2042
2043   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2044 }
2045
2046 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2047                                    bool isSigned) {
2048   EVT VT = N->getValueType(0);
2049
2050   if (N->getOpcode() != ISD::BUILD_VECTOR)
2051     return false;
2052
2053   for (const SDValue &Elt : N->op_values()) {
2054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2055       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2056       unsigned HalfSize = EltSize / 2;
2057       if (isSigned) {
2058         if (!isIntN(HalfSize, C->getSExtValue()))
2059           return false;
2060       } else {
2061         if (!isUIntN(HalfSize, C->getZExtValue()))
2062           return false;
2063       }
2064       continue;
2065     }
2066     return false;
2067   }
2068
2069   return true;
2070 }
2071
2072 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2073   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2074     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2075                                              N->getOperand(0)->getValueType(0),
2076                                              N->getValueType(0),
2077                                              N->getOpcode());
2078
2079   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2080   EVT VT = N->getValueType(0);
2081   SDLoc dl(N);
2082   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2083   unsigned NumElts = VT.getVectorNumElements();
2084   MVT TruncVT = MVT::getIntegerVT(EltSize);
2085   SmallVector<SDValue, 8> Ops;
2086   for (unsigned i = 0; i != NumElts; ++i) {
2087     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2088     const APInt &CInt = C->getAPIntValue();
2089     // Element types smaller than 32 bits are not legal, so use i32 elements.
2090     // The values are implicitly truncated so sext vs. zext doesn't matter.
2091     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2092   }
2093   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2094                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2095 }
2096
2097 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2098   if (N->getOpcode() == ISD::SIGN_EXTEND)
2099     return true;
2100   if (isExtendedBUILD_VECTOR(N, DAG, true))
2101     return true;
2102   return false;
2103 }
2104
2105 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2106   if (N->getOpcode() == ISD::ZERO_EXTEND)
2107     return true;
2108   if (isExtendedBUILD_VECTOR(N, DAG, false))
2109     return true;
2110   return false;
2111 }
2112
2113 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2114   unsigned Opcode = N->getOpcode();
2115   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2116     SDNode *N0 = N->getOperand(0).getNode();
2117     SDNode *N1 = N->getOperand(1).getNode();
2118     return N0->hasOneUse() && N1->hasOneUse() &&
2119       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2120   }
2121   return false;
2122 }
2123
2124 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2125   unsigned Opcode = N->getOpcode();
2126   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2127     SDNode *N0 = N->getOperand(0).getNode();
2128     SDNode *N1 = N->getOperand(1).getNode();
2129     return N0->hasOneUse() && N1->hasOneUse() &&
2130       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2131   }
2132   return false;
2133 }
2134
2135 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2136   // Multiplications are only custom-lowered for 128-bit vectors so that
2137   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2138   EVT VT = Op.getValueType();
2139   assert(VT.is128BitVector() && VT.isInteger() &&
2140          "unexpected type for custom-lowering ISD::MUL");
2141   SDNode *N0 = Op.getOperand(0).getNode();
2142   SDNode *N1 = Op.getOperand(1).getNode();
2143   unsigned NewOpc = 0;
2144   bool isMLA = false;
2145   bool isN0SExt = isSignExtended(N0, DAG);
2146   bool isN1SExt = isSignExtended(N1, DAG);
2147   if (isN0SExt && isN1SExt)
2148     NewOpc = AArch64ISD::SMULL;
2149   else {
2150     bool isN0ZExt = isZeroExtended(N0, DAG);
2151     bool isN1ZExt = isZeroExtended(N1, DAG);
2152     if (isN0ZExt && isN1ZExt)
2153       NewOpc = AArch64ISD::UMULL;
2154     else if (isN1SExt || isN1ZExt) {
2155       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2156       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2157       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2158         NewOpc = AArch64ISD::SMULL;
2159         isMLA = true;
2160       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2161         NewOpc =  AArch64ISD::UMULL;
2162         isMLA = true;
2163       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2164         std::swap(N0, N1);
2165         NewOpc =  AArch64ISD::UMULL;
2166         isMLA = true;
2167       }
2168     }
2169
2170     if (!NewOpc) {
2171       if (VT == MVT::v2i64)
2172         // Fall through to expand this.  It is not legal.
2173         return SDValue();
2174       else
2175         // Other vector multiplications are legal.
2176         return Op;
2177     }
2178   }
2179
2180   // Legalize to a S/UMULL instruction
2181   SDLoc DL(Op);
2182   SDValue Op0;
2183   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2184   if (!isMLA) {
2185     Op0 = skipExtensionForVectorMULL(N0, DAG);
2186     assert(Op0.getValueType().is64BitVector() &&
2187            Op1.getValueType().is64BitVector() &&
2188            "unexpected types for extended operands to VMULL");
2189     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2190   }
2191   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2192   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2193   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2194   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2195   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2196   EVT Op1VT = Op1.getValueType();
2197   return DAG.getNode(N0->getOpcode(), DL, VT,
2198                      DAG.getNode(NewOpc, DL, VT,
2199                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2200                      DAG.getNode(NewOpc, DL, VT,
2201                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2202 }
2203
2204 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2205                                                      SelectionDAG &DAG) const {
2206   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2207   SDLoc dl(Op);
2208   switch (IntNo) {
2209   default: return SDValue();    // Don't custom lower most intrinsics.
2210   case Intrinsic::aarch64_thread_pointer: {
2211     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2212     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2213   }
2214   case Intrinsic::aarch64_neon_smax:
2215     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2216                        Op.getOperand(1), Op.getOperand(2));
2217   case Intrinsic::aarch64_neon_umax:
2218     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2219                        Op.getOperand(1), Op.getOperand(2));
2220   case Intrinsic::aarch64_neon_smin:
2221     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2222                        Op.getOperand(1), Op.getOperand(2));
2223   case Intrinsic::aarch64_neon_umin:
2224     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2225                        Op.getOperand(1), Op.getOperand(2));
2226   }
2227 }
2228
2229 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2230                                               SelectionDAG &DAG) const {
2231   switch (Op.getOpcode()) {
2232   default:
2233     llvm_unreachable("unimplemented operand");
2234     return SDValue();
2235   case ISD::BITCAST:
2236     return LowerBITCAST(Op, DAG);
2237   case ISD::GlobalAddress:
2238     return LowerGlobalAddress(Op, DAG);
2239   case ISD::GlobalTLSAddress:
2240     return LowerGlobalTLSAddress(Op, DAG);
2241   case ISD::SETCC:
2242     return LowerSETCC(Op, DAG);
2243   case ISD::BR_CC:
2244     return LowerBR_CC(Op, DAG);
2245   case ISD::SELECT:
2246     return LowerSELECT(Op, DAG);
2247   case ISD::SELECT_CC:
2248     return LowerSELECT_CC(Op, DAG);
2249   case ISD::JumpTable:
2250     return LowerJumpTable(Op, DAG);
2251   case ISD::ConstantPool:
2252     return LowerConstantPool(Op, DAG);
2253   case ISD::BlockAddress:
2254     return LowerBlockAddress(Op, DAG);
2255   case ISD::VASTART:
2256     return LowerVASTART(Op, DAG);
2257   case ISD::VACOPY:
2258     return LowerVACOPY(Op, DAG);
2259   case ISD::VAARG:
2260     return LowerVAARG(Op, DAG);
2261   case ISD::ADDC:
2262   case ISD::ADDE:
2263   case ISD::SUBC:
2264   case ISD::SUBE:
2265     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2266   case ISD::SADDO:
2267   case ISD::UADDO:
2268   case ISD::SSUBO:
2269   case ISD::USUBO:
2270   case ISD::SMULO:
2271   case ISD::UMULO:
2272     return LowerXALUO(Op, DAG);
2273   case ISD::FADD:
2274     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2275   case ISD::FSUB:
2276     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2277   case ISD::FMUL:
2278     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2279   case ISD::FDIV:
2280     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2281   case ISD::FP_ROUND:
2282     return LowerFP_ROUND(Op, DAG);
2283   case ISD::FP_EXTEND:
2284     return LowerFP_EXTEND(Op, DAG);
2285   case ISD::FRAMEADDR:
2286     return LowerFRAMEADDR(Op, DAG);
2287   case ISD::RETURNADDR:
2288     return LowerRETURNADDR(Op, DAG);
2289   case ISD::INSERT_VECTOR_ELT:
2290     return LowerINSERT_VECTOR_ELT(Op, DAG);
2291   case ISD::EXTRACT_VECTOR_ELT:
2292     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2293   case ISD::BUILD_VECTOR:
2294     return LowerBUILD_VECTOR(Op, DAG);
2295   case ISD::VECTOR_SHUFFLE:
2296     return LowerVECTOR_SHUFFLE(Op, DAG);
2297   case ISD::EXTRACT_SUBVECTOR:
2298     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2299   case ISD::SRA:
2300   case ISD::SRL:
2301   case ISD::SHL:
2302     return LowerVectorSRA_SRL_SHL(Op, DAG);
2303   case ISD::SHL_PARTS:
2304     return LowerShiftLeftParts(Op, DAG);
2305   case ISD::SRL_PARTS:
2306   case ISD::SRA_PARTS:
2307     return LowerShiftRightParts(Op, DAG);
2308   case ISD::CTPOP:
2309     return LowerCTPOP(Op, DAG);
2310   case ISD::FCOPYSIGN:
2311     return LowerFCOPYSIGN(Op, DAG);
2312   case ISD::AND:
2313     return LowerVectorAND(Op, DAG);
2314   case ISD::OR:
2315     return LowerVectorOR(Op, DAG);
2316   case ISD::XOR:
2317     return LowerXOR(Op, DAG);
2318   case ISD::PREFETCH:
2319     return LowerPREFETCH(Op, DAG);
2320   case ISD::SINT_TO_FP:
2321   case ISD::UINT_TO_FP:
2322     return LowerINT_TO_FP(Op, DAG);
2323   case ISD::FP_TO_SINT:
2324   case ISD::FP_TO_UINT:
2325     return LowerFP_TO_INT(Op, DAG);
2326   case ISD::FSINCOS:
2327     return LowerFSINCOS(Op, DAG);
2328   case ISD::MUL:
2329     return LowerMUL(Op, DAG);
2330   case ISD::INTRINSIC_WO_CHAIN:
2331     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2332   }
2333 }
2334
2335 /// getFunctionAlignment - Return the Log2 alignment of this function.
2336 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2337   return 2;
2338 }
2339
2340 //===----------------------------------------------------------------------===//
2341 //                      Calling Convention Implementation
2342 //===----------------------------------------------------------------------===//
2343
2344 #include "AArch64GenCallingConv.inc"
2345
2346 /// Selects the correct CCAssignFn for a given CallingConvention value.
2347 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2348                                                      bool IsVarArg) const {
2349   switch (CC) {
2350   default:
2351     llvm_unreachable("Unsupported calling convention.");
2352   case CallingConv::WebKit_JS:
2353     return CC_AArch64_WebKit_JS;
2354   case CallingConv::GHC:
2355     return CC_AArch64_GHC;
2356   case CallingConv::C:
2357   case CallingConv::Fast:
2358     if (!Subtarget->isTargetDarwin())
2359       return CC_AArch64_AAPCS;
2360     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2361   }
2362 }
2363
2364 SDValue AArch64TargetLowering::LowerFormalArguments(
2365     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2366     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2367     SmallVectorImpl<SDValue> &InVals) const {
2368   MachineFunction &MF = DAG.getMachineFunction();
2369   MachineFrameInfo *MFI = MF.getFrameInfo();
2370
2371   // Assign locations to all of the incoming arguments.
2372   SmallVector<CCValAssign, 16> ArgLocs;
2373   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2374                  *DAG.getContext());
2375
2376   // At this point, Ins[].VT may already be promoted to i32. To correctly
2377   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2378   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2379   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2380   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2381   // LocVT.
2382   unsigned NumArgs = Ins.size();
2383   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2384   unsigned CurArgIdx = 0;
2385   for (unsigned i = 0; i != NumArgs; ++i) {
2386     MVT ValVT = Ins[i].VT;
2387     if (Ins[i].isOrigArg()) {
2388       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2389       CurArgIdx = Ins[i].getOrigArgIndex();
2390
2391       // Get type of the original argument.
2392       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2393                                   /*AllowUnknown*/ true);
2394       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2395       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2396       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2397         ValVT = MVT::i8;
2398       else if (ActualMVT == MVT::i16)
2399         ValVT = MVT::i16;
2400     }
2401     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2402     bool Res =
2403         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2404     assert(!Res && "Call operand has unhandled type");
2405     (void)Res;
2406   }
2407   assert(ArgLocs.size() == Ins.size());
2408   SmallVector<SDValue, 16> ArgValues;
2409   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410     CCValAssign &VA = ArgLocs[i];
2411
2412     if (Ins[i].Flags.isByVal()) {
2413       // Byval is used for HFAs in the PCS, but the system should work in a
2414       // non-compliant manner for larger structs.
2415       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2416       int Size = Ins[i].Flags.getByValSize();
2417       unsigned NumRegs = (Size + 7) / 8;
2418
2419       // FIXME: This works on big-endian for composite byvals, which are the common
2420       // case. It should also work for fundamental types too.
2421       unsigned FrameIdx =
2422         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2423       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2424       InVals.push_back(FrameIdxN);
2425
2426       continue;
2427     }
2428     
2429     if (VA.isRegLoc()) {
2430       // Arguments stored in registers.
2431       EVT RegVT = VA.getLocVT();
2432
2433       SDValue ArgValue;
2434       const TargetRegisterClass *RC;
2435
2436       if (RegVT == MVT::i32)
2437         RC = &AArch64::GPR32RegClass;
2438       else if (RegVT == MVT::i64)
2439         RC = &AArch64::GPR64RegClass;
2440       else if (RegVT == MVT::f16)
2441         RC = &AArch64::FPR16RegClass;
2442       else if (RegVT == MVT::f32)
2443         RC = &AArch64::FPR32RegClass;
2444       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2445         RC = &AArch64::FPR64RegClass;
2446       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2447         RC = &AArch64::FPR128RegClass;
2448       else
2449         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2450
2451       // Transform the arguments in physical registers into virtual ones.
2452       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2453       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2454
2455       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2456       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2457       // truncate to the right size.
2458       switch (VA.getLocInfo()) {
2459       default:
2460         llvm_unreachable("Unknown loc info!");
2461       case CCValAssign::Full:
2462         break;
2463       case CCValAssign::BCvt:
2464         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2465         break;
2466       case CCValAssign::AExt:
2467       case CCValAssign::SExt:
2468       case CCValAssign::ZExt:
2469         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2470         // nodes after our lowering.
2471         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2472         break;
2473       }
2474
2475       InVals.push_back(ArgValue);
2476
2477     } else { // VA.isRegLoc()
2478       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2479       unsigned ArgOffset = VA.getLocMemOffset();
2480       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2481
2482       uint32_t BEAlign = 0;
2483       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2484           !Ins[i].Flags.isInConsecutiveRegs())
2485         BEAlign = 8 - ArgSize;
2486
2487       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2488
2489       // Create load nodes to retrieve arguments from the stack.
2490       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2491       SDValue ArgValue;
2492
2493       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2494       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2495       MVT MemVT = VA.getValVT();
2496
2497       switch (VA.getLocInfo()) {
2498       default:
2499         break;
2500       case CCValAssign::BCvt:
2501         MemVT = VA.getLocVT();
2502         break;
2503       case CCValAssign::SExt:
2504         ExtType = ISD::SEXTLOAD;
2505         break;
2506       case CCValAssign::ZExt:
2507         ExtType = ISD::ZEXTLOAD;
2508         break;
2509       case CCValAssign::AExt:
2510         ExtType = ISD::EXTLOAD;
2511         break;
2512       }
2513
2514       ArgValue = DAG.getExtLoad(
2515           ExtType, DL, VA.getLocVT(), Chain, FIN,
2516           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2517           MemVT, false, false, false, 0);
2518
2519       InVals.push_back(ArgValue);
2520     }
2521   }
2522
2523   // varargs
2524   if (isVarArg) {
2525     if (!Subtarget->isTargetDarwin()) {
2526       // The AAPCS variadic function ABI is identical to the non-variadic
2527       // one. As a result there may be more arguments in registers and we should
2528       // save them for future reference.
2529       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2530     }
2531
2532     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2533     // This will point to the next argument passed via stack.
2534     unsigned StackOffset = CCInfo.getNextStackOffset();
2535     // We currently pass all varargs at 8-byte alignment.
2536     StackOffset = ((StackOffset + 7) & ~7);
2537     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2538   }
2539
2540   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2541   unsigned StackArgSize = CCInfo.getNextStackOffset();
2542   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2543   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2544     // This is a non-standard ABI so by fiat I say we're allowed to make full
2545     // use of the stack area to be popped, which must be aligned to 16 bytes in
2546     // any case:
2547     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2548
2549     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2550     // a multiple of 16.
2551     FuncInfo->setArgumentStackToRestore(StackArgSize);
2552
2553     // This realignment carries over to the available bytes below. Our own
2554     // callers will guarantee the space is free by giving an aligned value to
2555     // CALLSEQ_START.
2556   }
2557   // Even if we're not expected to free up the space, it's useful to know how
2558   // much is there while considering tail calls (because we can reuse it).
2559   FuncInfo->setBytesInStackArgArea(StackArgSize);
2560
2561   return Chain;
2562 }
2563
2564 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2565                                                 SelectionDAG &DAG, SDLoc DL,
2566                                                 SDValue &Chain) const {
2567   MachineFunction &MF = DAG.getMachineFunction();
2568   MachineFrameInfo *MFI = MF.getFrameInfo();
2569   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2570   auto PtrVT = getPointerTy(DAG.getDataLayout());
2571
2572   SmallVector<SDValue, 8> MemOps;
2573
2574   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2575                                           AArch64::X3, AArch64::X4, AArch64::X5,
2576                                           AArch64::X6, AArch64::X7 };
2577   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2578   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2579
2580   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2581   int GPRIdx = 0;
2582   if (GPRSaveSize != 0) {
2583     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2584
2585     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2586
2587     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2588       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2589       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2590       SDValue Store = DAG.getStore(
2591           Val.getValue(1), DL, Val, FIN,
2592           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2593           false, 0);
2594       MemOps.push_back(Store);
2595       FIN =
2596           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2597     }
2598   }
2599   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2600   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2601
2602   if (Subtarget->hasFPARMv8()) {
2603     static const MCPhysReg FPRArgRegs[] = {
2604         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2605         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2606     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2607     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2608
2609     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2610     int FPRIdx = 0;
2611     if (FPRSaveSize != 0) {
2612       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2613
2614       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2615
2616       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2617         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2618         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2619
2620         SDValue Store = DAG.getStore(
2621             Val.getValue(1), DL, Val, FIN,
2622             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2623             false, false, 0);
2624         MemOps.push_back(Store);
2625         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2626                           DAG.getConstant(16, DL, PtrVT));
2627       }
2628     }
2629     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2630     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2631   }
2632
2633   if (!MemOps.empty()) {
2634     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2635   }
2636 }
2637
2638 /// LowerCallResult - Lower the result values of a call into the
2639 /// appropriate copies out of appropriate physical registers.
2640 SDValue AArch64TargetLowering::LowerCallResult(
2641     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2642     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2643     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2644     SDValue ThisVal) const {
2645   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2646                           ? RetCC_AArch64_WebKit_JS
2647                           : RetCC_AArch64_AAPCS;
2648   // Assign locations to each value returned by this call.
2649   SmallVector<CCValAssign, 16> RVLocs;
2650   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2651                  *DAG.getContext());
2652   CCInfo.AnalyzeCallResult(Ins, RetCC);
2653
2654   // Copy all of the result registers out of their specified physreg.
2655   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2656     CCValAssign VA = RVLocs[i];
2657
2658     // Pass 'this' value directly from the argument to return value, to avoid
2659     // reg unit interference
2660     if (i == 0 && isThisReturn) {
2661       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2662              "unexpected return calling convention register assignment");
2663       InVals.push_back(ThisVal);
2664       continue;
2665     }
2666
2667     SDValue Val =
2668         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2669     Chain = Val.getValue(1);
2670     InFlag = Val.getValue(2);
2671
2672     switch (VA.getLocInfo()) {
2673     default:
2674       llvm_unreachable("Unknown loc info!");
2675     case CCValAssign::Full:
2676       break;
2677     case CCValAssign::BCvt:
2678       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2679       break;
2680     }
2681
2682     InVals.push_back(Val);
2683   }
2684
2685   return Chain;
2686 }
2687
2688 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2689     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2690     bool isCalleeStructRet, bool isCallerStructRet,
2691     const SmallVectorImpl<ISD::OutputArg> &Outs,
2692     const SmallVectorImpl<SDValue> &OutVals,
2693     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2694   // For CallingConv::C this function knows whether the ABI needs
2695   // changing. That's not true for other conventions so they will have to opt in
2696   // manually.
2697   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2698     return false;
2699
2700   const MachineFunction &MF = DAG.getMachineFunction();
2701   const Function *CallerF = MF.getFunction();
2702   CallingConv::ID CallerCC = CallerF->getCallingConv();
2703   bool CCMatch = CallerCC == CalleeCC;
2704
2705   // Byval parameters hand the function a pointer directly into the stack area
2706   // we want to reuse during a tail call. Working around this *is* possible (see
2707   // X86) but less efficient and uglier in LowerCall.
2708   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2709                                     e = CallerF->arg_end();
2710        i != e; ++i)
2711     if (i->hasByValAttr())
2712       return false;
2713
2714   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2715     if (IsTailCallConvention(CalleeCC) && CCMatch)
2716       return true;
2717     return false;
2718   }
2719
2720   // Externally-defined functions with weak linkage should not be
2721   // tail-called on AArch64 when the OS does not support dynamic
2722   // pre-emption of symbols, as the AAELF spec requires normal calls
2723   // to undefined weak functions to be replaced with a NOP or jump to the
2724   // next instruction. The behaviour of branch instructions in this
2725   // situation (as used for tail calls) is implementation-defined, so we
2726   // cannot rely on the linker replacing the tail call with a return.
2727   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2728     const GlobalValue *GV = G->getGlobal();
2729     const Triple &TT = getTargetMachine().getTargetTriple();
2730     if (GV->hasExternalWeakLinkage() &&
2731         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2732       return false;
2733   }
2734
2735   // Now we search for cases where we can use a tail call without changing the
2736   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2737   // concept.
2738
2739   // I want anyone implementing a new calling convention to think long and hard
2740   // about this assert.
2741   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2742          "Unexpected variadic calling convention");
2743
2744   if (isVarArg && !Outs.empty()) {
2745     // At least two cases here: if caller is fastcc then we can't have any
2746     // memory arguments (we'd be expected to clean up the stack afterwards). If
2747     // caller is C then we could potentially use its argument area.
2748
2749     // FIXME: for now we take the most conservative of these in both cases:
2750     // disallow all variadic memory operands.
2751     SmallVector<CCValAssign, 16> ArgLocs;
2752     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2753                    *DAG.getContext());
2754
2755     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2756     for (const CCValAssign &ArgLoc : ArgLocs)
2757       if (!ArgLoc.isRegLoc())
2758         return false;
2759   }
2760
2761   // If the calling conventions do not match, then we'd better make sure the
2762   // results are returned in the same way as what the caller expects.
2763   if (!CCMatch) {
2764     SmallVector<CCValAssign, 16> RVLocs1;
2765     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2766                     *DAG.getContext());
2767     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2768
2769     SmallVector<CCValAssign, 16> RVLocs2;
2770     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2771                     *DAG.getContext());
2772     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2773
2774     if (RVLocs1.size() != RVLocs2.size())
2775       return false;
2776     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2777       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2778         return false;
2779       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2780         return false;
2781       if (RVLocs1[i].isRegLoc()) {
2782         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2783           return false;
2784       } else {
2785         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2786           return false;
2787       }
2788     }
2789   }
2790
2791   // Nothing more to check if the callee is taking no arguments
2792   if (Outs.empty())
2793     return true;
2794
2795   SmallVector<CCValAssign, 16> ArgLocs;
2796   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2797                  *DAG.getContext());
2798
2799   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2800
2801   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2802
2803   // If the stack arguments for this call would fit into our own save area then
2804   // the call can be made tail.
2805   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2806 }
2807
2808 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2809                                                    SelectionDAG &DAG,
2810                                                    MachineFrameInfo *MFI,
2811                                                    int ClobberedFI) const {
2812   SmallVector<SDValue, 8> ArgChains;
2813   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2814   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2815
2816   // Include the original chain at the beginning of the list. When this is
2817   // used by target LowerCall hooks, this helps legalize find the
2818   // CALLSEQ_BEGIN node.
2819   ArgChains.push_back(Chain);
2820
2821   // Add a chain value for each stack argument corresponding
2822   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2823                             UE = DAG.getEntryNode().getNode()->use_end();
2824        U != UE; ++U)
2825     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2826       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2827         if (FI->getIndex() < 0) {
2828           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2829           int64_t InLastByte = InFirstByte;
2830           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2831
2832           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2833               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2834             ArgChains.push_back(SDValue(L, 1));
2835         }
2836
2837   // Build a tokenfactor for all the chains.
2838   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2839 }
2840
2841 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2842                                                    bool TailCallOpt) const {
2843   return CallCC == CallingConv::Fast && TailCallOpt;
2844 }
2845
2846 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2847   return CallCC == CallingConv::Fast;
2848 }
2849
2850 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2851 /// and add input and output parameter nodes.
2852 SDValue
2853 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2854                                  SmallVectorImpl<SDValue> &InVals) const {
2855   SelectionDAG &DAG = CLI.DAG;
2856   SDLoc &DL = CLI.DL;
2857   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2858   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2859   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2860   SDValue Chain = CLI.Chain;
2861   SDValue Callee = CLI.Callee;
2862   bool &IsTailCall = CLI.IsTailCall;
2863   CallingConv::ID CallConv = CLI.CallConv;
2864   bool IsVarArg = CLI.IsVarArg;
2865
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2868   bool IsThisReturn = false;
2869
2870   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2871   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2872   bool IsSibCall = false;
2873
2874   if (IsTailCall) {
2875     // Check if it's really possible to do a tail call.
2876     IsTailCall = isEligibleForTailCallOptimization(
2877         Callee, CallConv, IsVarArg, IsStructRet,
2878         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2879     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2880       report_fatal_error("failed to perform tail call elimination on a call "
2881                          "site marked musttail");
2882
2883     // A sibling call is one where we're under the usual C ABI and not planning
2884     // to change that but can still do a tail call:
2885     if (!TailCallOpt && IsTailCall)
2886       IsSibCall = true;
2887
2888     if (IsTailCall)
2889       ++NumTailCalls;
2890   }
2891
2892   // Analyze operands of the call, assigning locations to each operand.
2893   SmallVector<CCValAssign, 16> ArgLocs;
2894   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2895                  *DAG.getContext());
2896
2897   if (IsVarArg) {
2898     // Handle fixed and variable vector arguments differently.
2899     // Variable vector arguments always go into memory.
2900     unsigned NumArgs = Outs.size();
2901
2902     for (unsigned i = 0; i != NumArgs; ++i) {
2903       MVT ArgVT = Outs[i].VT;
2904       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2905       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2906                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2907       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2908       assert(!Res && "Call operand has unhandled type");
2909       (void)Res;
2910     }
2911   } else {
2912     // At this point, Outs[].VT may already be promoted to i32. To correctly
2913     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2914     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2915     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2916     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2917     // LocVT.
2918     unsigned NumArgs = Outs.size();
2919     for (unsigned i = 0; i != NumArgs; ++i) {
2920       MVT ValVT = Outs[i].VT;
2921       // Get type of the original argument.
2922       EVT ActualVT = getValueType(DAG.getDataLayout(),
2923                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2924                                   /*AllowUnknown*/ true);
2925       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2926       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2927       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2928       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2929         ValVT = MVT::i8;
2930       else if (ActualMVT == MVT::i16)
2931         ValVT = MVT::i16;
2932
2933       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2934       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2935       assert(!Res && "Call operand has unhandled type");
2936       (void)Res;
2937     }
2938   }
2939
2940   // Get a count of how many bytes are to be pushed on the stack.
2941   unsigned NumBytes = CCInfo.getNextStackOffset();
2942
2943   if (IsSibCall) {
2944     // Since we're not changing the ABI to make this a tail call, the memory
2945     // operands are already available in the caller's incoming argument space.
2946     NumBytes = 0;
2947   }
2948
2949   // FPDiff is the byte offset of the call's argument area from the callee's.
2950   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2951   // by this amount for a tail call. In a sibling call it must be 0 because the
2952   // caller will deallocate the entire stack and the callee still expects its
2953   // arguments to begin at SP+0. Completely unused for non-tail calls.
2954   int FPDiff = 0;
2955
2956   if (IsTailCall && !IsSibCall) {
2957     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2958
2959     // Since callee will pop argument stack as a tail call, we must keep the
2960     // popped size 16-byte aligned.
2961     NumBytes = RoundUpToAlignment(NumBytes, 16);
2962
2963     // FPDiff will be negative if this tail call requires more space than we
2964     // would automatically have in our incoming argument space. Positive if we
2965     // can actually shrink the stack.
2966     FPDiff = NumReusableBytes - NumBytes;
2967
2968     // The stack pointer must be 16-byte aligned at all times it's used for a
2969     // memory operation, which in practice means at *all* times and in
2970     // particular across call boundaries. Therefore our own arguments started at
2971     // a 16-byte aligned SP and the delta applied for the tail call should
2972     // satisfy the same constraint.
2973     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2974   }
2975
2976   // Adjust the stack pointer for the new arguments...
2977   // These operations are automatically eliminated by the prolog/epilog pass
2978   if (!IsSibCall)
2979     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2980                                                               true),
2981                                  DL);
2982
2983   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2984                                         getPointerTy(DAG.getDataLayout()));
2985
2986   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2987   SmallVector<SDValue, 8> MemOpChains;
2988   auto PtrVT = getPointerTy(DAG.getDataLayout());
2989
2990   // Walk the register/memloc assignments, inserting copies/loads.
2991   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2992        ++i, ++realArgIdx) {
2993     CCValAssign &VA = ArgLocs[i];
2994     SDValue Arg = OutVals[realArgIdx];
2995     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2996
2997     // Promote the value if needed.
2998     switch (VA.getLocInfo()) {
2999     default:
3000       llvm_unreachable("Unknown loc info!");
3001     case CCValAssign::Full:
3002       break;
3003     case CCValAssign::SExt:
3004       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3005       break;
3006     case CCValAssign::ZExt:
3007       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3008       break;
3009     case CCValAssign::AExt:
3010       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3011         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3012         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3013         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3014       }
3015       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3016       break;
3017     case CCValAssign::BCvt:
3018       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3019       break;
3020     case CCValAssign::FPExt:
3021       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3022       break;
3023     }
3024
3025     if (VA.isRegLoc()) {
3026       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3027         assert(VA.getLocVT() == MVT::i64 &&
3028                "unexpected calling convention register assignment");
3029         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3030                "unexpected use of 'returned'");
3031         IsThisReturn = true;
3032       }
3033       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3034     } else {
3035       assert(VA.isMemLoc());
3036
3037       SDValue DstAddr;
3038       MachinePointerInfo DstInfo;
3039
3040       // FIXME: This works on big-endian for composite byvals, which are the
3041       // common case. It should also work for fundamental types too.
3042       uint32_t BEAlign = 0;
3043       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3044                                         : VA.getValVT().getSizeInBits();
3045       OpSize = (OpSize + 7) / 8;
3046       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3047           !Flags.isInConsecutiveRegs()) {
3048         if (OpSize < 8)
3049           BEAlign = 8 - OpSize;
3050       }
3051       unsigned LocMemOffset = VA.getLocMemOffset();
3052       int32_t Offset = LocMemOffset + BEAlign;
3053       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3054       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3055
3056       if (IsTailCall) {
3057         Offset = Offset + FPDiff;
3058         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3059
3060         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3061         DstInfo =
3062             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3063
3064         // Make sure any stack arguments overlapping with where we're storing
3065         // are loaded before this eventual operation. Otherwise they'll be
3066         // clobbered.
3067         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3068       } else {
3069         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3070
3071         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3072         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3073                                                LocMemOffset);
3074       }
3075
3076       if (Outs[i].Flags.isByVal()) {
3077         SDValue SizeNode =
3078             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3079         SDValue Cpy = DAG.getMemcpy(
3080             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3081             /*isVol = */ false, /*AlwaysInline = */ false,
3082             /*isTailCall = */ false,
3083             DstInfo, MachinePointerInfo());
3084
3085         MemOpChains.push_back(Cpy);
3086       } else {
3087         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3088         // promoted to a legal register type i32, we should truncate Arg back to
3089         // i1/i8/i16.
3090         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3091             VA.getValVT() == MVT::i16)
3092           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3093
3094         SDValue Store =
3095             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3096         MemOpChains.push_back(Store);
3097       }
3098     }
3099   }
3100
3101   if (!MemOpChains.empty())
3102     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3103
3104   // Build a sequence of copy-to-reg nodes chained together with token chain
3105   // and flag operands which copy the outgoing args into the appropriate regs.
3106   SDValue InFlag;
3107   for (auto &RegToPass : RegsToPass) {
3108     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3109                              RegToPass.second, InFlag);
3110     InFlag = Chain.getValue(1);
3111   }
3112
3113   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3114   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3115   // node so that legalize doesn't hack it.
3116   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3117       Subtarget->isTargetMachO()) {
3118     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3119       const GlobalValue *GV = G->getGlobal();
3120       bool InternalLinkage = GV->hasInternalLinkage();
3121       if (InternalLinkage)
3122         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3123       else {
3124         Callee =
3125             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3126         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3127       }
3128     } else if (ExternalSymbolSDNode *S =
3129                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3130       const char *Sym = S->getSymbol();
3131       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3132       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3133     }
3134   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3135     const GlobalValue *GV = G->getGlobal();
3136     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3137   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3138     const char *Sym = S->getSymbol();
3139     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3140   }
3141
3142   // We don't usually want to end the call-sequence here because we would tidy
3143   // the frame up *after* the call, however in the ABI-changing tail-call case
3144   // we've carefully laid out the parameters so that when sp is reset they'll be
3145   // in the correct location.
3146   if (IsTailCall && !IsSibCall) {
3147     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3148                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3149     InFlag = Chain.getValue(1);
3150   }
3151
3152   std::vector<SDValue> Ops;
3153   Ops.push_back(Chain);
3154   Ops.push_back(Callee);
3155
3156   if (IsTailCall) {
3157     // Each tail call may have to adjust the stack by a different amount, so
3158     // this information must travel along with the operation for eventual
3159     // consumption by emitEpilogue.
3160     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3161   }
3162
3163   // Add argument registers to the end of the list so that they are known live
3164   // into the call.
3165   for (auto &RegToPass : RegsToPass)
3166     Ops.push_back(DAG.getRegister(RegToPass.first,
3167                                   RegToPass.second.getValueType()));
3168
3169   // Add a register mask operand representing the call-preserved registers.
3170   const uint32_t *Mask;
3171   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3172   if (IsThisReturn) {
3173     // For 'this' returns, use the X0-preserving mask if applicable
3174     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3175     if (!Mask) {
3176       IsThisReturn = false;
3177       Mask = TRI->getCallPreservedMask(MF, CallConv);
3178     }
3179   } else
3180     Mask = TRI->getCallPreservedMask(MF, CallConv);
3181
3182   assert(Mask && "Missing call preserved mask for calling convention");
3183   Ops.push_back(DAG.getRegisterMask(Mask));
3184
3185   if (InFlag.getNode())
3186     Ops.push_back(InFlag);
3187
3188   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3189
3190   // If we're doing a tall call, use a TC_RETURN here rather than an
3191   // actual call instruction.
3192   if (IsTailCall) {
3193     MF.getFrameInfo()->setHasTailCall();
3194     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3195   }
3196
3197   // Returns a chain and a flag for retval copy to use.
3198   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3199   InFlag = Chain.getValue(1);
3200
3201   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3202                                 ? RoundUpToAlignment(NumBytes, 16)
3203                                 : 0;
3204
3205   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3206                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3207                              InFlag, DL);
3208   if (!Ins.empty())
3209     InFlag = Chain.getValue(1);
3210
3211   // Handle result values, copying them out of physregs into vregs that we
3212   // return.
3213   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3214                          InVals, IsThisReturn,
3215                          IsThisReturn ? OutVals[0] : SDValue());
3216 }
3217
3218 bool AArch64TargetLowering::CanLowerReturn(
3219     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3220     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3221   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3222                           ? RetCC_AArch64_WebKit_JS
3223                           : RetCC_AArch64_AAPCS;
3224   SmallVector<CCValAssign, 16> RVLocs;
3225   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3226   return CCInfo.CheckReturn(Outs, RetCC);
3227 }
3228
3229 SDValue
3230 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3231                                    bool isVarArg,
3232                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3233                                    const SmallVectorImpl<SDValue> &OutVals,
3234                                    SDLoc DL, SelectionDAG &DAG) const {
3235   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3236                           ? RetCC_AArch64_WebKit_JS
3237                           : RetCC_AArch64_AAPCS;
3238   SmallVector<CCValAssign, 16> RVLocs;
3239   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3240                  *DAG.getContext());
3241   CCInfo.AnalyzeReturn(Outs, RetCC);
3242
3243   // Copy the result values into the output registers.
3244   SDValue Flag;
3245   SmallVector<SDValue, 4> RetOps(1, Chain);
3246   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3247        ++i, ++realRVLocIdx) {
3248     CCValAssign &VA = RVLocs[i];
3249     assert(VA.isRegLoc() && "Can only return in registers!");
3250     SDValue Arg = OutVals[realRVLocIdx];
3251
3252     switch (VA.getLocInfo()) {
3253     default:
3254       llvm_unreachable("Unknown loc info!");
3255     case CCValAssign::Full:
3256       if (Outs[i].ArgVT == MVT::i1) {
3257         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3258         // value. This is strictly redundant on Darwin (which uses "zeroext
3259         // i1"), but will be optimised out before ISel.
3260         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3261         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3262       }
3263       break;
3264     case CCValAssign::BCvt:
3265       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3266       break;
3267     }
3268
3269     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3270     Flag = Chain.getValue(1);
3271     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3272   }
3273
3274   RetOps[0] = Chain; // Update chain.
3275
3276   // Add the flag if we have it.
3277   if (Flag.getNode())
3278     RetOps.push_back(Flag);
3279
3280   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3281 }
3282
3283 //===----------------------------------------------------------------------===//
3284 //  Other Lowering Code
3285 //===----------------------------------------------------------------------===//
3286
3287 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3288                                                   SelectionDAG &DAG) const {
3289   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3290   SDLoc DL(Op);
3291   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3292   const GlobalValue *GV = GN->getGlobal();
3293   unsigned char OpFlags =
3294       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3295
3296   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3297          "unexpected offset in global node");
3298
3299   // This also catched the large code model case for Darwin.
3300   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3301     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3302     // FIXME: Once remat is capable of dealing with instructions with register
3303     // operands, expand this into two nodes instead of using a wrapper node.
3304     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3305   }
3306
3307   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3308     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3309            "use of MO_CONSTPOOL only supported on small model");
3310     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3311     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3312     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3313     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3314     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3315     SDValue GlobalAddr = DAG.getLoad(
3316         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3317         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3318         /*isVolatile=*/false,
3319         /*isNonTemporal=*/true,
3320         /*isInvariant=*/true, 8);
3321     if (GN->getOffset() != 0)
3322       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3323                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3324     return GlobalAddr;
3325   }
3326
3327   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3328     const unsigned char MO_NC = AArch64II::MO_NC;
3329     return DAG.getNode(
3330         AArch64ISD::WrapperLarge, DL, PtrVT,
3331         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3332         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3333         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3334         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3335   } else {
3336     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3337     // the only correct model on Darwin.
3338     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3339                                             OpFlags | AArch64II::MO_PAGE);
3340     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3341     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3342
3343     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3344     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3345   }
3346 }
3347
3348 /// \brief Convert a TLS address reference into the correct sequence of loads
3349 /// and calls to compute the variable's address (for Darwin, currently) and
3350 /// return an SDValue containing the final node.
3351
3352 /// Darwin only has one TLS scheme which must be capable of dealing with the
3353 /// fully general situation, in the worst case. This means:
3354 ///     + "extern __thread" declaration.
3355 ///     + Defined in a possibly unknown dynamic library.
3356 ///
3357 /// The general system is that each __thread variable has a [3 x i64] descriptor
3358 /// which contains information used by the runtime to calculate the address. The
3359 /// only part of this the compiler needs to know about is the first xword, which
3360 /// contains a function pointer that must be called with the address of the
3361 /// entire descriptor in "x0".
3362 ///
3363 /// Since this descriptor may be in a different unit, in general even the
3364 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3365 /// is:
3366 ///     adrp x0, _var@TLVPPAGE
3367 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3368 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3369 ///                                      ; the function pointer
3370 ///     blr x1                           ; Uses descriptor address in x0
3371 ///     ; Address of _var is now in x0.
3372 ///
3373 /// If the address of _var's descriptor *is* known to the linker, then it can
3374 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3375 /// a slight efficiency gain.
3376 SDValue
3377 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3378                                                    SelectionDAG &DAG) const {
3379   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3380
3381   SDLoc DL(Op);
3382   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3383   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3384
3385   SDValue TLVPAddr =
3386       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3387   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3388
3389   // The first entry in the descriptor is a function pointer that we must call
3390   // to obtain the address of the variable.
3391   SDValue Chain = DAG.getEntryNode();
3392   SDValue FuncTLVGet =
3393       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3394                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3395                   true, true, 8);
3396   Chain = FuncTLVGet.getValue(1);
3397
3398   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3399   MFI->setAdjustsStack(true);
3400
3401   // TLS calls preserve all registers except those that absolutely must be
3402   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3403   // silly).
3404   const uint32_t *Mask =
3405       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3406
3407   // Finally, we can make the call. This is just a degenerate version of a
3408   // normal AArch64 call node: x0 takes the address of the descriptor, and
3409   // returns the address of the variable in this thread.
3410   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3411   Chain =
3412       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3413                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3414                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3415   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3416 }
3417
3418 /// When accessing thread-local variables under either the general-dynamic or
3419 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3420 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3421 /// is a function pointer to carry out the resolution.
3422 ///
3423 /// The sequence is:
3424 ///    adrp  x0, :tlsdesc:var
3425 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3426 ///    add   x0, x0, #:tlsdesc_lo12:var
3427 ///    .tlsdesccall var
3428 ///    blr   x1
3429 ///    (TPIDR_EL0 offset now in x0)
3430 ///
3431 ///  The above sequence must be produced unscheduled, to enable the linker to
3432 ///  optimize/relax this sequence.
3433 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3434 ///  above sequence, and expanded really late in the compilation flow, to ensure
3435 ///  the sequence is produced as per above.
3436 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3437                                                       SelectionDAG &DAG) const {
3438   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3439
3440   SDValue Chain = DAG.getEntryNode();
3441   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3442
3443   SmallVector<SDValue, 2> Ops;
3444   Ops.push_back(Chain);
3445   Ops.push_back(SymAddr);
3446
3447   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3448   SDValue Glue = Chain.getValue(1);
3449
3450   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3451 }
3452
3453 SDValue
3454 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3455                                                 SelectionDAG &DAG) const {
3456   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3457   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3458          "ELF TLS only supported in small memory model");
3459   // Different choices can be made for the maximum size of the TLS area for a
3460   // module. For the small address model, the default TLS size is 16MiB and the
3461   // maximum TLS size is 4GiB.
3462   // FIXME: add -mtls-size command line option and make it control the 16MiB
3463   // vs. 4GiB code sequence generation.
3464   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3465
3466   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3467
3468   if (DAG.getTarget().Options.EmulatedTLS)
3469     return LowerToTLSEmulatedModel(GA, DAG);
3470
3471   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3472     if (Model == TLSModel::LocalDynamic)
3473       Model = TLSModel::GeneralDynamic;
3474   }
3475
3476   SDValue TPOff;
3477   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3478   SDLoc DL(Op);
3479   const GlobalValue *GV = GA->getGlobal();
3480
3481   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3482
3483   if (Model == TLSModel::LocalExec) {
3484     SDValue HiVar = DAG.getTargetGlobalAddress(
3485         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3486     SDValue LoVar = DAG.getTargetGlobalAddress(
3487         GV, DL, PtrVT, 0,
3488         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3489
3490     SDValue TPWithOff_lo =
3491         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3492                                    HiVar,
3493                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3494                 0);
3495     SDValue TPWithOff =
3496         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3497                                    LoVar,
3498                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3499                 0);
3500     return TPWithOff;
3501   } else if (Model == TLSModel::InitialExec) {
3502     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3503     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3504   } else if (Model == TLSModel::LocalDynamic) {
3505     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3506     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3507     // the beginning of the module's TLS region, followed by a DTPREL offset
3508     // calculation.
3509
3510     // These accesses will need deduplicating if there's more than one.
3511     AArch64FunctionInfo *MFI =
3512         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3513     MFI->incNumLocalDynamicTLSAccesses();
3514
3515     // The call needs a relocation too for linker relaxation. It doesn't make
3516     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3517     // the address.
3518     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3519                                                   AArch64II::MO_TLS);
3520
3521     // Now we can calculate the offset from TPIDR_EL0 to this module's
3522     // thread-local area.
3523     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3524
3525     // Now use :dtprel_whatever: operations to calculate this variable's offset
3526     // in its thread-storage area.
3527     SDValue HiVar = DAG.getTargetGlobalAddress(
3528         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3529     SDValue LoVar = DAG.getTargetGlobalAddress(
3530         GV, DL, MVT::i64, 0,
3531         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3532
3533     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3534                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3535                     0);
3536     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3537                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3538                     0);
3539   } else if (Model == TLSModel::GeneralDynamic) {
3540     // The call needs a relocation too for linker relaxation. It doesn't make
3541     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3542     // the address.
3543     SDValue SymAddr =
3544         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3545
3546     // Finally we can make a call to calculate the offset from tpidr_el0.
3547     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3548   } else
3549     llvm_unreachable("Unsupported ELF TLS access model");
3550
3551   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3552 }
3553
3554 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3555                                                      SelectionDAG &DAG) const {
3556   if (Subtarget->isTargetDarwin())
3557     return LowerDarwinGlobalTLSAddress(Op, DAG);
3558   else if (Subtarget->isTargetELF())
3559     return LowerELFGlobalTLSAddress(Op, DAG);
3560
3561   llvm_unreachable("Unexpected platform trying to use TLS");
3562 }
3563 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3564   SDValue Chain = Op.getOperand(0);
3565   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3566   SDValue LHS = Op.getOperand(2);
3567   SDValue RHS = Op.getOperand(3);
3568   SDValue Dest = Op.getOperand(4);
3569   SDLoc dl(Op);
3570
3571   // Handle f128 first, since lowering it will result in comparing the return
3572   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3573   // is expecting to deal with.
3574   if (LHS.getValueType() == MVT::f128) {
3575     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3576
3577     // If softenSetCCOperands returned a scalar, we need to compare the result
3578     // against zero to select between true and false values.
3579     if (!RHS.getNode()) {
3580       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3581       CC = ISD::SETNE;
3582     }
3583   }
3584
3585   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3586   // instruction.
3587   unsigned Opc = LHS.getOpcode();
3588   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3589       cast<ConstantSDNode>(RHS)->isOne() &&
3590       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3591        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3592     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3593            "Unexpected condition code.");
3594     // Only lower legal XALUO ops.
3595     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3596       return SDValue();
3597
3598     // The actual operation with overflow check.
3599     AArch64CC::CondCode OFCC;
3600     SDValue Value, Overflow;
3601     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3602
3603     if (CC == ISD::SETNE)
3604       OFCC = getInvertedCondCode(OFCC);
3605     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3606
3607     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3608                        Overflow);
3609   }
3610
3611   if (LHS.getValueType().isInteger()) {
3612     assert((LHS.getValueType() == RHS.getValueType()) &&
3613            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3614
3615     // If the RHS of the comparison is zero, we can potentially fold this
3616     // to a specialized branch.
3617     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3618     if (RHSC && RHSC->getZExtValue() == 0) {
3619       if (CC == ISD::SETEQ) {
3620         // See if we can use a TBZ to fold in an AND as well.
3621         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3622         // out of bounds, a late MI-layer pass rewrites branches.
3623         // 403.gcc is an example that hits this case.
3624         if (LHS.getOpcode() == ISD::AND &&
3625             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3626             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3627           SDValue Test = LHS.getOperand(0);
3628           uint64_t Mask = LHS.getConstantOperandVal(1);
3629           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3630                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3631                              Dest);
3632         }
3633
3634         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3635       } else if (CC == ISD::SETNE) {
3636         // See if we can use a TBZ to fold in an AND as well.
3637         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3638         // out of bounds, a late MI-layer pass rewrites branches.
3639         // 403.gcc is an example that hits this case.
3640         if (LHS.getOpcode() == ISD::AND &&
3641             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3642             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3643           SDValue Test = LHS.getOperand(0);
3644           uint64_t Mask = LHS.getConstantOperandVal(1);
3645           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3646                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3647                              Dest);
3648         }
3649
3650         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3651       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3652         // Don't combine AND since emitComparison converts the AND to an ANDS
3653         // (a.k.a. TST) and the test in the test bit and branch instruction
3654         // becomes redundant.  This would also increase register pressure.
3655         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3656         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3657                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3658       }
3659     }
3660     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3661         LHS.getOpcode() != ISD::AND) {
3662       // Don't combine AND since emitComparison converts the AND to an ANDS
3663       // (a.k.a. TST) and the test in the test bit and branch instruction
3664       // becomes redundant.  This would also increase register pressure.
3665       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3666       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3667                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3668     }
3669
3670     SDValue CCVal;
3671     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3672     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3673                        Cmp);
3674   }
3675
3676   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3677
3678   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3679   // clean.  Some of them require two branches to implement.
3680   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3681   AArch64CC::CondCode CC1, CC2;
3682   changeFPCCToAArch64CC(CC, CC1, CC2);
3683   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3684   SDValue BR1 =
3685       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3686   if (CC2 != AArch64CC::AL) {
3687     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3688     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3689                        Cmp);
3690   }
3691
3692   return BR1;
3693 }
3694
3695 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3696                                               SelectionDAG &DAG) const {
3697   EVT VT = Op.getValueType();
3698   SDLoc DL(Op);
3699
3700   SDValue In1 = Op.getOperand(0);
3701   SDValue In2 = Op.getOperand(1);
3702   EVT SrcVT = In2.getValueType();
3703
3704   if (SrcVT.bitsLT(VT))
3705     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3706   else if (SrcVT.bitsGT(VT))
3707     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3708
3709   EVT VecVT;
3710   EVT EltVT;
3711   uint64_t EltMask;
3712   SDValue VecVal1, VecVal2;
3713   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3714     EltVT = MVT::i32;
3715     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3716     EltMask = 0x80000000ULL;
3717
3718     if (!VT.isVector()) {
3719       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3720                                           DAG.getUNDEF(VecVT), In1);
3721       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3722                                           DAG.getUNDEF(VecVT), In2);
3723     } else {
3724       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3725       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3726     }
3727   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3728     EltVT = MVT::i64;
3729     VecVT = MVT::v2i64;
3730
3731     // We want to materialize a mask with the high bit set, but the AdvSIMD
3732     // immediate moves cannot materialize that in a single instruction for
3733     // 64-bit elements. Instead, materialize zero and then negate it.
3734     EltMask = 0;
3735
3736     if (!VT.isVector()) {
3737       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3738                                           DAG.getUNDEF(VecVT), In1);
3739       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3740                                           DAG.getUNDEF(VecVT), In2);
3741     } else {
3742       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3743       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3744     }
3745   } else {
3746     llvm_unreachable("Invalid type for copysign!");
3747   }
3748
3749   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3750
3751   // If we couldn't materialize the mask above, then the mask vector will be
3752   // the zero vector, and we need to negate it here.
3753   if (VT == MVT::f64 || VT == MVT::v2f64) {
3754     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3755     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3756     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3757   }
3758
3759   SDValue Sel =
3760       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3761
3762   if (VT == MVT::f32)
3763     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3764   else if (VT == MVT::f64)
3765     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3766   else
3767     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3768 }
3769
3770 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3771   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3772           Attribute::NoImplicitFloat))
3773     return SDValue();
3774
3775   if (!Subtarget->hasNEON())
3776     return SDValue();
3777
3778   // While there is no integer popcount instruction, it can
3779   // be more efficiently lowered to the following sequence that uses
3780   // AdvSIMD registers/instructions as long as the copies to/from
3781   // the AdvSIMD registers are cheap.
3782   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3783   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3784   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3785   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3786   SDValue Val = Op.getOperand(0);
3787   SDLoc DL(Op);
3788   EVT VT = Op.getValueType();
3789
3790   if (VT == MVT::i32)
3791     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3792   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3793
3794   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3795   SDValue UaddLV = DAG.getNode(
3796       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3797       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3798
3799   if (VT == MVT::i64)
3800     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3801   return UaddLV;
3802 }
3803
3804 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3805
3806   if (Op.getValueType().isVector())
3807     return LowerVSETCC(Op, DAG);
3808
3809   SDValue LHS = Op.getOperand(0);
3810   SDValue RHS = Op.getOperand(1);
3811   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3812   SDLoc dl(Op);
3813
3814   // We chose ZeroOrOneBooleanContents, so use zero and one.
3815   EVT VT = Op.getValueType();
3816   SDValue TVal = DAG.getConstant(1, dl, VT);
3817   SDValue FVal = DAG.getConstant(0, dl, VT);
3818
3819   // Handle f128 first, since one possible outcome is a normal integer
3820   // comparison which gets picked up by the next if statement.
3821   if (LHS.getValueType() == MVT::f128) {
3822     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3823
3824     // If softenSetCCOperands returned a scalar, use it.
3825     if (!RHS.getNode()) {
3826       assert(LHS.getValueType() == Op.getValueType() &&
3827              "Unexpected setcc expansion!");
3828       return LHS;
3829     }
3830   }
3831
3832   if (LHS.getValueType().isInteger()) {
3833     SDValue CCVal;
3834     SDValue Cmp =
3835         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3836
3837     // Note that we inverted the condition above, so we reverse the order of
3838     // the true and false operands here.  This will allow the setcc to be
3839     // matched to a single CSINC instruction.
3840     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3841   }
3842
3843   // Now we know we're dealing with FP values.
3844   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3845
3846   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3847   // and do the comparison.
3848   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3849
3850   AArch64CC::CondCode CC1, CC2;
3851   changeFPCCToAArch64CC(CC, CC1, CC2);
3852   if (CC2 == AArch64CC::AL) {
3853     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3854     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3855
3856     // Note that we inverted the condition above, so we reverse the order of
3857     // the true and false operands here.  This will allow the setcc to be
3858     // matched to a single CSINC instruction.
3859     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3860   } else {
3861     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3862     // totally clean.  Some of them require two CSELs to implement.  As is in
3863     // this case, we emit the first CSEL and then emit a second using the output
3864     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3865
3866     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3867     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3868     SDValue CS1 =
3869         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3870
3871     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3872     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3873   }
3874 }
3875
3876 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3877                                               SDValue RHS, SDValue TVal,
3878                                               SDValue FVal, SDLoc dl,
3879                                               SelectionDAG &DAG) const {
3880   // Handle f128 first, because it will result in a comparison of some RTLIB
3881   // call result against zero.
3882   if (LHS.getValueType() == MVT::f128) {
3883     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3884
3885     // If softenSetCCOperands returned a scalar, we need to compare the result
3886     // against zero to select between true and false values.
3887     if (!RHS.getNode()) {
3888       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3889       CC = ISD::SETNE;
3890     }
3891   }
3892
3893   // Handle integers first.
3894   if (LHS.getValueType().isInteger()) {
3895     assert((LHS.getValueType() == RHS.getValueType()) &&
3896            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3897
3898     unsigned Opcode = AArch64ISD::CSEL;
3899
3900     // If both the TVal and the FVal are constants, see if we can swap them in
3901     // order to for a CSINV or CSINC out of them.
3902     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3903     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3904
3905     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3906       std::swap(TVal, FVal);
3907       std::swap(CTVal, CFVal);
3908       CC = ISD::getSetCCInverse(CC, true);
3909     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3910       std::swap(TVal, FVal);
3911       std::swap(CTVal, CFVal);
3912       CC = ISD::getSetCCInverse(CC, true);
3913     } else if (TVal.getOpcode() == ISD::XOR) {
3914       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3915       // with a CSINV rather than a CSEL.
3916       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3917
3918       if (CVal && CVal->isAllOnesValue()) {
3919         std::swap(TVal, FVal);
3920         std::swap(CTVal, CFVal);
3921         CC = ISD::getSetCCInverse(CC, true);
3922       }
3923     } else if (TVal.getOpcode() == ISD::SUB) {
3924       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3925       // that we can match with a CSNEG rather than a CSEL.
3926       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3927
3928       if (CVal && CVal->isNullValue()) {
3929         std::swap(TVal, FVal);
3930         std::swap(CTVal, CFVal);
3931         CC = ISD::getSetCCInverse(CC, true);
3932       }
3933     } else if (CTVal && CFVal) {
3934       const int64_t TrueVal = CTVal->getSExtValue();
3935       const int64_t FalseVal = CFVal->getSExtValue();
3936       bool Swap = false;
3937
3938       // If both TVal and FVal are constants, see if FVal is the
3939       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3940       // instead of a CSEL in that case.
3941       if (TrueVal == ~FalseVal) {
3942         Opcode = AArch64ISD::CSINV;
3943       } else if (TrueVal == -FalseVal) {
3944         Opcode = AArch64ISD::CSNEG;
3945       } else if (TVal.getValueType() == MVT::i32) {
3946         // If our operands are only 32-bit wide, make sure we use 32-bit
3947         // arithmetic for the check whether we can use CSINC. This ensures that
3948         // the addition in the check will wrap around properly in case there is
3949         // an overflow (which would not be the case if we do the check with
3950         // 64-bit arithmetic).
3951         const uint32_t TrueVal32 = CTVal->getZExtValue();
3952         const uint32_t FalseVal32 = CFVal->getZExtValue();
3953
3954         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3955           Opcode = AArch64ISD::CSINC;
3956
3957           if (TrueVal32 > FalseVal32) {
3958             Swap = true;
3959           }
3960         }
3961         // 64-bit check whether we can use CSINC.
3962       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3963         Opcode = AArch64ISD::CSINC;
3964
3965         if (TrueVal > FalseVal) {
3966           Swap = true;
3967         }
3968       }
3969
3970       // Swap TVal and FVal if necessary.
3971       if (Swap) {
3972         std::swap(TVal, FVal);
3973         std::swap(CTVal, CFVal);
3974         CC = ISD::getSetCCInverse(CC, true);
3975       }
3976
3977       if (Opcode != AArch64ISD::CSEL) {
3978         // Drop FVal since we can get its value by simply inverting/negating
3979         // TVal.
3980         FVal = TVal;
3981       }
3982     }
3983
3984     SDValue CCVal;
3985     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3986
3987     EVT VT = TVal.getValueType();
3988     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3989   }
3990
3991   // Now we know we're dealing with FP values.
3992   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3993   assert(LHS.getValueType() == RHS.getValueType());
3994   EVT VT = TVal.getValueType();
3995   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3996
3997   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3998   // clean.  Some of them require two CSELs to implement.
3999   AArch64CC::CondCode CC1, CC2;
4000   changeFPCCToAArch64CC(CC, CC1, CC2);
4001   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4002   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4003
4004   // If we need a second CSEL, emit it, using the output of the first as the
4005   // RHS.  We're effectively OR'ing the two CC's together.
4006   if (CC2 != AArch64CC::AL) {
4007     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4008     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4009   }
4010
4011   // Otherwise, return the output of the first CSEL.
4012   return CS1;
4013 }
4014
4015 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4016                                               SelectionDAG &DAG) const {
4017   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4018   SDValue LHS = Op.getOperand(0);
4019   SDValue RHS = Op.getOperand(1);
4020   SDValue TVal = Op.getOperand(2);
4021   SDValue FVal = Op.getOperand(3);
4022   SDLoc DL(Op);
4023   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4024 }
4025
4026 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4027                                            SelectionDAG &DAG) const {
4028   SDValue CCVal = Op->getOperand(0);
4029   SDValue TVal = Op->getOperand(1);
4030   SDValue FVal = Op->getOperand(2);
4031   SDLoc DL(Op);
4032
4033   unsigned Opc = CCVal.getOpcode();
4034   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4035   // instruction.
4036   if (CCVal.getResNo() == 1 &&
4037       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4038        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4039     // Only lower legal XALUO ops.
4040     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4041       return SDValue();
4042
4043     AArch64CC::CondCode OFCC;
4044     SDValue Value, Overflow;
4045     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4046     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4047
4048     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4049                        CCVal, Overflow);
4050   }
4051
4052   // Lower it the same way as we would lower a SELECT_CC node.
4053   ISD::CondCode CC;
4054   SDValue LHS, RHS;
4055   if (CCVal.getOpcode() == ISD::SETCC) {
4056     LHS = CCVal.getOperand(0);
4057     RHS = CCVal.getOperand(1);
4058     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4059   } else {
4060     LHS = CCVal;
4061     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4062     CC = ISD::SETNE;
4063   }
4064   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4065 }
4066
4067 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4068                                               SelectionDAG &DAG) const {
4069   // Jump table entries as PC relative offsets. No additional tweaking
4070   // is necessary here. Just get the address of the jump table.
4071   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4072   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4073   SDLoc DL(Op);
4074
4075   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4076       !Subtarget->isTargetMachO()) {
4077     const unsigned char MO_NC = AArch64II::MO_NC;
4078     return DAG.getNode(
4079         AArch64ISD::WrapperLarge, DL, PtrVT,
4080         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4081         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4082         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4083         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4084                                AArch64II::MO_G0 | MO_NC));
4085   }
4086
4087   SDValue Hi =
4088       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4089   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4090                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4091   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4092   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4093 }
4094
4095 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4096                                                  SelectionDAG &DAG) const {
4097   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4098   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4099   SDLoc DL(Op);
4100
4101   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4102     // Use the GOT for the large code model on iOS.
4103     if (Subtarget->isTargetMachO()) {
4104       SDValue GotAddr = DAG.getTargetConstantPool(
4105           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4106           AArch64II::MO_GOT);
4107       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4108     }
4109
4110     const unsigned char MO_NC = AArch64II::MO_NC;
4111     return DAG.getNode(
4112         AArch64ISD::WrapperLarge, DL, PtrVT,
4113         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4114                                   CP->getOffset(), AArch64II::MO_G3),
4115         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4116                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4117         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4118                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4119         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4120                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4121   } else {
4122     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4123     // ELF, the only valid one on Darwin.
4124     SDValue Hi =
4125         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4126                                   CP->getOffset(), AArch64II::MO_PAGE);
4127     SDValue Lo = DAG.getTargetConstantPool(
4128         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4129         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4130
4131     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4132     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4133   }
4134 }
4135
4136 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4137                                                SelectionDAG &DAG) const {
4138   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4139   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4140   SDLoc DL(Op);
4141   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4142       !Subtarget->isTargetMachO()) {
4143     const unsigned char MO_NC = AArch64II::MO_NC;
4144     return DAG.getNode(
4145         AArch64ISD::WrapperLarge, DL, PtrVT,
4146         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4147         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4148         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4149         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4150   } else {
4151     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4152     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4153                                                              AArch64II::MO_NC);
4154     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4155     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4156   }
4157 }
4158
4159 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4160                                                  SelectionDAG &DAG) const {
4161   AArch64FunctionInfo *FuncInfo =
4162       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4163
4164   SDLoc DL(Op);
4165   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4166                                  getPointerTy(DAG.getDataLayout()));
4167   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4168   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4169                       MachinePointerInfo(SV), false, false, 0);
4170 }
4171
4172 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4173                                                 SelectionDAG &DAG) const {
4174   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4175   // Standard, section B.3.
4176   MachineFunction &MF = DAG.getMachineFunction();
4177   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4178   auto PtrVT = getPointerTy(DAG.getDataLayout());
4179   SDLoc DL(Op);
4180
4181   SDValue Chain = Op.getOperand(0);
4182   SDValue VAList = Op.getOperand(1);
4183   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4184   SmallVector<SDValue, 4> MemOps;
4185
4186   // void *__stack at offset 0
4187   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4188   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4189                                 MachinePointerInfo(SV), false, false, 8));
4190
4191   // void *__gr_top at offset 8
4192   int GPRSize = FuncInfo->getVarArgsGPRSize();
4193   if (GPRSize > 0) {
4194     SDValue GRTop, GRTopAddr;
4195
4196     GRTopAddr =
4197         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4198
4199     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4200     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4201                         DAG.getConstant(GPRSize, DL, PtrVT));
4202
4203     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4204                                   MachinePointerInfo(SV, 8), false, false, 8));
4205   }
4206
4207   // void *__vr_top at offset 16
4208   int FPRSize = FuncInfo->getVarArgsFPRSize();
4209   if (FPRSize > 0) {
4210     SDValue VRTop, VRTopAddr;
4211     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4212                             DAG.getConstant(16, DL, PtrVT));
4213
4214     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4215     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4216                         DAG.getConstant(FPRSize, DL, PtrVT));
4217
4218     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4219                                   MachinePointerInfo(SV, 16), false, false, 8));
4220   }
4221
4222   // int __gr_offs at offset 24
4223   SDValue GROffsAddr =
4224       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4225   MemOps.push_back(DAG.getStore(Chain, DL,
4226                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4227                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4228                                 false, 4));
4229
4230   // int __vr_offs at offset 28
4231   SDValue VROffsAddr =
4232       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4233   MemOps.push_back(DAG.getStore(Chain, DL,
4234                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4235                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4236                                 false, 4));
4237
4238   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4239 }
4240
4241 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4242                                             SelectionDAG &DAG) const {
4243   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4244                                      : LowerAAPCS_VASTART(Op, DAG);
4245 }
4246
4247 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4248                                            SelectionDAG &DAG) const {
4249   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4250   // pointer.
4251   SDLoc DL(Op);
4252   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4253   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4254   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4255
4256   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4257                        Op.getOperand(2),
4258                        DAG.getConstant(VaListSize, DL, MVT::i32),
4259                        8, false, false, false, MachinePointerInfo(DestSV),
4260                        MachinePointerInfo(SrcSV));
4261 }
4262
4263 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4264   assert(Subtarget->isTargetDarwin() &&
4265          "automatic va_arg instruction only works on Darwin");
4266
4267   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4268   EVT VT = Op.getValueType();
4269   SDLoc DL(Op);
4270   SDValue Chain = Op.getOperand(0);
4271   SDValue Addr = Op.getOperand(1);
4272   unsigned Align = Op.getConstantOperandVal(3);
4273   auto PtrVT = getPointerTy(DAG.getDataLayout());
4274
4275   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4276                                false, false, false, 0);
4277   Chain = VAList.getValue(1);
4278
4279   if (Align > 8) {
4280     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4281     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4282                          DAG.getConstant(Align - 1, DL, PtrVT));
4283     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4284                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4285   }
4286
4287   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4288   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4289
4290   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4291   // up to 64 bits.  At the very least, we have to increase the striding of the
4292   // vaargs list to match this, and for FP values we need to introduce
4293   // FP_ROUND nodes as well.
4294   if (VT.isInteger() && !VT.isVector())
4295     ArgSize = 8;
4296   bool NeedFPTrunc = false;
4297   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4298     ArgSize = 8;
4299     NeedFPTrunc = true;
4300   }
4301
4302   // Increment the pointer, VAList, to the next vaarg
4303   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4304                                DAG.getConstant(ArgSize, DL, PtrVT));
4305   // Store the incremented VAList to the legalized pointer
4306   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4307                                  false, false, 0);
4308
4309   // Load the actual argument out of the pointer VAList
4310   if (NeedFPTrunc) {
4311     // Load the value as an f64.
4312     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4313                                  MachinePointerInfo(), false, false, false, 0);
4314     // Round the value down to an f32.
4315     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4316                                    DAG.getIntPtrConstant(1, DL));
4317     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4318     // Merge the rounded value with the chain output of the load.
4319     return DAG.getMergeValues(Ops, DL);
4320   }
4321
4322   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4323                      false, false, 0);
4324 }
4325
4326 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4327                                               SelectionDAG &DAG) const {
4328   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4329   MFI->setFrameAddressIsTaken(true);
4330
4331   EVT VT = Op.getValueType();
4332   SDLoc DL(Op);
4333   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4334   SDValue FrameAddr =
4335       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4336   while (Depth--)
4337     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4338                             MachinePointerInfo(), false, false, false, 0);
4339   return FrameAddr;
4340 }
4341
4342 // FIXME? Maybe this could be a TableGen attribute on some registers and
4343 // this table could be generated automatically from RegInfo.
4344 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4345                                                   SelectionDAG &DAG) const {
4346   unsigned Reg = StringSwitch<unsigned>(RegName)
4347                        .Case("sp", AArch64::SP)
4348                        .Default(0);
4349   if (Reg)
4350     return Reg;
4351   report_fatal_error(Twine("Invalid register name \""
4352                               + StringRef(RegName)  + "\"."));
4353 }
4354
4355 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4356                                                SelectionDAG &DAG) const {
4357   MachineFunction &MF = DAG.getMachineFunction();
4358   MachineFrameInfo *MFI = MF.getFrameInfo();
4359   MFI->setReturnAddressIsTaken(true);
4360
4361   EVT VT = Op.getValueType();
4362   SDLoc DL(Op);
4363   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4364   if (Depth) {
4365     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4366     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4367     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4368                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4369                        MachinePointerInfo(), false, false, false, 0);
4370   }
4371
4372   // Return LR, which contains the return address. Mark it an implicit live-in.
4373   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4374   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4375 }
4376
4377 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4378 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4379 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4380                                                     SelectionDAG &DAG) const {
4381   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4382   EVT VT = Op.getValueType();
4383   unsigned VTBits = VT.getSizeInBits();
4384   SDLoc dl(Op);
4385   SDValue ShOpLo = Op.getOperand(0);
4386   SDValue ShOpHi = Op.getOperand(1);
4387   SDValue ShAmt = Op.getOperand(2);
4388   SDValue ARMcc;
4389   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4390
4391   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4392
4393   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4394                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4395   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4396   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4397                                    DAG.getConstant(VTBits, dl, MVT::i64));
4398   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4399
4400   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4401                                ISD::SETGE, dl, DAG);
4402   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4403
4404   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4405   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4406   SDValue Lo =
4407       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4408
4409   // AArch64 shifts larger than the register width are wrapped rather than
4410   // clamped, so we can't just emit "hi >> x".
4411   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4412   SDValue TrueValHi = Opc == ISD::SRA
4413                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4414                                         DAG.getConstant(VTBits - 1, dl,
4415                                                         MVT::i64))
4416                           : DAG.getConstant(0, dl, VT);
4417   SDValue Hi =
4418       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4419
4420   SDValue Ops[2] = { Lo, Hi };
4421   return DAG.getMergeValues(Ops, dl);
4422 }
4423
4424 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4425 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4426 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4427                                                  SelectionDAG &DAG) const {
4428   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4429   EVT VT = Op.getValueType();
4430   unsigned VTBits = VT.getSizeInBits();
4431   SDLoc dl(Op);
4432   SDValue ShOpLo = Op.getOperand(0);
4433   SDValue ShOpHi = Op.getOperand(1);
4434   SDValue ShAmt = Op.getOperand(2);
4435   SDValue ARMcc;
4436
4437   assert(Op.getOpcode() == ISD::SHL_PARTS);
4438   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4439                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4440   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4441   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4442                                    DAG.getConstant(VTBits, dl, MVT::i64));
4443   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4444   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4445
4446   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4447
4448   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4449                                ISD::SETGE, dl, DAG);
4450   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4451   SDValue Hi =
4452       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4453
4454   // AArch64 shifts of larger than register sizes are wrapped rather than
4455   // clamped, so we can't just emit "lo << a" if a is too big.
4456   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4457   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4458   SDValue Lo =
4459       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4460
4461   SDValue Ops[2] = { Lo, Hi };
4462   return DAG.getMergeValues(Ops, dl);
4463 }
4464
4465 bool AArch64TargetLowering::isOffsetFoldingLegal(
4466     const GlobalAddressSDNode *GA) const {
4467   // The AArch64 target doesn't support folding offsets into global addresses.
4468   return false;
4469 }
4470
4471 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4472   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4473   // FIXME: We should be able to handle f128 as well with a clever lowering.
4474   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4475     return true;
4476
4477   if (VT == MVT::f64)
4478     return AArch64_AM::getFP64Imm(Imm) != -1;
4479   else if (VT == MVT::f32)
4480     return AArch64_AM::getFP32Imm(Imm) != -1;
4481   return false;
4482 }
4483
4484 //===----------------------------------------------------------------------===//
4485 //                          AArch64 Optimization Hooks
4486 //===----------------------------------------------------------------------===//
4487
4488 //===----------------------------------------------------------------------===//
4489 //                          AArch64 Inline Assembly Support
4490 //===----------------------------------------------------------------------===//
4491
4492 // Table of Constraints
4493 // TODO: This is the current set of constraints supported by ARM for the
4494 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4495 //
4496 // r - A general register
4497 // w - An FP/SIMD register of some size in the range v0-v31
4498 // x - An FP/SIMD register of some size in the range v0-v15
4499 // I - Constant that can be used with an ADD instruction
4500 // J - Constant that can be used with a SUB instruction
4501 // K - Constant that can be used with a 32-bit logical instruction
4502 // L - Constant that can be used with a 64-bit logical instruction
4503 // M - Constant that can be used as a 32-bit MOV immediate
4504 // N - Constant that can be used as a 64-bit MOV immediate
4505 // Q - A memory reference with base register and no offset
4506 // S - A symbolic address
4507 // Y - Floating point constant zero
4508 // Z - Integer constant zero
4509 //
4510 //   Note that general register operands will be output using their 64-bit x
4511 // register name, whatever the size of the variable, unless the asm operand
4512 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4513 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4514 // %q modifier.
4515
4516 /// getConstraintType - Given a constraint letter, return the type of
4517 /// constraint it is for this target.
4518 AArch64TargetLowering::ConstraintType
4519 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4520   if (Constraint.size() == 1) {
4521     switch (Constraint[0]) {
4522     default:
4523       break;
4524     case 'z':
4525       return C_Other;
4526     case 'x':
4527     case 'w':
4528       return C_RegisterClass;
4529     // An address with a single base register. Due to the way we
4530     // currently handle addresses it is the same as 'r'.
4531     case 'Q':
4532       return C_Memory;
4533     }
4534   }
4535   return TargetLowering::getConstraintType(Constraint);
4536 }
4537
4538 /// Examine constraint type and operand type and determine a weight value.
4539 /// This object must already have been set up with the operand type
4540 /// and the current alternative constraint selected.
4541 TargetLowering::ConstraintWeight
4542 AArch64TargetLowering::getSingleConstraintMatchWeight(
4543     AsmOperandInfo &info, const char *constraint) const {
4544   ConstraintWeight weight = CW_Invalid;
4545   Value *CallOperandVal = info.CallOperandVal;
4546   // If we don't have a value, we can't do a match,
4547   // but allow it at the lowest weight.
4548   if (!CallOperandVal)
4549     return CW_Default;
4550   Type *type = CallOperandVal->getType();
4551   // Look at the constraint type.
4552   switch (*constraint) {
4553   default:
4554     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4555     break;
4556   case 'x':
4557   case 'w':
4558     if (type->isFloatingPointTy() || type->isVectorTy())
4559       weight = CW_Register;
4560     break;
4561   case 'z':
4562     weight = CW_Constant;
4563     break;
4564   }
4565   return weight;
4566 }
4567
4568 std::pair<unsigned, const TargetRegisterClass *>
4569 AArch64TargetLowering::getRegForInlineAsmConstraint(
4570     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4571   if (Constraint.size() == 1) {
4572     switch (Constraint[0]) {
4573     case 'r':
4574       if (VT.getSizeInBits() == 64)
4575         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4576       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4577     case 'w':
4578       if (VT == MVT::f32)
4579         return std::make_pair(0U, &AArch64::FPR32RegClass);
4580       if (VT.getSizeInBits() == 64)
4581         return std::make_pair(0U, &AArch64::FPR64RegClass);
4582       if (VT.getSizeInBits() == 128)
4583         return std::make_pair(0U, &AArch64::FPR128RegClass);
4584       break;
4585     // The instructions that this constraint is designed for can
4586     // only take 128-bit registers so just use that regclass.
4587     case 'x':
4588       if (VT.getSizeInBits() == 128)
4589         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4590       break;
4591     }
4592   }
4593   if (StringRef("{cc}").equals_lower(Constraint))
4594     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4595
4596   // Use the default implementation in TargetLowering to convert the register
4597   // constraint into a member of a register class.
4598   std::pair<unsigned, const TargetRegisterClass *> Res;
4599   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4600
4601   // Not found as a standard register?
4602   if (!Res.second) {
4603     unsigned Size = Constraint.size();
4604     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4605         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4606       int RegNo;
4607       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4608       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4609         // v0 - v31 are aliases of q0 - q31.
4610         // By default we'll emit v0-v31 for this unless there's a modifier where
4611         // we'll emit the correct register as well.
4612         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4613         Res.second = &AArch64::FPR128RegClass;
4614       }
4615     }
4616   }
4617
4618   return Res;
4619 }
4620
4621 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4622 /// vector.  If it is invalid, don't add anything to Ops.
4623 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4624     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4625     SelectionDAG &DAG) const {
4626   SDValue Result;
4627
4628   // Currently only support length 1 constraints.
4629   if (Constraint.length() != 1)
4630     return;
4631
4632   char ConstraintLetter = Constraint[0];
4633   switch (ConstraintLetter) {
4634   default:
4635     break;
4636
4637   // This set of constraints deal with valid constants for various instructions.
4638   // Validate and return a target constant for them if we can.
4639   case 'z': {
4640     // 'z' maps to xzr or wzr so it needs an input of 0.
4641     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4642     if (!C || C->getZExtValue() != 0)
4643       return;
4644
4645     if (Op.getValueType() == MVT::i64)
4646       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4647     else
4648       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4649     break;
4650   }
4651
4652   case 'I':
4653   case 'J':
4654   case 'K':
4655   case 'L':
4656   case 'M':
4657   case 'N':
4658     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4659     if (!C)
4660       return;
4661
4662     // Grab the value and do some validation.
4663     uint64_t CVal = C->getZExtValue();
4664     switch (ConstraintLetter) {
4665     // The I constraint applies only to simple ADD or SUB immediate operands:
4666     // i.e. 0 to 4095 with optional shift by 12
4667     // The J constraint applies only to ADD or SUB immediates that would be
4668     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4669     // instruction [or vice versa], in other words -1 to -4095 with optional
4670     // left shift by 12.
4671     case 'I':
4672       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4673         break;
4674       return;
4675     case 'J': {
4676       uint64_t NVal = -C->getSExtValue();
4677       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4678         CVal = C->getSExtValue();
4679         break;
4680       }
4681       return;
4682     }
4683     // The K and L constraints apply *only* to logical immediates, including
4684     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4685     // been removed and MOV should be used). So these constraints have to
4686     // distinguish between bit patterns that are valid 32-bit or 64-bit
4687     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4688     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4689     // versa.
4690     case 'K':
4691       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4692         break;
4693       return;
4694     case 'L':
4695       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4696         break;
4697       return;
4698     // The M and N constraints are a superset of K and L respectively, for use
4699     // with the MOV (immediate) alias. As well as the logical immediates they
4700     // also match 32 or 64-bit immediates that can be loaded either using a
4701     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4702     // (M) or 64-bit 0x1234000000000000 (N) etc.
4703     // As a note some of this code is liberally stolen from the asm parser.
4704     case 'M': {
4705       if (!isUInt<32>(CVal))
4706         return;
4707       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4708         break;
4709       if ((CVal & 0xFFFF) == CVal)
4710         break;
4711       if ((CVal & 0xFFFF0000ULL) == CVal)
4712         break;
4713       uint64_t NCVal = ~(uint32_t)CVal;
4714       if ((NCVal & 0xFFFFULL) == NCVal)
4715         break;
4716       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4717         break;
4718       return;
4719     }
4720     case 'N': {
4721       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4722         break;
4723       if ((CVal & 0xFFFFULL) == CVal)
4724         break;
4725       if ((CVal & 0xFFFF0000ULL) == CVal)
4726         break;
4727       if ((CVal & 0xFFFF00000000ULL) == CVal)
4728         break;
4729       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4730         break;
4731       uint64_t NCVal = ~CVal;
4732       if ((NCVal & 0xFFFFULL) == NCVal)
4733         break;
4734       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4735         break;
4736       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4737         break;
4738       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4739         break;
4740       return;
4741     }
4742     default:
4743       return;
4744     }
4745
4746     // All assembler immediates are 64-bit integers.
4747     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4748     break;
4749   }
4750
4751   if (Result.getNode()) {
4752     Ops.push_back(Result);
4753     return;
4754   }
4755
4756   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4757 }
4758
4759 //===----------------------------------------------------------------------===//
4760 //                     AArch64 Advanced SIMD Support
4761 //===----------------------------------------------------------------------===//
4762
4763 /// WidenVector - Given a value in the V64 register class, produce the
4764 /// equivalent value in the V128 register class.
4765 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4766   EVT VT = V64Reg.getValueType();
4767   unsigned NarrowSize = VT.getVectorNumElements();
4768   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4769   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4770   SDLoc DL(V64Reg);
4771
4772   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4773                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4774 }
4775
4776 /// getExtFactor - Determine the adjustment factor for the position when
4777 /// generating an "extract from vector registers" instruction.
4778 static unsigned getExtFactor(SDValue &V) {
4779   EVT EltType = V.getValueType().getVectorElementType();
4780   return EltType.getSizeInBits() / 8;
4781 }
4782
4783 /// NarrowVector - Given a value in the V128 register class, produce the
4784 /// equivalent value in the V64 register class.
4785 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4786   EVT VT = V128Reg.getValueType();
4787   unsigned WideSize = VT.getVectorNumElements();
4788   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4789   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4790   SDLoc DL(V128Reg);
4791
4792   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4793 }
4794
4795 // Gather data to see if the operation can be modelled as a
4796 // shuffle in combination with VEXTs.
4797 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4798                                                   SelectionDAG &DAG) const {
4799   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4800   SDLoc dl(Op);
4801   EVT VT = Op.getValueType();
4802   unsigned NumElts = VT.getVectorNumElements();
4803
4804   struct ShuffleSourceInfo {
4805     SDValue Vec;
4806     unsigned MinElt;
4807     unsigned MaxElt;
4808
4809     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4810     // be compatible with the shuffle we intend to construct. As a result
4811     // ShuffleVec will be some sliding window into the original Vec.
4812     SDValue ShuffleVec;
4813
4814     // Code should guarantee that element i in Vec starts at element "WindowBase
4815     // + i * WindowScale in ShuffleVec".
4816     int WindowBase;
4817     int WindowScale;
4818
4819     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4820     ShuffleSourceInfo(SDValue Vec)
4821         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4822           WindowScale(1) {}
4823   };
4824
4825   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4826   // node.
4827   SmallVector<ShuffleSourceInfo, 2> Sources;
4828   for (unsigned i = 0; i < NumElts; ++i) {
4829     SDValue V = Op.getOperand(i);
4830     if (V.getOpcode() == ISD::UNDEF)
4831       continue;
4832     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4833       // A shuffle can only come from building a vector from various
4834       // elements of other vectors.
4835       return SDValue();
4836     }
4837
4838     // Add this element source to the list if it's not already there.
4839     SDValue SourceVec = V.getOperand(0);
4840     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4841     if (Source == Sources.end())
4842       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4843
4844     // Update the minimum and maximum lane number seen.
4845     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4846     Source->MinElt = std::min(Source->MinElt, EltNo);
4847     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4848   }
4849
4850   // Currently only do something sane when at most two source vectors
4851   // are involved.
4852   if (Sources.size() > 2)
4853     return SDValue();
4854
4855   // Find out the smallest element size among result and two sources, and use
4856   // it as element size to build the shuffle_vector.
4857   EVT SmallestEltTy = VT.getVectorElementType();
4858   for (auto &Source : Sources) {
4859     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4860     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4861       SmallestEltTy = SrcEltTy;
4862     }
4863   }
4864   unsigned ResMultiplier =
4865       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4866   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4867   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4868
4869   // If the source vector is too wide or too narrow, we may nevertheless be able
4870   // to construct a compatible shuffle either by concatenating it with UNDEF or
4871   // extracting a suitable range of elements.
4872   for (auto &Src : Sources) {
4873     EVT SrcVT = Src.ShuffleVec.getValueType();
4874
4875     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4876       continue;
4877
4878     // This stage of the search produces a source with the same element type as
4879     // the original, but with a total width matching the BUILD_VECTOR output.
4880     EVT EltVT = SrcVT.getVectorElementType();
4881     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4882     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4883
4884     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4885       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4886       // We can pad out the smaller vector for free, so if it's part of a
4887       // shuffle...
4888       Src.ShuffleVec =
4889           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4890                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4891       continue;
4892     }
4893
4894     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4895
4896     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4897       // Span too large for a VEXT to cope
4898       return SDValue();
4899     }
4900
4901     if (Src.MinElt >= NumSrcElts) {
4902       // The extraction can just take the second half
4903       Src.ShuffleVec =
4904           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4905                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4906       Src.WindowBase = -NumSrcElts;
4907     } else if (Src.MaxElt < NumSrcElts) {
4908       // The extraction can just take the first half
4909       Src.ShuffleVec =
4910           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4911                       DAG.getConstant(0, dl, MVT::i64));
4912     } else {
4913       // An actual VEXT is needed
4914       SDValue VEXTSrc1 =
4915           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4916                       DAG.getConstant(0, dl, MVT::i64));
4917       SDValue VEXTSrc2 =
4918           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4919                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4920       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4921
4922       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4923                                    VEXTSrc2,
4924                                    DAG.getConstant(Imm, dl, MVT::i32));
4925       Src.WindowBase = -Src.MinElt;
4926     }
4927   }
4928
4929   // Another possible incompatibility occurs from the vector element types. We
4930   // can fix this by bitcasting the source vectors to the same type we intend
4931   // for the shuffle.
4932   for (auto &Src : Sources) {
4933     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4934     if (SrcEltTy == SmallestEltTy)
4935       continue;
4936     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4937     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4938     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4939     Src.WindowBase *= Src.WindowScale;
4940   }
4941
4942   // Final sanity check before we try to actually produce a shuffle.
4943   DEBUG(
4944     for (auto Src : Sources)
4945       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4946   );
4947
4948   // The stars all align, our next step is to produce the mask for the shuffle.
4949   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4950   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4951   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4952     SDValue Entry = Op.getOperand(i);
4953     if (Entry.getOpcode() == ISD::UNDEF)
4954       continue;
4955
4956     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4957     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4958
4959     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4960     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4961     // segment.
4962     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4963     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4964                                VT.getVectorElementType().getSizeInBits());
4965     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4966
4967     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4968     // starting at the appropriate offset.
4969     int *LaneMask = &Mask[i * ResMultiplier];
4970
4971     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4972     ExtractBase += NumElts * (Src - Sources.begin());
4973     for (int j = 0; j < LanesDefined; ++j)
4974       LaneMask[j] = ExtractBase + j;
4975   }
4976
4977   // Final check before we try to produce nonsense...
4978   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4979     return SDValue();
4980
4981   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4982   for (unsigned i = 0; i < Sources.size(); ++i)
4983     ShuffleOps[i] = Sources[i].ShuffleVec;
4984
4985   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4986                                          ShuffleOps[1], &Mask[0]);
4987   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4988 }
4989
4990 // check if an EXT instruction can handle the shuffle mask when the
4991 // vector sources of the shuffle are the same.
4992 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4993   unsigned NumElts = VT.getVectorNumElements();
4994
4995   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4996   if (M[0] < 0)
4997     return false;
4998
4999   Imm = M[0];
5000
5001   // If this is a VEXT shuffle, the immediate value is the index of the first
5002   // element.  The other shuffle indices must be the successive elements after
5003   // the first one.
5004   unsigned ExpectedElt = Imm;
5005   for (unsigned i = 1; i < NumElts; ++i) {
5006     // Increment the expected index.  If it wraps around, just follow it
5007     // back to index zero and keep going.
5008     ++ExpectedElt;
5009     if (ExpectedElt == NumElts)
5010       ExpectedElt = 0;
5011
5012     if (M[i] < 0)
5013       continue; // ignore UNDEF indices
5014     if (ExpectedElt != static_cast<unsigned>(M[i]))
5015       return false;
5016   }
5017
5018   return true;
5019 }
5020
5021 // check if an EXT instruction can handle the shuffle mask when the
5022 // vector sources of the shuffle are different.
5023 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5024                       unsigned &Imm) {
5025   // Look for the first non-undef element.
5026   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5027       [](int Elt) {return Elt >= 0;});
5028
5029   // Benefit form APInt to handle overflow when calculating expected element.
5030   unsigned NumElts = VT.getVectorNumElements();
5031   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5032   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5033   // The following shuffle indices must be the successive elements after the
5034   // first real element.
5035   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5036       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5037   if (FirstWrongElt != M.end())
5038     return false;
5039
5040   // The index of an EXT is the first element if it is not UNDEF.
5041   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5042   // value of the first element.  E.g. 
5043   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5044   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5045   // ExpectedElt is the last mask index plus 1.
5046   Imm = ExpectedElt.getZExtValue();
5047
5048   // There are two difference cases requiring to reverse input vectors.
5049   // For example, for vector <4 x i32> we have the following cases,
5050   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5051   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5052   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5053   // to reverse two input vectors.
5054   if (Imm < NumElts)
5055     ReverseEXT = true;
5056   else
5057     Imm -= NumElts;
5058
5059   return true;
5060 }
5061
5062 /// isREVMask - Check if a vector shuffle corresponds to a REV
5063 /// instruction with the specified blocksize.  (The order of the elements
5064 /// within each block of the vector is reversed.)
5065 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5066   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5067          "Only possible block sizes for REV are: 16, 32, 64");
5068
5069   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5070   if (EltSz == 64)
5071     return false;
5072
5073   unsigned NumElts = VT.getVectorNumElements();
5074   unsigned BlockElts = M[0] + 1;
5075   // If the first shuffle index is UNDEF, be optimistic.
5076   if (M[0] < 0)
5077     BlockElts = BlockSize / EltSz;
5078
5079   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5080     return false;
5081
5082   for (unsigned i = 0; i < NumElts; ++i) {
5083     if (M[i] < 0)
5084       continue; // ignore UNDEF indices
5085     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5086       return false;
5087   }
5088
5089   return true;
5090 }
5091
5092 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5093   unsigned NumElts = VT.getVectorNumElements();
5094   WhichResult = (M[0] == 0 ? 0 : 1);
5095   unsigned Idx = WhichResult * NumElts / 2;
5096   for (unsigned i = 0; i != NumElts; i += 2) {
5097     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5098         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5099       return false;
5100     Idx += 1;
5101   }
5102
5103   return true;
5104 }
5105
5106 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5107   unsigned NumElts = VT.getVectorNumElements();
5108   WhichResult = (M[0] == 0 ? 0 : 1);
5109   for (unsigned i = 0; i != NumElts; ++i) {
5110     if (M[i] < 0)
5111       continue; // ignore UNDEF indices
5112     if ((unsigned)M[i] != 2 * i + WhichResult)
5113       return false;
5114   }
5115
5116   return true;
5117 }
5118
5119 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5120   unsigned NumElts = VT.getVectorNumElements();
5121   WhichResult = (M[0] == 0 ? 0 : 1);
5122   for (unsigned i = 0; i < NumElts; i += 2) {
5123     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5124         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5125       return false;
5126   }
5127   return true;
5128 }
5129
5130 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5131 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5132 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5133 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5134   unsigned NumElts = VT.getVectorNumElements();
5135   WhichResult = (M[0] == 0 ? 0 : 1);
5136   unsigned Idx = WhichResult * NumElts / 2;
5137   for (unsigned i = 0; i != NumElts; i += 2) {
5138     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5139         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5140       return false;
5141     Idx += 1;
5142   }
5143
5144   return true;
5145 }
5146
5147 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5148 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5149 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5150 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5151   unsigned Half = VT.getVectorNumElements() / 2;
5152   WhichResult = (M[0] == 0 ? 0 : 1);
5153   for (unsigned j = 0; j != 2; ++j) {
5154     unsigned Idx = WhichResult;
5155     for (unsigned i = 0; i != Half; ++i) {
5156       int MIdx = M[i + j * Half];
5157       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5158         return false;
5159       Idx += 2;
5160     }
5161   }
5162
5163   return true;
5164 }
5165
5166 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5167 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5168 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5169 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5170   unsigned NumElts = VT.getVectorNumElements();
5171   WhichResult = (M[0] == 0 ? 0 : 1);
5172   for (unsigned i = 0; i < NumElts; i += 2) {
5173     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5174         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5175       return false;
5176   }
5177   return true;
5178 }
5179
5180 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5181                       bool &DstIsLeft, int &Anomaly) {
5182   if (M.size() != static_cast<size_t>(NumInputElements))
5183     return false;
5184
5185   int NumLHSMatch = 0, NumRHSMatch = 0;
5186   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5187
5188   for (int i = 0; i < NumInputElements; ++i) {
5189     if (M[i] == -1) {
5190       ++NumLHSMatch;
5191       ++NumRHSMatch;
5192       continue;
5193     }
5194
5195     if (M[i] == i)
5196       ++NumLHSMatch;
5197     else
5198       LastLHSMismatch = i;
5199
5200     if (M[i] == i + NumInputElements)
5201       ++NumRHSMatch;
5202     else
5203       LastRHSMismatch = i;
5204   }
5205
5206   if (NumLHSMatch == NumInputElements - 1) {
5207     DstIsLeft = true;
5208     Anomaly = LastLHSMismatch;
5209     return true;
5210   } else if (NumRHSMatch == NumInputElements - 1) {
5211     DstIsLeft = false;
5212     Anomaly = LastRHSMismatch;
5213     return true;
5214   }
5215
5216   return false;
5217 }
5218
5219 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5220   if (VT.getSizeInBits() != 128)
5221     return false;
5222
5223   unsigned NumElts = VT.getVectorNumElements();
5224
5225   for (int I = 0, E = NumElts / 2; I != E; I++) {
5226     if (Mask[I] != I)
5227       return false;
5228   }
5229
5230   int Offset = NumElts / 2;
5231   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5232     if (Mask[I] != I + SplitLHS * Offset)
5233       return false;
5234   }
5235
5236   return true;
5237 }
5238
5239 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5240   SDLoc DL(Op);
5241   EVT VT = Op.getValueType();
5242   SDValue V0 = Op.getOperand(0);
5243   SDValue V1 = Op.getOperand(1);
5244   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5245
5246   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5247       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5248     return SDValue();
5249
5250   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5251
5252   if (!isConcatMask(Mask, VT, SplitV0))
5253     return SDValue();
5254
5255   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5256                                 VT.getVectorNumElements() / 2);
5257   if (SplitV0) {
5258     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5259                      DAG.getConstant(0, DL, MVT::i64));
5260   }
5261   if (V1.getValueType().getSizeInBits() == 128) {
5262     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5263                      DAG.getConstant(0, DL, MVT::i64));
5264   }
5265   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5266 }
5267
5268 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5269 /// the specified operations to build the shuffle.
5270 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5271                                       SDValue RHS, SelectionDAG &DAG,
5272                                       SDLoc dl) {
5273   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5274   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5275   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5276
5277   enum {
5278     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5279     OP_VREV,
5280     OP_VDUP0,
5281     OP_VDUP1,
5282     OP_VDUP2,
5283     OP_VDUP3,
5284     OP_VEXT1,
5285     OP_VEXT2,
5286     OP_VEXT3,
5287     OP_VUZPL, // VUZP, left result
5288     OP_VUZPR, // VUZP, right result
5289     OP_VZIPL, // VZIP, left result
5290     OP_VZIPR, // VZIP, right result
5291     OP_VTRNL, // VTRN, left result
5292     OP_VTRNR  // VTRN, right result
5293   };
5294
5295   if (OpNum == OP_COPY) {
5296     if (LHSID == (1 * 9 + 2) * 9 + 3)
5297       return LHS;
5298     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5299     return RHS;
5300   }
5301
5302   SDValue OpLHS, OpRHS;
5303   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5304   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5305   EVT VT = OpLHS.getValueType();
5306
5307   switch (OpNum) {
5308   default:
5309     llvm_unreachable("Unknown shuffle opcode!");
5310   case OP_VREV:
5311     // VREV divides the vector in half and swaps within the half.
5312     if (VT.getVectorElementType() == MVT::i32 ||
5313         VT.getVectorElementType() == MVT::f32)
5314       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5315     // vrev <4 x i16> -> REV32
5316     if (VT.getVectorElementType() == MVT::i16 ||
5317         VT.getVectorElementType() == MVT::f16)
5318       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5319     // vrev <4 x i8> -> REV16
5320     assert(VT.getVectorElementType() == MVT::i8);
5321     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5322   case OP_VDUP0:
5323   case OP_VDUP1:
5324   case OP_VDUP2:
5325   case OP_VDUP3: {
5326     EVT EltTy = VT.getVectorElementType();
5327     unsigned Opcode;
5328     if (EltTy == MVT::i8)
5329       Opcode = AArch64ISD::DUPLANE8;
5330     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5331       Opcode = AArch64ISD::DUPLANE16;
5332     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5333       Opcode = AArch64ISD::DUPLANE32;
5334     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5335       Opcode = AArch64ISD::DUPLANE64;
5336     else
5337       llvm_unreachable("Invalid vector element type?");
5338
5339     if (VT.getSizeInBits() == 64)
5340       OpLHS = WidenVector(OpLHS, DAG);
5341     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5342     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5343   }
5344   case OP_VEXT1:
5345   case OP_VEXT2:
5346   case OP_VEXT3: {
5347     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5348     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5349                        DAG.getConstant(Imm, dl, MVT::i32));
5350   }
5351   case OP_VUZPL:
5352     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5353                        OpRHS);
5354   case OP_VUZPR:
5355     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5356                        OpRHS);
5357   case OP_VZIPL:
5358     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5359                        OpRHS);
5360   case OP_VZIPR:
5361     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5362                        OpRHS);
5363   case OP_VTRNL:
5364     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5365                        OpRHS);
5366   case OP_VTRNR:
5367     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5368                        OpRHS);
5369   }
5370 }
5371
5372 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5373                            SelectionDAG &DAG) {
5374   // Check to see if we can use the TBL instruction.
5375   SDValue V1 = Op.getOperand(0);
5376   SDValue V2 = Op.getOperand(1);
5377   SDLoc DL(Op);
5378
5379   EVT EltVT = Op.getValueType().getVectorElementType();
5380   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5381
5382   SmallVector<SDValue, 8> TBLMask;
5383   for (int Val : ShuffleMask) {
5384     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5385       unsigned Offset = Byte + Val * BytesPerElt;
5386       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5387     }
5388   }
5389
5390   MVT IndexVT = MVT::v8i8;
5391   unsigned IndexLen = 8;
5392   if (Op.getValueType().getSizeInBits() == 128) {
5393     IndexVT = MVT::v16i8;
5394     IndexLen = 16;
5395   }
5396
5397   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5398   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5399
5400   SDValue Shuffle;
5401   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5402     if (IndexLen == 8)
5403       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5404     Shuffle = DAG.getNode(
5405         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5406         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5407         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5408                     makeArrayRef(TBLMask.data(), IndexLen)));
5409   } else {
5410     if (IndexLen == 8) {
5411       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5412       Shuffle = DAG.getNode(
5413           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5414           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5415           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5416                       makeArrayRef(TBLMask.data(), IndexLen)));
5417     } else {
5418       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5419       // cannot currently represent the register constraints on the input
5420       // table registers.
5421       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5422       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5423       //                               &TBLMask[0], IndexLen));
5424       Shuffle = DAG.getNode(
5425           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5426           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5427           V1Cst, V2Cst,
5428           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5429                       makeArrayRef(TBLMask.data(), IndexLen)));
5430     }
5431   }
5432   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5433 }
5434
5435 static unsigned getDUPLANEOp(EVT EltType) {
5436   if (EltType == MVT::i8)
5437     return AArch64ISD::DUPLANE8;
5438   if (EltType == MVT::i16 || EltType == MVT::f16)
5439     return AArch64ISD::DUPLANE16;
5440   if (EltType == MVT::i32 || EltType == MVT::f32)
5441     return AArch64ISD::DUPLANE32;
5442   if (EltType == MVT::i64 || EltType == MVT::f64)
5443     return AArch64ISD::DUPLANE64;
5444
5445   llvm_unreachable("Invalid vector element type?");
5446 }
5447
5448 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5449                                                    SelectionDAG &DAG) const {
5450   SDLoc dl(Op);
5451   EVT VT = Op.getValueType();
5452
5453   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5454
5455   // Convert shuffles that are directly supported on NEON to target-specific
5456   // DAG nodes, instead of keeping them as shuffles and matching them again
5457   // during code selection.  This is more efficient and avoids the possibility
5458   // of inconsistencies between legalization and selection.
5459   ArrayRef<int> ShuffleMask = SVN->getMask();
5460
5461   SDValue V1 = Op.getOperand(0);
5462   SDValue V2 = Op.getOperand(1);
5463
5464   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5465                                        V1.getValueType().getSimpleVT())) {
5466     int Lane = SVN->getSplatIndex();
5467     // If this is undef splat, generate it via "just" vdup, if possible.
5468     if (Lane == -1)
5469       Lane = 0;
5470
5471     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5472       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5473                          V1.getOperand(0));
5474     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5475     // constant. If so, we can just reference the lane's definition directly.
5476     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5477         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5478       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5479
5480     // Otherwise, duplicate from the lane of the input vector.
5481     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5482
5483     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5484     // to make a vector of the same size as this SHUFFLE. We can ignore the
5485     // extract entirely, and canonicalise the concat using WidenVector.
5486     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5487       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5488       V1 = V1.getOperand(0);
5489     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5490       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5491       Lane -= Idx * VT.getVectorNumElements() / 2;
5492       V1 = WidenVector(V1.getOperand(Idx), DAG);
5493     } else if (VT.getSizeInBits() == 64)
5494       V1 = WidenVector(V1, DAG);
5495
5496     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5497   }
5498
5499   if (isREVMask(ShuffleMask, VT, 64))
5500     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5501   if (isREVMask(ShuffleMask, VT, 32))
5502     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5503   if (isREVMask(ShuffleMask, VT, 16))
5504     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5505
5506   bool ReverseEXT = false;
5507   unsigned Imm;
5508   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5509     if (ReverseEXT)
5510       std::swap(V1, V2);
5511     Imm *= getExtFactor(V1);
5512     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5513                        DAG.getConstant(Imm, dl, MVT::i32));
5514   } else if (V2->getOpcode() == ISD::UNDEF &&
5515              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5516     Imm *= getExtFactor(V1);
5517     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5518                        DAG.getConstant(Imm, dl, MVT::i32));
5519   }
5520
5521   unsigned WhichResult;
5522   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5523     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5524     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5525   }
5526   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5527     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5528     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5529   }
5530   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5531     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5532     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5533   }
5534
5535   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5536     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5537     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5538   }
5539   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5540     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5541     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5542   }
5543   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5544     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5545     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5546   }
5547
5548   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5549   if (Concat.getNode())
5550     return Concat;
5551
5552   bool DstIsLeft;
5553   int Anomaly;
5554   int NumInputElements = V1.getValueType().getVectorNumElements();
5555   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5556     SDValue DstVec = DstIsLeft ? V1 : V2;
5557     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5558
5559     SDValue SrcVec = V1;
5560     int SrcLane = ShuffleMask[Anomaly];
5561     if (SrcLane >= NumInputElements) {
5562       SrcVec = V2;
5563       SrcLane -= VT.getVectorNumElements();
5564     }
5565     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5566
5567     EVT ScalarVT = VT.getVectorElementType();
5568
5569     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5570       ScalarVT = MVT::i32;
5571
5572     return DAG.getNode(
5573         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5574         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5575         DstLaneV);
5576   }
5577
5578   // If the shuffle is not directly supported and it has 4 elements, use
5579   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5580   unsigned NumElts = VT.getVectorNumElements();
5581   if (NumElts == 4) {
5582     unsigned PFIndexes[4];
5583     for (unsigned i = 0; i != 4; ++i) {
5584       if (ShuffleMask[i] < 0)
5585         PFIndexes[i] = 8;
5586       else
5587         PFIndexes[i] = ShuffleMask[i];
5588     }
5589
5590     // Compute the index in the perfect shuffle table.
5591     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5592                             PFIndexes[2] * 9 + PFIndexes[3];
5593     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5594     unsigned Cost = (PFEntry >> 30);
5595
5596     if (Cost <= 4)
5597       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5598   }
5599
5600   return GenerateTBL(Op, ShuffleMask, DAG);
5601 }
5602
5603 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5604                                APInt &UndefBits) {
5605   EVT VT = BVN->getValueType(0);
5606   APInt SplatBits, SplatUndef;
5607   unsigned SplatBitSize;
5608   bool HasAnyUndefs;
5609   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5610     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5611
5612     for (unsigned i = 0; i < NumSplats; ++i) {
5613       CnstBits <<= SplatBitSize;
5614       UndefBits <<= SplatBitSize;
5615       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5616       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5617     }
5618
5619     return true;
5620   }
5621
5622   return false;
5623 }
5624
5625 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5626                                               SelectionDAG &DAG) const {
5627   BuildVectorSDNode *BVN =
5628       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5629   SDValue LHS = Op.getOperand(0);
5630   SDLoc dl(Op);
5631   EVT VT = Op.getValueType();
5632
5633   if (!BVN)
5634     return Op;
5635
5636   APInt CnstBits(VT.getSizeInBits(), 0);
5637   APInt UndefBits(VT.getSizeInBits(), 0);
5638   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5639     // We only have BIC vector immediate instruction, which is and-not.
5640     CnstBits = ~CnstBits;
5641
5642     // We make use of a little bit of goto ickiness in order to avoid having to
5643     // duplicate the immediate matching logic for the undef toggled case.
5644     bool SecondTry = false;
5645   AttemptModImm:
5646
5647     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5648       CnstBits = CnstBits.zextOrTrunc(64);
5649       uint64_t CnstVal = CnstBits.getZExtValue();
5650
5651       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5652         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5653         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5654         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5655                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5656                                   DAG.getConstant(0, dl, MVT::i32));
5657         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5658       }
5659
5660       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5661         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5662         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5663         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5664                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5665                                   DAG.getConstant(8, dl, MVT::i32));
5666         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5667       }
5668
5669       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5670         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5671         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5672         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5673                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5674                                   DAG.getConstant(16, dl, MVT::i32));
5675         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5676       }
5677
5678       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5679         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5680         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5681         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5682                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5683                                   DAG.getConstant(24, dl, MVT::i32));
5684         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5685       }
5686
5687       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5688         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5689         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5690         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5691                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5692                                   DAG.getConstant(0, dl, MVT::i32));
5693         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5694       }
5695
5696       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5697         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5698         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5699         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5700                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5701                                   DAG.getConstant(8, dl, MVT::i32));
5702         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5703       }
5704     }
5705
5706     if (SecondTry)
5707       goto FailedModImm;
5708     SecondTry = true;
5709     CnstBits = ~UndefBits;
5710     goto AttemptModImm;
5711   }
5712
5713 // We can always fall back to a non-immediate AND.
5714 FailedModImm:
5715   return Op;
5716 }
5717
5718 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5719 // consists of only the same constant int value, returned in reference arg
5720 // ConstVal
5721 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5722                                      uint64_t &ConstVal) {
5723   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5724   if (!Bvec)
5725     return false;
5726   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5727   if (!FirstElt)
5728     return false;
5729   EVT VT = Bvec->getValueType(0);
5730   unsigned NumElts = VT.getVectorNumElements();
5731   for (unsigned i = 1; i < NumElts; ++i)
5732     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5733       return false;
5734   ConstVal = FirstElt->getZExtValue();
5735   return true;
5736 }
5737
5738 static unsigned getIntrinsicID(const SDNode *N) {
5739   unsigned Opcode = N->getOpcode();
5740   switch (Opcode) {
5741   default:
5742     return Intrinsic::not_intrinsic;
5743   case ISD::INTRINSIC_WO_CHAIN: {
5744     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5745     if (IID < Intrinsic::num_intrinsics)
5746       return IID;
5747     return Intrinsic::not_intrinsic;
5748   }
5749   }
5750 }
5751
5752 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5753 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5754 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5755 // Also, logical shift right -> sri, with the same structure.
5756 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5757   EVT VT = N->getValueType(0);
5758
5759   if (!VT.isVector())
5760     return SDValue();
5761
5762   SDLoc DL(N);
5763
5764   // Is the first op an AND?
5765   const SDValue And = N->getOperand(0);
5766   if (And.getOpcode() != ISD::AND)
5767     return SDValue();
5768
5769   // Is the second op an shl or lshr?
5770   SDValue Shift = N->getOperand(1);
5771   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5772   // or AArch64ISD::VLSHR vector, #shift
5773   unsigned ShiftOpc = Shift.getOpcode();
5774   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5775     return SDValue();
5776   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5777
5778   // Is the shift amount constant?
5779   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5780   if (!C2node)
5781     return SDValue();
5782
5783   // Is the and mask vector all constant?
5784   uint64_t C1;
5785   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5786     return SDValue();
5787
5788   // Is C1 == ~C2, taking into account how much one can shift elements of a
5789   // particular size?
5790   uint64_t C2 = C2node->getZExtValue();
5791   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5792   if (C2 > ElemSizeInBits)
5793     return SDValue();
5794   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5795   if ((C1 & ElemMask) != (~C2 & ElemMask))
5796     return SDValue();
5797
5798   SDValue X = And.getOperand(0);
5799   SDValue Y = Shift.getOperand(0);
5800
5801   unsigned Intrin =
5802       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5803   SDValue ResultSLI =
5804       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5805                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5806                   Shift.getOperand(1));
5807
5808   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5809   DEBUG(N->dump(&DAG));
5810   DEBUG(dbgs() << "into: \n");
5811   DEBUG(ResultSLI->dump(&DAG));
5812
5813   ++NumShiftInserts;
5814   return ResultSLI;
5815 }
5816
5817 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5818                                              SelectionDAG &DAG) const {
5819   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5820   if (EnableAArch64SlrGeneration) {
5821     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5822     if (Res.getNode())
5823       return Res;
5824   }
5825
5826   BuildVectorSDNode *BVN =
5827       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5828   SDValue LHS = Op.getOperand(1);
5829   SDLoc dl(Op);
5830   EVT VT = Op.getValueType();
5831
5832   // OR commutes, so try swapping the operands.
5833   if (!BVN) {
5834     LHS = Op.getOperand(0);
5835     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5836   }
5837   if (!BVN)
5838     return Op;
5839
5840   APInt CnstBits(VT.getSizeInBits(), 0);
5841   APInt UndefBits(VT.getSizeInBits(), 0);
5842   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5843     // We make use of a little bit of goto ickiness in order to avoid having to
5844     // duplicate the immediate matching logic for the undef toggled case.
5845     bool SecondTry = false;
5846   AttemptModImm:
5847
5848     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5849       CnstBits = CnstBits.zextOrTrunc(64);
5850       uint64_t CnstVal = CnstBits.getZExtValue();
5851
5852       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5853         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5854         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5855         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5856                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5857                                   DAG.getConstant(0, dl, MVT::i32));
5858         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5859       }
5860
5861       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5862         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5863         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5864         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5865                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5866                                   DAG.getConstant(8, dl, MVT::i32));
5867         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5868       }
5869
5870       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5871         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5872         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5873         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5874                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5875                                   DAG.getConstant(16, dl, MVT::i32));
5876         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5877       }
5878
5879       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5880         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5881         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5882         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5883                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5884                                   DAG.getConstant(24, dl, MVT::i32));
5885         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5886       }
5887
5888       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5889         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5890         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5891         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5892                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5893                                   DAG.getConstant(0, dl, MVT::i32));
5894         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5895       }
5896
5897       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5898         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5899         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5900         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5901                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5902                                   DAG.getConstant(8, dl, MVT::i32));
5903         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5904       }
5905     }
5906
5907     if (SecondTry)
5908       goto FailedModImm;
5909     SecondTry = true;
5910     CnstBits = UndefBits;
5911     goto AttemptModImm;
5912   }
5913
5914 // We can always fall back to a non-immediate OR.
5915 FailedModImm:
5916   return Op;
5917 }
5918
5919 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5920 // be truncated to fit element width.
5921 static SDValue NormalizeBuildVector(SDValue Op,
5922                                     SelectionDAG &DAG) {
5923   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5924   SDLoc dl(Op);
5925   EVT VT = Op.getValueType();
5926   EVT EltTy= VT.getVectorElementType();
5927
5928   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5929     return Op;
5930
5931   SmallVector<SDValue, 16> Ops;
5932   for (SDValue Lane : Op->ops()) {
5933     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5934       APInt LowBits(EltTy.getSizeInBits(),
5935                     CstLane->getZExtValue());
5936       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5937     }
5938     Ops.push_back(Lane);
5939   }
5940   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5941 }
5942
5943 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5944                                                  SelectionDAG &DAG) const {
5945   SDLoc dl(Op);
5946   EVT VT = Op.getValueType();
5947   Op = NormalizeBuildVector(Op, DAG);
5948   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5949
5950   APInt CnstBits(VT.getSizeInBits(), 0);
5951   APInt UndefBits(VT.getSizeInBits(), 0);
5952   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5953     // We make use of a little bit of goto ickiness in order to avoid having to
5954     // duplicate the immediate matching logic for the undef toggled case.
5955     bool SecondTry = false;
5956   AttemptModImm:
5957
5958     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5959       CnstBits = CnstBits.zextOrTrunc(64);
5960       uint64_t CnstVal = CnstBits.getZExtValue();
5961
5962       // Certain magic vector constants (used to express things like NOT
5963       // and NEG) are passed through unmodified.  This allows codegen patterns
5964       // for these operations to match.  Special-purpose patterns will lower
5965       // these immediates to MOVIs if it proves necessary.
5966       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5967         return Op;
5968
5969       // The many faces of MOVI...
5970       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5971         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5972         if (VT.getSizeInBits() == 128) {
5973           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5974                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5975           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5976         }
5977
5978         // Support the V64 version via subregister insertion.
5979         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5980                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5981         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5982       }
5983
5984       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5985         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5986         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5987         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5988                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5989                                   DAG.getConstant(0, dl, MVT::i32));
5990         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5991       }
5992
5993       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5994         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5995         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5996         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5997                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5998                                   DAG.getConstant(8, dl, MVT::i32));
5999         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6000       }
6001
6002       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6003         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6004         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6005         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6006                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6007                                   DAG.getConstant(16, dl, MVT::i32));
6008         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6009       }
6010
6011       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6012         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6013         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6014         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6015                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6016                                   DAG.getConstant(24, dl, MVT::i32));
6017         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6018       }
6019
6020       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6021         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6022         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6023         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6024                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6025                                   DAG.getConstant(0, dl, MVT::i32));
6026         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6027       }
6028
6029       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6030         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6031         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6032         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6033                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6034                                   DAG.getConstant(8, dl, MVT::i32));
6035         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6036       }
6037
6038       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6039         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6040         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6041         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6042                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6043                                   DAG.getConstant(264, dl, MVT::i32));
6044         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6045       }
6046
6047       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6048         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6049         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6050         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6051                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6052                                   DAG.getConstant(272, dl, MVT::i32));
6053         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6054       }
6055
6056       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6057         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6058         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6059         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6060                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6061         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6062       }
6063
6064       // The few faces of FMOV...
6065       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6066         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6067         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6068         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6069                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6070         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6071       }
6072
6073       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6074           VT.getSizeInBits() == 128) {
6075         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6076         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6077                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6078         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6079       }
6080
6081       // The many faces of MVNI...
6082       CnstVal = ~CnstVal;
6083       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6084         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6085         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6086         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6087                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6088                                   DAG.getConstant(0, dl, MVT::i32));
6089         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6090       }
6091
6092       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6093         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6094         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6095         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6096                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6097                                   DAG.getConstant(8, dl, MVT::i32));
6098         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6099       }
6100
6101       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6102         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6103         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6104         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6105                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6106                                   DAG.getConstant(16, dl, MVT::i32));
6107         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6108       }
6109
6110       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6111         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6112         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6113         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6114                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6115                                   DAG.getConstant(24, dl, MVT::i32));
6116         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6117       }
6118
6119       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6120         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6121         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6122         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6123                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6124                                   DAG.getConstant(0, dl, MVT::i32));
6125         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6126       }
6127
6128       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6129         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6130         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6131         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6132                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6133                                   DAG.getConstant(8, dl, MVT::i32));
6134         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6135       }
6136
6137       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6138         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6139         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6140         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6141                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6142                                   DAG.getConstant(264, dl, MVT::i32));
6143         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6144       }
6145
6146       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6147         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6148         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6149         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6150                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6151                                   DAG.getConstant(272, dl, MVT::i32));
6152         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6153       }
6154     }
6155
6156     if (SecondTry)
6157       goto FailedModImm;
6158     SecondTry = true;
6159     CnstBits = UndefBits;
6160     goto AttemptModImm;
6161   }
6162 FailedModImm:
6163
6164   // Scan through the operands to find some interesting properties we can
6165   // exploit:
6166   //   1) If only one value is used, we can use a DUP, or
6167   //   2) if only the low element is not undef, we can just insert that, or
6168   //   3) if only one constant value is used (w/ some non-constant lanes),
6169   //      we can splat the constant value into the whole vector then fill
6170   //      in the non-constant lanes.
6171   //   4) FIXME: If different constant values are used, but we can intelligently
6172   //             select the values we'll be overwriting for the non-constant
6173   //             lanes such that we can directly materialize the vector
6174   //             some other way (MOVI, e.g.), we can be sneaky.
6175   unsigned NumElts = VT.getVectorNumElements();
6176   bool isOnlyLowElement = true;
6177   bool usesOnlyOneValue = true;
6178   bool usesOnlyOneConstantValue = true;
6179   bool isConstant = true;
6180   unsigned NumConstantLanes = 0;
6181   SDValue Value;
6182   SDValue ConstantValue;
6183   for (unsigned i = 0; i < NumElts; ++i) {
6184     SDValue V = Op.getOperand(i);
6185     if (V.getOpcode() == ISD::UNDEF)
6186       continue;
6187     if (i > 0)
6188       isOnlyLowElement = false;
6189     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6190       isConstant = false;
6191
6192     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6193       ++NumConstantLanes;
6194       if (!ConstantValue.getNode())
6195         ConstantValue = V;
6196       else if (ConstantValue != V)
6197         usesOnlyOneConstantValue = false;
6198     }
6199
6200     if (!Value.getNode())
6201       Value = V;
6202     else if (V != Value)
6203       usesOnlyOneValue = false;
6204   }
6205
6206   if (!Value.getNode())
6207     return DAG.getUNDEF(VT);
6208
6209   if (isOnlyLowElement)
6210     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6211
6212   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6213   // i32 and try again.
6214   if (usesOnlyOneValue) {
6215     if (!isConstant) {
6216       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6217           Value.getValueType() != VT)
6218         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6219
6220       // This is actually a DUPLANExx operation, which keeps everything vectory.
6221
6222       // DUPLANE works on 128-bit vectors, widen it if necessary.
6223       SDValue Lane = Value.getOperand(1);
6224       Value = Value.getOperand(0);
6225       if (Value.getValueType().getSizeInBits() == 64)
6226         Value = WidenVector(Value, DAG);
6227
6228       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6229       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6230     }
6231
6232     if (VT.getVectorElementType().isFloatingPoint()) {
6233       SmallVector<SDValue, 8> Ops;
6234       EVT EltTy = VT.getVectorElementType();
6235       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6236               "Unsupported floating-point vector type");
6237       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6238       for (unsigned i = 0; i < NumElts; ++i)
6239         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6240       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6241       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6242       Val = LowerBUILD_VECTOR(Val, DAG);
6243       if (Val.getNode())
6244         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6245     }
6246   }
6247
6248   // If there was only one constant value used and for more than one lane,
6249   // start by splatting that value, then replace the non-constant lanes. This
6250   // is better than the default, which will perform a separate initialization
6251   // for each lane.
6252   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6253     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6254     // Now insert the non-constant lanes.
6255     for (unsigned i = 0; i < NumElts; ++i) {
6256       SDValue V = Op.getOperand(i);
6257       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6258       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6259         // Note that type legalization likely mucked about with the VT of the
6260         // source operand, so we may have to convert it here before inserting.
6261         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6262       }
6263     }
6264     return Val;
6265   }
6266
6267   // If all elements are constants and the case above didn't get hit, fall back
6268   // to the default expansion, which will generate a load from the constant
6269   // pool.
6270   if (isConstant)
6271     return SDValue();
6272
6273   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6274   if (NumElts >= 4) {
6275     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6276       return shuffle;
6277   }
6278
6279   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6280   // know the default expansion would otherwise fall back on something even
6281   // worse. For a vector with one or two non-undef values, that's
6282   // scalar_to_vector for the elements followed by a shuffle (provided the
6283   // shuffle is valid for the target) and materialization element by element
6284   // on the stack followed by a load for everything else.
6285   if (!isConstant && !usesOnlyOneValue) {
6286     SDValue Vec = DAG.getUNDEF(VT);
6287     SDValue Op0 = Op.getOperand(0);
6288     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6289     unsigned i = 0;
6290     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6291     // a) Avoid a RMW dependency on the full vector register, and
6292     // b) Allow the register coalescer to fold away the copy if the
6293     //    value is already in an S or D register.
6294     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6295     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6296     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6297         (ElemSize == 32 || ElemSize == 64)) {
6298       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6299       MachineSDNode *N =
6300           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6301                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6302       Vec = SDValue(N, 0);
6303       ++i;
6304     }
6305     for (; i < NumElts; ++i) {
6306       SDValue V = Op.getOperand(i);
6307       if (V.getOpcode() == ISD::UNDEF)
6308         continue;
6309       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6310       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6311     }
6312     return Vec;
6313   }
6314
6315   // Just use the default expansion. We failed to find a better alternative.
6316   return SDValue();
6317 }
6318
6319 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6320                                                       SelectionDAG &DAG) const {
6321   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6322
6323   // Check for non-constant or out of range lane.
6324   EVT VT = Op.getOperand(0).getValueType();
6325   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6326   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6327     return SDValue();
6328
6329
6330   // Insertion/extraction are legal for V128 types.
6331   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6332       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6333       VT == MVT::v8f16)
6334     return Op;
6335
6336   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6337       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6338     return SDValue();
6339
6340   // For V64 types, we perform insertion by expanding the value
6341   // to a V128 type and perform the insertion on that.
6342   SDLoc DL(Op);
6343   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6344   EVT WideTy = WideVec.getValueType();
6345
6346   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6347                              Op.getOperand(1), Op.getOperand(2));
6348   // Re-narrow the resultant vector.
6349   return NarrowVector(Node, DAG);
6350 }
6351
6352 SDValue
6353 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6354                                                SelectionDAG &DAG) const {
6355   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6356
6357   // Check for non-constant or out of range lane.
6358   EVT VT = Op.getOperand(0).getValueType();
6359   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6360   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6361     return SDValue();
6362
6363
6364   // Insertion/extraction are legal for V128 types.
6365   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6366       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6367       VT == MVT::v8f16)
6368     return Op;
6369
6370   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6371       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6372     return SDValue();
6373
6374   // For V64 types, we perform extraction by expanding the value
6375   // to a V128 type and perform the extraction on that.
6376   SDLoc DL(Op);
6377   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6378   EVT WideTy = WideVec.getValueType();
6379
6380   EVT ExtrTy = WideTy.getVectorElementType();
6381   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6382     ExtrTy = MVT::i32;
6383
6384   // For extractions, we just return the result directly.
6385   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6386                      Op.getOperand(1));
6387 }
6388
6389 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6390                                                       SelectionDAG &DAG) const {
6391   EVT VT = Op.getOperand(0).getValueType();
6392   SDLoc dl(Op);
6393   // Just in case...
6394   if (!VT.isVector())
6395     return SDValue();
6396
6397   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6398   if (!Cst)
6399     return SDValue();
6400   unsigned Val = Cst->getZExtValue();
6401
6402   unsigned Size = Op.getValueType().getSizeInBits();
6403   if (Val == 0) {
6404     switch (Size) {
6405     case 8:
6406       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6407                                         Op.getOperand(0));
6408     case 16:
6409       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6410                                         Op.getOperand(0));
6411     case 32:
6412       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6413                                         Op.getOperand(0));
6414     case 64:
6415       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6416                                         Op.getOperand(0));
6417     default:
6418       llvm_unreachable("Unexpected vector type in extract_subvector!");
6419     }
6420   }
6421   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6422   // that directly.
6423   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6424     return Op;
6425
6426   return SDValue();
6427 }
6428
6429 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6430                                                EVT VT) const {
6431   if (VT.getVectorNumElements() == 4 &&
6432       (VT.is128BitVector() || VT.is64BitVector())) {
6433     unsigned PFIndexes[4];
6434     for (unsigned i = 0; i != 4; ++i) {
6435       if (M[i] < 0)
6436         PFIndexes[i] = 8;
6437       else
6438         PFIndexes[i] = M[i];
6439     }
6440
6441     // Compute the index in the perfect shuffle table.
6442     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6443                             PFIndexes[2] * 9 + PFIndexes[3];
6444     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6445     unsigned Cost = (PFEntry >> 30);
6446
6447     if (Cost <= 4)
6448       return true;
6449   }
6450
6451   bool DummyBool;
6452   int DummyInt;
6453   unsigned DummyUnsigned;
6454
6455   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6456           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6457           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6458           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6459           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6460           isZIPMask(M, VT, DummyUnsigned) ||
6461           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6462           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6463           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6464           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6465           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6466 }
6467
6468 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6469 /// operand of a vector shift operation, where all the elements of the
6470 /// build_vector must have the same constant integer value.
6471 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6472   // Ignore bit_converts.
6473   while (Op.getOpcode() == ISD::BITCAST)
6474     Op = Op.getOperand(0);
6475   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6476   APInt SplatBits, SplatUndef;
6477   unsigned SplatBitSize;
6478   bool HasAnyUndefs;
6479   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6480                                     HasAnyUndefs, ElementBits) ||
6481       SplatBitSize > ElementBits)
6482     return false;
6483   Cnt = SplatBits.getSExtValue();
6484   return true;
6485 }
6486
6487 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6488 /// operand of a vector shift left operation.  That value must be in the range:
6489 ///   0 <= Value < ElementBits for a left shift; or
6490 ///   0 <= Value <= ElementBits for a long left shift.
6491 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6492   assert(VT.isVector() && "vector shift count is not a vector type");
6493   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6494   if (!getVShiftImm(Op, ElementBits, Cnt))
6495     return false;
6496   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6497 }
6498
6499 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6500 /// operand of a vector shift right operation. The value must be in the range:
6501 ///   1 <= Value <= ElementBits for a right shift; or
6502 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6503   assert(VT.isVector() && "vector shift count is not a vector type");
6504   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6505   if (!getVShiftImm(Op, ElementBits, Cnt))
6506     return false;
6507   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6508 }
6509
6510 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6511                                                       SelectionDAG &DAG) const {
6512   EVT VT = Op.getValueType();
6513   SDLoc DL(Op);
6514   int64_t Cnt;
6515
6516   if (!Op.getOperand(1).getValueType().isVector())
6517     return Op;
6518   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6519
6520   switch (Op.getOpcode()) {
6521   default:
6522     llvm_unreachable("unexpected shift opcode");
6523
6524   case ISD::SHL:
6525     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6526       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6527                          DAG.getConstant(Cnt, DL, MVT::i32));
6528     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6529                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6530                                        MVT::i32),
6531                        Op.getOperand(0), Op.getOperand(1));
6532   case ISD::SRA:
6533   case ISD::SRL:
6534     // Right shift immediate
6535     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6536       unsigned Opc =
6537           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6538       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6539                          DAG.getConstant(Cnt, DL, MVT::i32));
6540     }
6541
6542     // Right shift register.  Note, there is not a shift right register
6543     // instruction, but the shift left register instruction takes a signed
6544     // value, where negative numbers specify a right shift.
6545     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6546                                                 : Intrinsic::aarch64_neon_ushl;
6547     // negate the shift amount
6548     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6549     SDValue NegShiftLeft =
6550         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6551                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6552                     NegShift);
6553     return NegShiftLeft;
6554   }
6555
6556   return SDValue();
6557 }
6558
6559 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6560                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6561                                     SDLoc dl, SelectionDAG &DAG) {
6562   EVT SrcVT = LHS.getValueType();
6563   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6564          "function only supposed to emit natural comparisons");
6565
6566   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6567   APInt CnstBits(VT.getSizeInBits(), 0);
6568   APInt UndefBits(VT.getSizeInBits(), 0);
6569   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6570   bool IsZero = IsCnst && (CnstBits == 0);
6571
6572   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6573     switch (CC) {
6574     default:
6575       return SDValue();
6576     case AArch64CC::NE: {
6577       SDValue Fcmeq;
6578       if (IsZero)
6579         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6580       else
6581         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6582       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6583     }
6584     case AArch64CC::EQ:
6585       if (IsZero)
6586         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6587       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6588     case AArch64CC::GE:
6589       if (IsZero)
6590         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6591       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6592     case AArch64CC::GT:
6593       if (IsZero)
6594         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6595       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6596     case AArch64CC::LS:
6597       if (IsZero)
6598         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6599       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6600     case AArch64CC::LT:
6601       if (!NoNans)
6602         return SDValue();
6603     // If we ignore NaNs then we can use to the MI implementation.
6604     // Fallthrough.
6605     case AArch64CC::MI:
6606       if (IsZero)
6607         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6608       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6609     }
6610   }
6611
6612   switch (CC) {
6613   default:
6614     return SDValue();
6615   case AArch64CC::NE: {
6616     SDValue Cmeq;
6617     if (IsZero)
6618       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6619     else
6620       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6621     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6622   }
6623   case AArch64CC::EQ:
6624     if (IsZero)
6625       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6626     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6627   case AArch64CC::GE:
6628     if (IsZero)
6629       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6630     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6631   case AArch64CC::GT:
6632     if (IsZero)
6633       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6634     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6635   case AArch64CC::LE:
6636     if (IsZero)
6637       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6638     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6639   case AArch64CC::LS:
6640     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6641   case AArch64CC::LO:
6642     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6643   case AArch64CC::LT:
6644     if (IsZero)
6645       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6646     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6647   case AArch64CC::HI:
6648     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6649   case AArch64CC::HS:
6650     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6651   }
6652 }
6653
6654 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6655                                            SelectionDAG &DAG) const {
6656   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6657   SDValue LHS = Op.getOperand(0);
6658   SDValue RHS = Op.getOperand(1);
6659   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6660   SDLoc dl(Op);
6661
6662   if (LHS.getValueType().getVectorElementType().isInteger()) {
6663     assert(LHS.getValueType() == RHS.getValueType());
6664     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6665     SDValue Cmp =
6666         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6667     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6668   }
6669
6670   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6671          LHS.getValueType().getVectorElementType() == MVT::f64);
6672
6673   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6674   // clean.  Some of them require two branches to implement.
6675   AArch64CC::CondCode CC1, CC2;
6676   bool ShouldInvert;
6677   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6678
6679   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6680   SDValue Cmp =
6681       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6682   if (!Cmp.getNode())
6683     return SDValue();
6684
6685   if (CC2 != AArch64CC::AL) {
6686     SDValue Cmp2 =
6687         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6688     if (!Cmp2.getNode())
6689       return SDValue();
6690
6691     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6692   }
6693
6694   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6695
6696   if (ShouldInvert)
6697     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6698
6699   return Cmp;
6700 }
6701
6702 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6703 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6704 /// specified in the intrinsic calls.
6705 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6706                                                const CallInst &I,
6707                                                unsigned Intrinsic) const {
6708   auto &DL = I.getModule()->getDataLayout();
6709   switch (Intrinsic) {
6710   case Intrinsic::aarch64_neon_ld2:
6711   case Intrinsic::aarch64_neon_ld3:
6712   case Intrinsic::aarch64_neon_ld4:
6713   case Intrinsic::aarch64_neon_ld1x2:
6714   case Intrinsic::aarch64_neon_ld1x3:
6715   case Intrinsic::aarch64_neon_ld1x4:
6716   case Intrinsic::aarch64_neon_ld2lane:
6717   case Intrinsic::aarch64_neon_ld3lane:
6718   case Intrinsic::aarch64_neon_ld4lane:
6719   case Intrinsic::aarch64_neon_ld2r:
6720   case Intrinsic::aarch64_neon_ld3r:
6721   case Intrinsic::aarch64_neon_ld4r: {
6722     Info.opc = ISD::INTRINSIC_W_CHAIN;
6723     // Conservatively set memVT to the entire set of vectors loaded.
6724     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6725     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6726     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6727     Info.offset = 0;
6728     Info.align = 0;
6729     Info.vol = false; // volatile loads with NEON intrinsics not supported
6730     Info.readMem = true;
6731     Info.writeMem = false;
6732     return true;
6733   }
6734   case Intrinsic::aarch64_neon_st2:
6735   case Intrinsic::aarch64_neon_st3:
6736   case Intrinsic::aarch64_neon_st4:
6737   case Intrinsic::aarch64_neon_st1x2:
6738   case Intrinsic::aarch64_neon_st1x3:
6739   case Intrinsic::aarch64_neon_st1x4:
6740   case Intrinsic::aarch64_neon_st2lane:
6741   case Intrinsic::aarch64_neon_st3lane:
6742   case Intrinsic::aarch64_neon_st4lane: {
6743     Info.opc = ISD::INTRINSIC_VOID;
6744     // Conservatively set memVT to the entire set of vectors stored.
6745     unsigned NumElts = 0;
6746     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6747       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6748       if (!ArgTy->isVectorTy())
6749         break;
6750       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6751     }
6752     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6753     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6754     Info.offset = 0;
6755     Info.align = 0;
6756     Info.vol = false; // volatile stores with NEON intrinsics not supported
6757     Info.readMem = false;
6758     Info.writeMem = true;
6759     return true;
6760   }
6761   case Intrinsic::aarch64_ldaxr:
6762   case Intrinsic::aarch64_ldxr: {
6763     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6764     Info.opc = ISD::INTRINSIC_W_CHAIN;
6765     Info.memVT = MVT::getVT(PtrTy->getElementType());
6766     Info.ptrVal = I.getArgOperand(0);
6767     Info.offset = 0;
6768     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6769     Info.vol = true;
6770     Info.readMem = true;
6771     Info.writeMem = false;
6772     return true;
6773   }
6774   case Intrinsic::aarch64_stlxr:
6775   case Intrinsic::aarch64_stxr: {
6776     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6777     Info.opc = ISD::INTRINSIC_W_CHAIN;
6778     Info.memVT = MVT::getVT(PtrTy->getElementType());
6779     Info.ptrVal = I.getArgOperand(1);
6780     Info.offset = 0;
6781     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6782     Info.vol = true;
6783     Info.readMem = false;
6784     Info.writeMem = true;
6785     return true;
6786   }
6787   case Intrinsic::aarch64_ldaxp:
6788   case Intrinsic::aarch64_ldxp: {
6789     Info.opc = ISD::INTRINSIC_W_CHAIN;
6790     Info.memVT = MVT::i128;
6791     Info.ptrVal = I.getArgOperand(0);
6792     Info.offset = 0;
6793     Info.align = 16;
6794     Info.vol = true;
6795     Info.readMem = true;
6796     Info.writeMem = false;
6797     return true;
6798   }
6799   case Intrinsic::aarch64_stlxp:
6800   case Intrinsic::aarch64_stxp: {
6801     Info.opc = ISD::INTRINSIC_W_CHAIN;
6802     Info.memVT = MVT::i128;
6803     Info.ptrVal = I.getArgOperand(2);
6804     Info.offset = 0;
6805     Info.align = 16;
6806     Info.vol = true;
6807     Info.readMem = false;
6808     Info.writeMem = true;
6809     return true;
6810   }
6811   default:
6812     break;
6813   }
6814
6815   return false;
6816 }
6817
6818 // Truncations from 64-bit GPR to 32-bit GPR is free.
6819 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6820   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6821     return false;
6822   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6823   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6824   return NumBits1 > NumBits2;
6825 }
6826 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6827   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6828     return false;
6829   unsigned NumBits1 = VT1.getSizeInBits();
6830   unsigned NumBits2 = VT2.getSizeInBits();
6831   return NumBits1 > NumBits2;
6832 }
6833
6834 /// Check if it is profitable to hoist instruction in then/else to if.
6835 /// Not profitable if I and it's user can form a FMA instruction
6836 /// because we prefer FMSUB/FMADD.
6837 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6838   if (I->getOpcode() != Instruction::FMul)
6839     return true;
6840
6841   if (I->getNumUses() != 1)
6842     return true;
6843
6844   Instruction *User = I->user_back();
6845
6846   if (User &&
6847       !(User->getOpcode() == Instruction::FSub ||
6848         User->getOpcode() == Instruction::FAdd))
6849     return true;
6850
6851   const TargetOptions &Options = getTargetMachine().Options;
6852   const DataLayout &DL = I->getModule()->getDataLayout();
6853   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6854
6855   if (isFMAFasterThanFMulAndFAdd(VT) &&
6856       isOperationLegalOrCustom(ISD::FMA, VT) &&
6857       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6858     return false;
6859
6860   return true;
6861 }
6862
6863 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6864 // 64-bit GPR.
6865 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6866   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6867     return false;
6868   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6869   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6870   return NumBits1 == 32 && NumBits2 == 64;
6871 }
6872 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6873   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6874     return false;
6875   unsigned NumBits1 = VT1.getSizeInBits();
6876   unsigned NumBits2 = VT2.getSizeInBits();
6877   return NumBits1 == 32 && NumBits2 == 64;
6878 }
6879
6880 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6881   EVT VT1 = Val.getValueType();
6882   if (isZExtFree(VT1, VT2)) {
6883     return true;
6884   }
6885
6886   if (Val.getOpcode() != ISD::LOAD)
6887     return false;
6888
6889   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6890   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6891           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6892           VT1.getSizeInBits() <= 32);
6893 }
6894
6895 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6896   if (isa<FPExtInst>(Ext))
6897     return false;
6898
6899   // Vector types are next free.
6900   if (Ext->getType()->isVectorTy())
6901     return false;
6902
6903   for (const Use &U : Ext->uses()) {
6904     // The extension is free if we can fold it with a left shift in an
6905     // addressing mode or an arithmetic operation: add, sub, and cmp.
6906
6907     // Is there a shift?
6908     const Instruction *Instr = cast<Instruction>(U.getUser());
6909
6910     // Is this a constant shift?
6911     switch (Instr->getOpcode()) {
6912     case Instruction::Shl:
6913       if (!isa<ConstantInt>(Instr->getOperand(1)))
6914         return false;
6915       break;
6916     case Instruction::GetElementPtr: {
6917       gep_type_iterator GTI = gep_type_begin(Instr);
6918       auto &DL = Ext->getModule()->getDataLayout();
6919       std::advance(GTI, U.getOperandNo());
6920       Type *IdxTy = *GTI;
6921       // This extension will end up with a shift because of the scaling factor.
6922       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6923       // Get the shift amount based on the scaling factor:
6924       // log2(sizeof(IdxTy)) - log2(8).
6925       uint64_t ShiftAmt =
6926           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6927       // Is the constant foldable in the shift of the addressing mode?
6928       // I.e., shift amount is between 1 and 4 inclusive.
6929       if (ShiftAmt == 0 || ShiftAmt > 4)
6930         return false;
6931       break;
6932     }
6933     case Instruction::Trunc:
6934       // Check if this is a noop.
6935       // trunc(sext ty1 to ty2) to ty1.
6936       if (Instr->getType() == Ext->getOperand(0)->getType())
6937         continue;
6938     // FALL THROUGH.
6939     default:
6940       return false;
6941     }
6942
6943     // At this point we can use the bfm family, so this extension is free
6944     // for that use.
6945   }
6946   return true;
6947 }
6948
6949 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6950                                           unsigned &RequiredAligment) const {
6951   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6952     return false;
6953   // Cyclone supports unaligned accesses.
6954   RequiredAligment = 0;
6955   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6956   return NumBits == 32 || NumBits == 64;
6957 }
6958
6959 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6960                                           unsigned &RequiredAligment) const {
6961   if (!LoadedType.isSimple() ||
6962       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6963     return false;
6964   // Cyclone supports unaligned accesses.
6965   RequiredAligment = 0;
6966   unsigned NumBits = LoadedType.getSizeInBits();
6967   return NumBits == 32 || NumBits == 64;
6968 }
6969
6970 /// \brief Lower an interleaved load into a ldN intrinsic.
6971 ///
6972 /// E.g. Lower an interleaved load (Factor = 2):
6973 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6974 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6975 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6976 ///
6977 ///      Into:
6978 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6979 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6980 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6981 bool AArch64TargetLowering::lowerInterleavedLoad(
6982     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6983     ArrayRef<unsigned> Indices, unsigned Factor) const {
6984   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6985          "Invalid interleave factor");
6986   assert(!Shuffles.empty() && "Empty shufflevector input");
6987   assert(Shuffles.size() == Indices.size() &&
6988          "Unmatched number of shufflevectors and indices");
6989
6990   const DataLayout &DL = LI->getModule()->getDataLayout();
6991
6992   VectorType *VecTy = Shuffles[0]->getType();
6993   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6994
6995   // Skip if we do not have NEON and skip illegal vector types.
6996   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
6997     return false;
6998
6999   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7000   // load integer vectors first and then convert to pointer vectors.
7001   Type *EltTy = VecTy->getVectorElementType();
7002   if (EltTy->isPointerTy())
7003     VecTy =
7004         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7005
7006   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7007   Type *Tys[2] = {VecTy, PtrTy};
7008   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7009                                             Intrinsic::aarch64_neon_ld3,
7010                                             Intrinsic::aarch64_neon_ld4};
7011   Function *LdNFunc =
7012       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7013
7014   IRBuilder<> Builder(LI);
7015   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7016
7017   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7018
7019   // Replace uses of each shufflevector with the corresponding vector loaded
7020   // by ldN.
7021   for (unsigned i = 0; i < Shuffles.size(); i++) {
7022     ShuffleVectorInst *SVI = Shuffles[i];
7023     unsigned Index = Indices[i];
7024
7025     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7026
7027     // Convert the integer vector to pointer vector if the element is pointer.
7028     if (EltTy->isPointerTy())
7029       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7030
7031     SVI->replaceAllUsesWith(SubVec);
7032   }
7033
7034   return true;
7035 }
7036
7037 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7038 ///
7039 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7040 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7041                                    unsigned NumElts) {
7042   SmallVector<Constant *, 16> Mask;
7043   for (unsigned i = 0; i < NumElts; i++)
7044     Mask.push_back(Builder.getInt32(Start + i));
7045
7046   return ConstantVector::get(Mask);
7047 }
7048
7049 /// \brief Lower an interleaved store into a stN intrinsic.
7050 ///
7051 /// E.g. Lower an interleaved store (Factor = 3):
7052 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7053 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7054 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7055 ///
7056 ///      Into:
7057 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7058 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7059 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7060 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7061 ///
7062 /// Note that the new shufflevectors will be removed and we'll only generate one
7063 /// st3 instruction in CodeGen.
7064 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7065                                                   ShuffleVectorInst *SVI,
7066                                                   unsigned Factor) const {
7067   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7068          "Invalid interleave factor");
7069
7070   VectorType *VecTy = SVI->getType();
7071   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7072          "Invalid interleaved store");
7073
7074   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7075   Type *EltTy = VecTy->getVectorElementType();
7076   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7077
7078   const DataLayout &DL = SI->getModule()->getDataLayout();
7079   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7080
7081   // Skip if we do not have NEON and skip illegal vector types.
7082   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7083     return false;
7084
7085   Value *Op0 = SVI->getOperand(0);
7086   Value *Op1 = SVI->getOperand(1);
7087   IRBuilder<> Builder(SI);
7088
7089   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7090   // vectors to integer vectors.
7091   if (EltTy->isPointerTy()) {
7092     Type *IntTy = DL.getIntPtrType(EltTy);
7093     unsigned NumOpElts =
7094         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7095
7096     // Convert to the corresponding integer vector.
7097     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7098     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7099     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7100
7101     SubVecTy = VectorType::get(IntTy, NumSubElts);
7102   }
7103
7104   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7105   Type *Tys[2] = {SubVecTy, PtrTy};
7106   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7107                                              Intrinsic::aarch64_neon_st3,
7108                                              Intrinsic::aarch64_neon_st4};
7109   Function *StNFunc =
7110       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7111
7112   SmallVector<Value *, 5> Ops;
7113
7114   // Split the shufflevector operands into sub vectors for the new stN call.
7115   for (unsigned i = 0; i < Factor; i++)
7116     Ops.push_back(Builder.CreateShuffleVector(
7117         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7118
7119   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7120   Builder.CreateCall(StNFunc, Ops);
7121   return true;
7122 }
7123
7124 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7125                        unsigned AlignCheck) {
7126   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7127           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7128 }
7129
7130 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7131                                                unsigned SrcAlign, bool IsMemset,
7132                                                bool ZeroMemset,
7133                                                bool MemcpyStrSrc,
7134                                                MachineFunction &MF) const {
7135   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7136   // instruction to materialize the v2i64 zero and one store (with restrictive
7137   // addressing mode). Just do two i64 store of zero-registers.
7138   bool Fast;
7139   const Function *F = MF.getFunction();
7140   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7141       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7142       (memOpAlign(SrcAlign, DstAlign, 16) ||
7143        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7144     return MVT::f128;
7145
7146   if (Size >= 8 &&
7147       (memOpAlign(SrcAlign, DstAlign, 8) ||
7148        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7149     return MVT::i64;
7150
7151   if (Size >= 4 &&
7152       (memOpAlign(SrcAlign, DstAlign, 4) ||
7153        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7154     return MVT::i32;
7155
7156   return MVT::Other;
7157 }
7158
7159 // 12-bit optionally shifted immediates are legal for adds.
7160 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7161   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7162     return true;
7163   return false;
7164 }
7165
7166 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7167 // immediates is the same as for an add or a sub.
7168 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7169   if (Immed < 0)
7170     Immed *= -1;
7171   return isLegalAddImmediate(Immed);
7172 }
7173
7174 /// isLegalAddressingMode - Return true if the addressing mode represented
7175 /// by AM is legal for this target, for a load/store of the specified type.
7176 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7177                                                   const AddrMode &AM, Type *Ty,
7178                                                   unsigned AS) const {
7179   // AArch64 has five basic addressing modes:
7180   //  reg
7181   //  reg + 9-bit signed offset
7182   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7183   //  reg1 + reg2
7184   //  reg + SIZE_IN_BYTES * reg
7185
7186   // No global is ever allowed as a base.
7187   if (AM.BaseGV)
7188     return false;
7189
7190   // No reg+reg+imm addressing.
7191   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7192     return false;
7193
7194   // check reg + imm case:
7195   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7196   uint64_t NumBytes = 0;
7197   if (Ty->isSized()) {
7198     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7199     NumBytes = NumBits / 8;
7200     if (!isPowerOf2_64(NumBits))
7201       NumBytes = 0;
7202   }
7203
7204   if (!AM.Scale) {
7205     int64_t Offset = AM.BaseOffs;
7206
7207     // 9-bit signed offset
7208     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7209       return true;
7210
7211     // 12-bit unsigned offset
7212     unsigned shift = Log2_64(NumBytes);
7213     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7214         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7215         (Offset >> shift) << shift == Offset)
7216       return true;
7217     return false;
7218   }
7219
7220   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7221
7222   if (!AM.Scale || AM.Scale == 1 ||
7223       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7224     return true;
7225   return false;
7226 }
7227
7228 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7229                                                 const AddrMode &AM, Type *Ty,
7230                                                 unsigned AS) const {
7231   // Scaling factors are not free at all.
7232   // Operands                     | Rt Latency
7233   // -------------------------------------------
7234   // Rt, [Xn, Xm]                 | 4
7235   // -------------------------------------------
7236   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7237   // Rt, [Xn, Wm, <extend> #imm]  |
7238   if (isLegalAddressingMode(DL, AM, Ty, AS))
7239     // Scale represents reg2 * scale, thus account for 1 if
7240     // it is not equal to 0 or 1.
7241     return AM.Scale != 0 && AM.Scale != 1;
7242   return -1;
7243 }
7244
7245 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7246   VT = VT.getScalarType();
7247
7248   if (!VT.isSimple())
7249     return false;
7250
7251   switch (VT.getSimpleVT().SimpleTy) {
7252   case MVT::f32:
7253   case MVT::f64:
7254     return true;
7255   default:
7256     break;
7257   }
7258
7259   return false;
7260 }
7261
7262 const MCPhysReg *
7263 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7264   // LR is a callee-save register, but we must treat it as clobbered by any call
7265   // site. Hence we include LR in the scratch registers, which are in turn added
7266   // as implicit-defs for stackmaps and patchpoints.
7267   static const MCPhysReg ScratchRegs[] = {
7268     AArch64::X16, AArch64::X17, AArch64::LR, 0
7269   };
7270   return ScratchRegs;
7271 }
7272
7273 bool
7274 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7275   EVT VT = N->getValueType(0);
7276     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7277     // it with shift to let it be lowered to UBFX.
7278   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7279       isa<ConstantSDNode>(N->getOperand(1))) {
7280     uint64_t TruncMask = N->getConstantOperandVal(1);
7281     if (isMask_64(TruncMask) &&
7282       N->getOperand(0).getOpcode() == ISD::SRL &&
7283       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7284       return false;
7285   }
7286   return true;
7287 }
7288
7289 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7290                                                               Type *Ty) const {
7291   assert(Ty->isIntegerTy());
7292
7293   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7294   if (BitSize == 0)
7295     return false;
7296
7297   int64_t Val = Imm.getSExtValue();
7298   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7299     return true;
7300
7301   if ((int64_t)Val < 0)
7302     Val = ~Val;
7303   if (BitSize == 32)
7304     Val &= (1LL << 32) - 1;
7305
7306   unsigned LZ = countLeadingZeros((uint64_t)Val);
7307   unsigned Shift = (63 - LZ) / 16;
7308   // MOVZ is free so return true for one or fewer MOVK.
7309   return Shift < 3;
7310 }
7311
7312 // Generate SUBS and CSEL for integer abs.
7313 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7314   EVT VT = N->getValueType(0);
7315
7316   SDValue N0 = N->getOperand(0);
7317   SDValue N1 = N->getOperand(1);
7318   SDLoc DL(N);
7319
7320   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7321   // and change it to SUB and CSEL.
7322   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7323       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7324       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7325     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7326       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7327         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7328                                   N0.getOperand(0));
7329         // Generate SUBS & CSEL.
7330         SDValue Cmp =
7331             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7332                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7333         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7334                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7335                            SDValue(Cmp.getNode(), 1));
7336       }
7337   return SDValue();
7338 }
7339
7340 // performXorCombine - Attempts to handle integer ABS.
7341 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7342                                  TargetLowering::DAGCombinerInfo &DCI,
7343                                  const AArch64Subtarget *Subtarget) {
7344   if (DCI.isBeforeLegalizeOps())
7345     return SDValue();
7346
7347   return performIntegerAbsCombine(N, DAG);
7348 }
7349
7350 SDValue
7351 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7352                                      SelectionDAG &DAG,
7353                                      std::vector<SDNode *> *Created) const {
7354   // fold (sdiv X, pow2)
7355   EVT VT = N->getValueType(0);
7356   if ((VT != MVT::i32 && VT != MVT::i64) ||
7357       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7358     return SDValue();
7359
7360   SDLoc DL(N);
7361   SDValue N0 = N->getOperand(0);
7362   unsigned Lg2 = Divisor.countTrailingZeros();
7363   SDValue Zero = DAG.getConstant(0, DL, VT);
7364   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7365
7366   // Add (N0 < 0) ? Pow2 - 1 : 0;
7367   SDValue CCVal;
7368   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7369   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7370   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7371
7372   if (Created) {
7373     Created->push_back(Cmp.getNode());
7374     Created->push_back(Add.getNode());
7375     Created->push_back(CSel.getNode());
7376   }
7377
7378   // Divide by pow2.
7379   SDValue SRA =
7380       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7381
7382   // If we're dividing by a positive value, we're done.  Otherwise, we must
7383   // negate the result.
7384   if (Divisor.isNonNegative())
7385     return SRA;
7386
7387   if (Created)
7388     Created->push_back(SRA.getNode());
7389   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7390 }
7391
7392 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7393                                  TargetLowering::DAGCombinerInfo &DCI,
7394                                  const AArch64Subtarget *Subtarget) {
7395   if (DCI.isBeforeLegalizeOps())
7396     return SDValue();
7397
7398   // Multiplication of a power of two plus/minus one can be done more
7399   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7400   // future CPUs have a cheaper MADD instruction, this may need to be
7401   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7402   // 64-bit is 5 cycles, so this is always a win.
7403   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7404     APInt Value = C->getAPIntValue();
7405     EVT VT = N->getValueType(0);
7406     SDLoc DL(N);
7407     if (Value.isNonNegative()) {
7408       // (mul x, 2^N + 1) => (add (shl x, N), x)
7409       APInt VM1 = Value - 1;
7410       if (VM1.isPowerOf2()) {
7411         SDValue ShiftedVal =
7412             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7413                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7414         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7415                            N->getOperand(0));
7416       }
7417       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7418       APInt VP1 = Value + 1;
7419       if (VP1.isPowerOf2()) {
7420         SDValue ShiftedVal =
7421             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7422                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7423         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7424                            N->getOperand(0));
7425       }
7426     } else {
7427       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7428       APInt VNP1 = -Value + 1;
7429       if (VNP1.isPowerOf2()) {
7430         SDValue ShiftedVal =
7431             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7432                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7433         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7434                            ShiftedVal);
7435       }
7436       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7437       APInt VNM1 = -Value - 1;
7438       if (VNM1.isPowerOf2()) {
7439         SDValue ShiftedVal =
7440             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7441                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7442         SDValue Add =
7443             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7444         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7445       }
7446     }
7447   }
7448   return SDValue();
7449 }
7450
7451 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7452                                                          SelectionDAG &DAG) {
7453   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7454   // optimize away operation when it's from a constant.
7455   //
7456   // The general transformation is:
7457   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7458   //       AND(VECTOR_CMP(x,y), constant2)
7459   //    constant2 = UNARYOP(constant)
7460
7461   // Early exit if this isn't a vector operation, the operand of the
7462   // unary operation isn't a bitwise AND, or if the sizes of the operations
7463   // aren't the same.
7464   EVT VT = N->getValueType(0);
7465   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7466       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7467       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7468     return SDValue();
7469
7470   // Now check that the other operand of the AND is a constant. We could
7471   // make the transformation for non-constant splats as well, but it's unclear
7472   // that would be a benefit as it would not eliminate any operations, just
7473   // perform one more step in scalar code before moving to the vector unit.
7474   if (BuildVectorSDNode *BV =
7475           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7476     // Bail out if the vector isn't a constant.
7477     if (!BV->isConstant())
7478       return SDValue();
7479
7480     // Everything checks out. Build up the new and improved node.
7481     SDLoc DL(N);
7482     EVT IntVT = BV->getValueType(0);
7483     // Create a new constant of the appropriate type for the transformed
7484     // DAG.
7485     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7486     // The AND node needs bitcasts to/from an integer vector type around it.
7487     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7488     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7489                                  N->getOperand(0)->getOperand(0), MaskConst);
7490     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7491     return Res;
7492   }
7493
7494   return SDValue();
7495 }
7496
7497 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7498                                      const AArch64Subtarget *Subtarget) {
7499   // First try to optimize away the conversion when it's conditionally from
7500   // a constant. Vectors only.
7501   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7502     return Res;
7503
7504   EVT VT = N->getValueType(0);
7505   if (VT != MVT::f32 && VT != MVT::f64)
7506     return SDValue();
7507
7508   // Only optimize when the source and destination types have the same width.
7509   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7510     return SDValue();
7511
7512   // If the result of an integer load is only used by an integer-to-float
7513   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7514   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7515   SDValue N0 = N->getOperand(0);
7516   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7517       // Do not change the width of a volatile load.
7518       !cast<LoadSDNode>(N0)->isVolatile()) {
7519     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7520     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7521                                LN0->getPointerInfo(), LN0->isVolatile(),
7522                                LN0->isNonTemporal(), LN0->isInvariant(),
7523                                LN0->getAlignment());
7524
7525     // Make sure successors of the original load stay after it by updating them
7526     // to use the new Chain.
7527     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7528
7529     unsigned Opcode =
7530         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7531     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7532   }
7533
7534   return SDValue();
7535 }
7536
7537 /// Fold a floating-point multiply by power of two into floating-point to
7538 /// fixed-point conversion.
7539 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7540                                      const AArch64Subtarget *Subtarget) {
7541   if (!Subtarget->hasNEON())
7542     return SDValue();
7543
7544   SDValue Op = N->getOperand(0);
7545   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7546     return SDValue();
7547
7548   SDValue ConstVec = Op->getOperand(1);
7549   if (!isa<BuildVectorSDNode>(ConstVec))
7550     return SDValue();
7551
7552   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7553   uint32_t FloatBits = FloatTy.getSizeInBits();
7554   if (FloatBits != 32 && FloatBits != 64)
7555     return SDValue();
7556
7557   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7558   uint32_t IntBits = IntTy.getSizeInBits();
7559   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7560     return SDValue();
7561
7562   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7563   if (IntBits > FloatBits)
7564     return SDValue();
7565
7566   BitVector UndefElements;
7567   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7568   int32_t Bits = IntBits == 64 ? 64 : 32;
7569   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7570   if (C == -1 || C == 0 || C > Bits)
7571     return SDValue();
7572
7573   MVT ResTy;
7574   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7575   switch (NumLanes) {
7576   default:
7577     return SDValue();
7578   case 2:
7579     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7580     break;
7581   case 4:
7582     ResTy = MVT::v4i32;
7583     break;
7584   }
7585
7586   SDLoc DL(N);
7587   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7588   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7589                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7590   SDValue FixConv =
7591       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7592                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7593                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7594   // We can handle smaller integers by generating an extra trunc.
7595   if (IntBits < FloatBits)
7596     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7597
7598   return FixConv;
7599 }
7600
7601 /// Fold a floating-point divide by power of two into fixed-point to
7602 /// floating-point conversion.
7603 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7604                                   const AArch64Subtarget *Subtarget) {
7605   if (!Subtarget->hasNEON())
7606     return SDValue();
7607
7608   SDValue Op = N->getOperand(0);
7609   unsigned Opc = Op->getOpcode();
7610   if (!Op.getValueType().isVector() ||
7611       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7612     return SDValue();
7613
7614   SDValue ConstVec = N->getOperand(1);
7615   if (!isa<BuildVectorSDNode>(ConstVec))
7616     return SDValue();
7617
7618   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7619   int32_t IntBits = IntTy.getSizeInBits();
7620   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7621     return SDValue();
7622
7623   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7624   int32_t FloatBits = FloatTy.getSizeInBits();
7625   if (FloatBits != 32 && FloatBits != 64)
7626     return SDValue();
7627
7628   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7629   if (IntBits > FloatBits)
7630     return SDValue();
7631
7632   BitVector UndefElements;
7633   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7634   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7635   if (C == -1 || C == 0 || C > FloatBits)
7636     return SDValue();
7637
7638   MVT ResTy;
7639   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7640   switch (NumLanes) {
7641   default:
7642     return SDValue();
7643   case 2:
7644     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7645     break;
7646   case 4:
7647     ResTy = MVT::v4i32;
7648     break;
7649   }
7650
7651   SDLoc DL(N);
7652   SDValue ConvInput = Op.getOperand(0);
7653   bool IsSigned = Opc == ISD::SINT_TO_FP;
7654   if (IntBits < FloatBits)
7655     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7656                             ResTy, ConvInput);
7657
7658   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7659                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7660   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7661                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7662                      DAG.getConstant(C, DL, MVT::i32));
7663 }
7664
7665 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7666 /// searches for and classifies those shifts.
7667 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7668                          bool &FromHi) {
7669   if (N.getOpcode() == ISD::SHL)
7670     FromHi = false;
7671   else if (N.getOpcode() == ISD::SRL)
7672     FromHi = true;
7673   else
7674     return false;
7675
7676   if (!isa<ConstantSDNode>(N.getOperand(1)))
7677     return false;
7678
7679   ShiftAmount = N->getConstantOperandVal(1);
7680   Src = N->getOperand(0);
7681   return true;
7682 }
7683
7684 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7685 /// registers viewed as a high/low pair. This function looks for the pattern:
7686 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7687 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7688 /// independent.
7689 static SDValue tryCombineToEXTR(SDNode *N,
7690                                 TargetLowering::DAGCombinerInfo &DCI) {
7691   SelectionDAG &DAG = DCI.DAG;
7692   SDLoc DL(N);
7693   EVT VT = N->getValueType(0);
7694
7695   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7696
7697   if (VT != MVT::i32 && VT != MVT::i64)
7698     return SDValue();
7699
7700   SDValue LHS;
7701   uint32_t ShiftLHS = 0;
7702   bool LHSFromHi = 0;
7703   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7704     return SDValue();
7705
7706   SDValue RHS;
7707   uint32_t ShiftRHS = 0;
7708   bool RHSFromHi = 0;
7709   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7710     return SDValue();
7711
7712   // If they're both trying to come from the high part of the register, they're
7713   // not really an EXTR.
7714   if (LHSFromHi == RHSFromHi)
7715     return SDValue();
7716
7717   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7718     return SDValue();
7719
7720   if (LHSFromHi) {
7721     std::swap(LHS, RHS);
7722     std::swap(ShiftLHS, ShiftRHS);
7723   }
7724
7725   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7726                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7727 }
7728
7729 static SDValue tryCombineToBSL(SDNode *N,
7730                                 TargetLowering::DAGCombinerInfo &DCI) {
7731   EVT VT = N->getValueType(0);
7732   SelectionDAG &DAG = DCI.DAG;
7733   SDLoc DL(N);
7734
7735   if (!VT.isVector())
7736     return SDValue();
7737
7738   SDValue N0 = N->getOperand(0);
7739   if (N0.getOpcode() != ISD::AND)
7740     return SDValue();
7741
7742   SDValue N1 = N->getOperand(1);
7743   if (N1.getOpcode() != ISD::AND)
7744     return SDValue();
7745
7746   // We only have to look for constant vectors here since the general, variable
7747   // case can be handled in TableGen.
7748   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7749   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7750   for (int i = 1; i >= 0; --i)
7751     for (int j = 1; j >= 0; --j) {
7752       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7753       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7754       if (!BVN0 || !BVN1)
7755         continue;
7756
7757       bool FoundMatch = true;
7758       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7759         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7760         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7761         if (!CN0 || !CN1 ||
7762             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7763           FoundMatch = false;
7764           break;
7765         }
7766       }
7767
7768       if (FoundMatch)
7769         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7770                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7771     }
7772
7773   return SDValue();
7774 }
7775
7776 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7777                                 const AArch64Subtarget *Subtarget) {
7778   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7779   if (!EnableAArch64ExtrGeneration)
7780     return SDValue();
7781   SelectionDAG &DAG = DCI.DAG;
7782   EVT VT = N->getValueType(0);
7783
7784   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7785     return SDValue();
7786
7787   SDValue Res = tryCombineToEXTR(N, DCI);
7788   if (Res.getNode())
7789     return Res;
7790
7791   Res = tryCombineToBSL(N, DCI);
7792   if (Res.getNode())
7793     return Res;
7794
7795   return SDValue();
7796 }
7797
7798 static SDValue performBitcastCombine(SDNode *N,
7799                                      TargetLowering::DAGCombinerInfo &DCI,
7800                                      SelectionDAG &DAG) {
7801   // Wait 'til after everything is legalized to try this. That way we have
7802   // legal vector types and such.
7803   if (DCI.isBeforeLegalizeOps())
7804     return SDValue();
7805
7806   // Remove extraneous bitcasts around an extract_subvector.
7807   // For example,
7808   //    (v4i16 (bitconvert
7809   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7810   //  becomes
7811   //    (extract_subvector ((v8i16 ...), (i64 4)))
7812
7813   // Only interested in 64-bit vectors as the ultimate result.
7814   EVT VT = N->getValueType(0);
7815   if (!VT.isVector())
7816     return SDValue();
7817   if (VT.getSimpleVT().getSizeInBits() != 64)
7818     return SDValue();
7819   // Is the operand an extract_subvector starting at the beginning or halfway
7820   // point of the vector? A low half may also come through as an
7821   // EXTRACT_SUBREG, so look for that, too.
7822   SDValue Op0 = N->getOperand(0);
7823   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7824       !(Op0->isMachineOpcode() &&
7825         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7826     return SDValue();
7827   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7828   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7829     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7830       return SDValue();
7831   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7832     if (idx != AArch64::dsub)
7833       return SDValue();
7834     // The dsub reference is equivalent to a lane zero subvector reference.
7835     idx = 0;
7836   }
7837   // Look through the bitcast of the input to the extract.
7838   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7839     return SDValue();
7840   SDValue Source = Op0->getOperand(0)->getOperand(0);
7841   // If the source type has twice the number of elements as our destination
7842   // type, we know this is an extract of the high or low half of the vector.
7843   EVT SVT = Source->getValueType(0);
7844   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7845     return SDValue();
7846
7847   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7848
7849   // Create the simplified form to just extract the low or high half of the
7850   // vector directly rather than bothering with the bitcasts.
7851   SDLoc dl(N);
7852   unsigned NumElements = VT.getVectorNumElements();
7853   if (idx) {
7854     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7855     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7856   } else {
7857     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7858     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7859                                       Source, SubReg),
7860                    0);
7861   }
7862 }
7863
7864 static SDValue performConcatVectorsCombine(SDNode *N,
7865                                            TargetLowering::DAGCombinerInfo &DCI,
7866                                            SelectionDAG &DAG) {
7867   SDLoc dl(N);
7868   EVT VT = N->getValueType(0);
7869   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7870
7871   // Optimize concat_vectors of truncated vectors, where the intermediate
7872   // type is illegal, to avoid said illegality,  e.g.,
7873   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7874   //                          (v2i16 (truncate (v2i64)))))
7875   // ->
7876   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7877   //                                    (v4i32 (bitcast (v2i64))),
7878   //                                    <0, 2, 4, 6>)))
7879   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7880   // on both input and result type, so we might generate worse code.
7881   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7882   if (N->getNumOperands() == 2 &&
7883       N0->getOpcode() == ISD::TRUNCATE &&
7884       N1->getOpcode() == ISD::TRUNCATE) {
7885     SDValue N00 = N0->getOperand(0);
7886     SDValue N10 = N1->getOperand(0);
7887     EVT N00VT = N00.getValueType();
7888
7889     if (N00VT == N10.getValueType() &&
7890         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7891         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7892       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7893       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7894       for (size_t i = 0; i < Mask.size(); ++i)
7895         Mask[i] = i * 2;
7896       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7897                          DAG.getVectorShuffle(
7898                              MidVT, dl,
7899                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7900                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7901     }
7902   }
7903
7904   // Wait 'til after everything is legalized to try this. That way we have
7905   // legal vector types and such.
7906   if (DCI.isBeforeLegalizeOps())
7907     return SDValue();
7908
7909   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7910   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7911   // canonicalise to that.
7912   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7913     assert(VT.getVectorElementType().getSizeInBits() == 64);
7914     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7915                        DAG.getConstant(0, dl, MVT::i64));
7916   }
7917
7918   // Canonicalise concat_vectors so that the right-hand vector has as few
7919   // bit-casts as possible before its real operation. The primary matching
7920   // destination for these operations will be the narrowing "2" instructions,
7921   // which depend on the operation being performed on this right-hand vector.
7922   // For example,
7923   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7924   // becomes
7925   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7926
7927   if (N1->getOpcode() != ISD::BITCAST)
7928     return SDValue();
7929   SDValue RHS = N1->getOperand(0);
7930   MVT RHSTy = RHS.getValueType().getSimpleVT();
7931   // If the RHS is not a vector, this is not the pattern we're looking for.
7932   if (!RHSTy.isVector())
7933     return SDValue();
7934
7935   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7936
7937   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7938                                   RHSTy.getVectorNumElements() * 2);
7939   return DAG.getNode(ISD::BITCAST, dl, VT,
7940                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7941                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7942                                  RHS));
7943 }
7944
7945 static SDValue tryCombineFixedPointConvert(SDNode *N,
7946                                            TargetLowering::DAGCombinerInfo &DCI,
7947                                            SelectionDAG &DAG) {
7948   // Wait 'til after everything is legalized to try this. That way we have
7949   // legal vector types and such.
7950   if (DCI.isBeforeLegalizeOps())
7951     return SDValue();
7952   // Transform a scalar conversion of a value from a lane extract into a
7953   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7954   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7955   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7956   //
7957   // The second form interacts better with instruction selection and the
7958   // register allocator to avoid cross-class register copies that aren't
7959   // coalescable due to a lane reference.
7960
7961   // Check the operand and see if it originates from a lane extract.
7962   SDValue Op1 = N->getOperand(1);
7963   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7964     // Yep, no additional predication needed. Perform the transform.
7965     SDValue IID = N->getOperand(0);
7966     SDValue Shift = N->getOperand(2);
7967     SDValue Vec = Op1.getOperand(0);
7968     SDValue Lane = Op1.getOperand(1);
7969     EVT ResTy = N->getValueType(0);
7970     EVT VecResTy;
7971     SDLoc DL(N);
7972
7973     // The vector width should be 128 bits by the time we get here, even
7974     // if it started as 64 bits (the extract_vector handling will have
7975     // done so).
7976     assert(Vec.getValueType().getSizeInBits() == 128 &&
7977            "unexpected vector size on extract_vector_elt!");
7978     if (Vec.getValueType() == MVT::v4i32)
7979       VecResTy = MVT::v4f32;
7980     else if (Vec.getValueType() == MVT::v2i64)
7981       VecResTy = MVT::v2f64;
7982     else
7983       llvm_unreachable("unexpected vector type!");
7984
7985     SDValue Convert =
7986         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7987     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7988   }
7989   return SDValue();
7990 }
7991
7992 // AArch64 high-vector "long" operations are formed by performing the non-high
7993 // version on an extract_subvector of each operand which gets the high half:
7994 //
7995 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7996 //
7997 // However, there are cases which don't have an extract_high explicitly, but
7998 // have another operation that can be made compatible with one for free. For
7999 // example:
8000 //
8001 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8002 //
8003 // This routine does the actual conversion of such DUPs, once outer routines
8004 // have determined that everything else is in order.
8005 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8006 // similarly here.
8007 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8008   switch (N.getOpcode()) {
8009   case AArch64ISD::DUP:
8010   case AArch64ISD::DUPLANE8:
8011   case AArch64ISD::DUPLANE16:
8012   case AArch64ISD::DUPLANE32:
8013   case AArch64ISD::DUPLANE64:
8014   case AArch64ISD::MOVI:
8015   case AArch64ISD::MOVIshift:
8016   case AArch64ISD::MOVIedit:
8017   case AArch64ISD::MOVImsl:
8018   case AArch64ISD::MVNIshift:
8019   case AArch64ISD::MVNImsl:
8020     break;
8021   default:
8022     // FMOV could be supported, but isn't very useful, as it would only occur
8023     // if you passed a bitcast' floating point immediate to an eligible long
8024     // integer op (addl, smull, ...).
8025     return SDValue();
8026   }
8027
8028   MVT NarrowTy = N.getSimpleValueType();
8029   if (!NarrowTy.is64BitVector())
8030     return SDValue();
8031
8032   MVT ElementTy = NarrowTy.getVectorElementType();
8033   unsigned NumElems = NarrowTy.getVectorNumElements();
8034   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8035
8036   SDLoc dl(N);
8037   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8038                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8039                      DAG.getConstant(NumElems, dl, MVT::i64));
8040 }
8041
8042 static bool isEssentiallyExtractSubvector(SDValue N) {
8043   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8044     return true;
8045
8046   return N.getOpcode() == ISD::BITCAST &&
8047          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8048 }
8049
8050 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8051 struct GenericSetCCInfo {
8052   const SDValue *Opnd0;
8053   const SDValue *Opnd1;
8054   ISD::CondCode CC;
8055 };
8056
8057 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8058 struct AArch64SetCCInfo {
8059   const SDValue *Cmp;
8060   AArch64CC::CondCode CC;
8061 };
8062
8063 /// \brief Helper structure to keep track of SetCC information.
8064 union SetCCInfo {
8065   GenericSetCCInfo Generic;
8066   AArch64SetCCInfo AArch64;
8067 };
8068
8069 /// \brief Helper structure to be able to read SetCC information.  If set to
8070 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8071 /// GenericSetCCInfo.
8072 struct SetCCInfoAndKind {
8073   SetCCInfo Info;
8074   bool IsAArch64;
8075 };
8076
8077 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8078 /// an
8079 /// AArch64 lowered one.
8080 /// \p SetCCInfo is filled accordingly.
8081 /// \post SetCCInfo is meanginfull only when this function returns true.
8082 /// \return True when Op is a kind of SET_CC operation.
8083 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8084   // If this is a setcc, this is straight forward.
8085   if (Op.getOpcode() == ISD::SETCC) {
8086     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8087     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8088     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8089     SetCCInfo.IsAArch64 = false;
8090     return true;
8091   }
8092   // Otherwise, check if this is a matching csel instruction.
8093   // In other words:
8094   // - csel 1, 0, cc
8095   // - csel 0, 1, !cc
8096   if (Op.getOpcode() != AArch64ISD::CSEL)
8097     return false;
8098   // Set the information about the operands.
8099   // TODO: we want the operands of the Cmp not the csel
8100   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8101   SetCCInfo.IsAArch64 = true;
8102   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8103       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8104
8105   // Check that the operands matches the constraints:
8106   // (1) Both operands must be constants.
8107   // (2) One must be 1 and the other must be 0.
8108   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8109   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8110
8111   // Check (1).
8112   if (!TValue || !FValue)
8113     return false;
8114
8115   // Check (2).
8116   if (!TValue->isOne()) {
8117     // Update the comparison when we are interested in !cc.
8118     std::swap(TValue, FValue);
8119     SetCCInfo.Info.AArch64.CC =
8120         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8121   }
8122   return TValue->isOne() && FValue->isNullValue();
8123 }
8124
8125 // Returns true if Op is setcc or zext of setcc.
8126 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8127   if (isSetCC(Op, Info))
8128     return true;
8129   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8130     isSetCC(Op->getOperand(0), Info));
8131 }
8132
8133 // The folding we want to perform is:
8134 // (add x, [zext] (setcc cc ...) )
8135 //   -->
8136 // (csel x, (add x, 1), !cc ...)
8137 //
8138 // The latter will get matched to a CSINC instruction.
8139 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8140   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8141   SDValue LHS = Op->getOperand(0);
8142   SDValue RHS = Op->getOperand(1);
8143   SetCCInfoAndKind InfoAndKind;
8144
8145   // If neither operand is a SET_CC, give up.
8146   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8147     std::swap(LHS, RHS);
8148     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8149       return SDValue();
8150   }
8151
8152   // FIXME: This could be generatized to work for FP comparisons.
8153   EVT CmpVT = InfoAndKind.IsAArch64
8154                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8155                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8156   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8157     return SDValue();
8158
8159   SDValue CCVal;
8160   SDValue Cmp;
8161   SDLoc dl(Op);
8162   if (InfoAndKind.IsAArch64) {
8163     CCVal = DAG.getConstant(
8164         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8165         MVT::i32);
8166     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8167   } else
8168     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8169                       *InfoAndKind.Info.Generic.Opnd1,
8170                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8171                       CCVal, DAG, dl);
8172
8173   EVT VT = Op->getValueType(0);
8174   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8175   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8176 }
8177
8178 // The basic add/sub long vector instructions have variants with "2" on the end
8179 // which act on the high-half of their inputs. They are normally matched by
8180 // patterns like:
8181 //
8182 // (add (zeroext (extract_high LHS)),
8183 //      (zeroext (extract_high RHS)))
8184 // -> uaddl2 vD, vN, vM
8185 //
8186 // However, if one of the extracts is something like a duplicate, this
8187 // instruction can still be used profitably. This function puts the DAG into a
8188 // more appropriate form for those patterns to trigger.
8189 static SDValue performAddSubLongCombine(SDNode *N,
8190                                         TargetLowering::DAGCombinerInfo &DCI,
8191                                         SelectionDAG &DAG) {
8192   if (DCI.isBeforeLegalizeOps())
8193     return SDValue();
8194
8195   MVT VT = N->getSimpleValueType(0);
8196   if (!VT.is128BitVector()) {
8197     if (N->getOpcode() == ISD::ADD)
8198       return performSetccAddFolding(N, DAG);
8199     return SDValue();
8200   }
8201
8202   // Make sure both branches are extended in the same way.
8203   SDValue LHS = N->getOperand(0);
8204   SDValue RHS = N->getOperand(1);
8205   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8206        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8207       LHS.getOpcode() != RHS.getOpcode())
8208     return SDValue();
8209
8210   unsigned ExtType = LHS.getOpcode();
8211
8212   // It's not worth doing if at least one of the inputs isn't already an
8213   // extract, but we don't know which it'll be so we have to try both.
8214   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8215     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8216     if (!RHS.getNode())
8217       return SDValue();
8218
8219     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8220   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8221     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8222     if (!LHS.getNode())
8223       return SDValue();
8224
8225     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8226   }
8227
8228   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8229 }
8230
8231 // Massage DAGs which we can use the high-half "long" operations on into
8232 // something isel will recognize better. E.g.
8233 //
8234 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8235 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8236 //                     (extract_high (v2i64 (dup128 scalar)))))
8237 //
8238 static SDValue tryCombineLongOpWithDup(SDNode *N,
8239                                        TargetLowering::DAGCombinerInfo &DCI,
8240                                        SelectionDAG &DAG) {
8241   if (DCI.isBeforeLegalizeOps())
8242     return SDValue();
8243
8244   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8245   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8246   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8247   assert(LHS.getValueType().is64BitVector() &&
8248          RHS.getValueType().is64BitVector() &&
8249          "unexpected shape for long operation");
8250
8251   // Either node could be a DUP, but it's not worth doing both of them (you'd
8252   // just as well use the non-high version) so look for a corresponding extract
8253   // operation on the other "wing".
8254   if (isEssentiallyExtractSubvector(LHS)) {
8255     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8256     if (!RHS.getNode())
8257       return SDValue();
8258   } else if (isEssentiallyExtractSubvector(RHS)) {
8259     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8260     if (!LHS.getNode())
8261       return SDValue();
8262   }
8263
8264   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8265   if (IsIntrinsic)
8266     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8267                        N->getOperand(0), LHS, RHS);
8268   else
8269     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8270                        LHS, RHS);
8271 }
8272
8273 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8274   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8275   unsigned ElemBits = ElemTy.getSizeInBits();
8276
8277   int64_t ShiftAmount;
8278   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8279     APInt SplatValue, SplatUndef;
8280     unsigned SplatBitSize;
8281     bool HasAnyUndefs;
8282     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8283                               HasAnyUndefs, ElemBits) ||
8284         SplatBitSize != ElemBits)
8285       return SDValue();
8286
8287     ShiftAmount = SplatValue.getSExtValue();
8288   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8289     ShiftAmount = CVN->getSExtValue();
8290   } else
8291     return SDValue();
8292
8293   unsigned Opcode;
8294   bool IsRightShift;
8295   switch (IID) {
8296   default:
8297     llvm_unreachable("Unknown shift intrinsic");
8298   case Intrinsic::aarch64_neon_sqshl:
8299     Opcode = AArch64ISD::SQSHL_I;
8300     IsRightShift = false;
8301     break;
8302   case Intrinsic::aarch64_neon_uqshl:
8303     Opcode = AArch64ISD::UQSHL_I;
8304     IsRightShift = false;
8305     break;
8306   case Intrinsic::aarch64_neon_srshl:
8307     Opcode = AArch64ISD::SRSHR_I;
8308     IsRightShift = true;
8309     break;
8310   case Intrinsic::aarch64_neon_urshl:
8311     Opcode = AArch64ISD::URSHR_I;
8312     IsRightShift = true;
8313     break;
8314   case Intrinsic::aarch64_neon_sqshlu:
8315     Opcode = AArch64ISD::SQSHLU_I;
8316     IsRightShift = false;
8317     break;
8318   }
8319
8320   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8321     SDLoc dl(N);
8322     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8323                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8324   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8325     SDLoc dl(N);
8326     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8327                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8328   }
8329
8330   return SDValue();
8331 }
8332
8333 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8334 // the intrinsics must be legal and take an i32, this means there's almost
8335 // certainly going to be a zext in the DAG which we can eliminate.
8336 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8337   SDValue AndN = N->getOperand(2);
8338   if (AndN.getOpcode() != ISD::AND)
8339     return SDValue();
8340
8341   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8342   if (!CMask || CMask->getZExtValue() != Mask)
8343     return SDValue();
8344
8345   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8346                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8347 }
8348
8349 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8350                                            SelectionDAG &DAG) {
8351   SDLoc dl(N);
8352   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8353                      DAG.getNode(Opc, dl,
8354                                  N->getOperand(1).getSimpleValueType(),
8355                                  N->getOperand(1)),
8356                      DAG.getConstant(0, dl, MVT::i64));
8357 }
8358
8359 static SDValue performIntrinsicCombine(SDNode *N,
8360                                        TargetLowering::DAGCombinerInfo &DCI,
8361                                        const AArch64Subtarget *Subtarget) {
8362   SelectionDAG &DAG = DCI.DAG;
8363   unsigned IID = getIntrinsicID(N);
8364   switch (IID) {
8365   default:
8366     break;
8367   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8368   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8369     return tryCombineFixedPointConvert(N, DCI, DAG);
8370   case Intrinsic::aarch64_neon_saddv:
8371     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8372   case Intrinsic::aarch64_neon_uaddv:
8373     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8374   case Intrinsic::aarch64_neon_sminv:
8375     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8376   case Intrinsic::aarch64_neon_uminv:
8377     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8378   case Intrinsic::aarch64_neon_smaxv:
8379     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8380   case Intrinsic::aarch64_neon_umaxv:
8381     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8382   case Intrinsic::aarch64_neon_fmax:
8383     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8384                        N->getOperand(1), N->getOperand(2));
8385   case Intrinsic::aarch64_neon_fmin:
8386     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8387                        N->getOperand(1), N->getOperand(2));
8388   case Intrinsic::aarch64_neon_sabd:
8389     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8390                        N->getOperand(1), N->getOperand(2));
8391   case Intrinsic::aarch64_neon_uabd:
8392     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8393                        N->getOperand(1), N->getOperand(2));
8394   case Intrinsic::aarch64_neon_fmaxnm:
8395     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8396                        N->getOperand(1), N->getOperand(2));
8397   case Intrinsic::aarch64_neon_fminnm:
8398     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8399                        N->getOperand(1), N->getOperand(2));
8400   case Intrinsic::aarch64_neon_smull:
8401   case Intrinsic::aarch64_neon_umull:
8402   case Intrinsic::aarch64_neon_pmull:
8403   case Intrinsic::aarch64_neon_sqdmull:
8404     return tryCombineLongOpWithDup(N, DCI, DAG);
8405   case Intrinsic::aarch64_neon_sqshl:
8406   case Intrinsic::aarch64_neon_uqshl:
8407   case Intrinsic::aarch64_neon_sqshlu:
8408   case Intrinsic::aarch64_neon_srshl:
8409   case Intrinsic::aarch64_neon_urshl:
8410     return tryCombineShiftImm(IID, N, DAG);
8411   case Intrinsic::aarch64_crc32b:
8412   case Intrinsic::aarch64_crc32cb:
8413     return tryCombineCRC32(0xff, N, DAG);
8414   case Intrinsic::aarch64_crc32h:
8415   case Intrinsic::aarch64_crc32ch:
8416     return tryCombineCRC32(0xffff, N, DAG);
8417   }
8418   return SDValue();
8419 }
8420
8421 static SDValue performExtendCombine(SDNode *N,
8422                                     TargetLowering::DAGCombinerInfo &DCI,
8423                                     SelectionDAG &DAG) {
8424   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8425   // we can convert that DUP into another extract_high (of a bigger DUP), which
8426   // helps the backend to decide that an sabdl2 would be useful, saving a real
8427   // extract_high operation.
8428   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8429       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8430        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8431     SDNode *ABDNode = N->getOperand(0).getNode();
8432     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8433     if (!NewABD.getNode())
8434       return SDValue();
8435
8436     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8437                        NewABD);
8438   }
8439
8440   // This is effectively a custom type legalization for AArch64.
8441   //
8442   // Type legalization will split an extend of a small, legal, type to a larger
8443   // illegal type by first splitting the destination type, often creating
8444   // illegal source types, which then get legalized in isel-confusing ways,
8445   // leading to really terrible codegen. E.g.,
8446   //   %result = v8i32 sext v8i8 %value
8447   // becomes
8448   //   %losrc = extract_subreg %value, ...
8449   //   %hisrc = extract_subreg %value, ...
8450   //   %lo = v4i32 sext v4i8 %losrc
8451   //   %hi = v4i32 sext v4i8 %hisrc
8452   // Things go rapidly downhill from there.
8453   //
8454   // For AArch64, the [sz]ext vector instructions can only go up one element
8455   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8456   // take two instructions.
8457   //
8458   // This implies that the most efficient way to do the extend from v8i8
8459   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8460   // the normal splitting to happen for the v8i16->v8i32.
8461
8462   // This is pre-legalization to catch some cases where the default
8463   // type legalization will create ill-tempered code.
8464   if (!DCI.isBeforeLegalizeOps())
8465     return SDValue();
8466
8467   // We're only interested in cleaning things up for non-legal vector types
8468   // here. If both the source and destination are legal, things will just
8469   // work naturally without any fiddling.
8470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8471   EVT ResVT = N->getValueType(0);
8472   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8473     return SDValue();
8474   // If the vector type isn't a simple VT, it's beyond the scope of what
8475   // we're  worried about here. Let legalization do its thing and hope for
8476   // the best.
8477   SDValue Src = N->getOperand(0);
8478   EVT SrcVT = Src->getValueType(0);
8479   if (!ResVT.isSimple() || !SrcVT.isSimple())
8480     return SDValue();
8481
8482   // If the source VT is a 64-bit vector, we can play games and get the
8483   // better results we want.
8484   if (SrcVT.getSizeInBits() != 64)
8485     return SDValue();
8486
8487   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8488   unsigned ElementCount = SrcVT.getVectorNumElements();
8489   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8490   SDLoc DL(N);
8491   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8492
8493   // Now split the rest of the operation into two halves, each with a 64
8494   // bit source.
8495   EVT LoVT, HiVT;
8496   SDValue Lo, Hi;
8497   unsigned NumElements = ResVT.getVectorNumElements();
8498   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8499   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8500                                  ResVT.getVectorElementType(), NumElements / 2);
8501
8502   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8503                                LoVT.getVectorNumElements());
8504   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8505                    DAG.getConstant(0, DL, MVT::i64));
8506   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8507                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8508   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8509   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8510
8511   // Now combine the parts back together so we still have a single result
8512   // like the combiner expects.
8513   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8514 }
8515
8516 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8517 /// value. The load store optimizer pass will merge them to store pair stores.
8518 /// This has better performance than a splat of the scalar followed by a split
8519 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8520 /// followed by an ext.b and two stores.
8521 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8522   SDValue StVal = St->getValue();
8523   EVT VT = StVal.getValueType();
8524
8525   // Don't replace floating point stores, they possibly won't be transformed to
8526   // stp because of the store pair suppress pass.
8527   if (VT.isFloatingPoint())
8528     return SDValue();
8529
8530   // Check for insert vector elements.
8531   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8532     return SDValue();
8533
8534   // We can express a splat as store pair(s) for 2 or 4 elements.
8535   unsigned NumVecElts = VT.getVectorNumElements();
8536   if (NumVecElts != 4 && NumVecElts != 2)
8537     return SDValue();
8538   SDValue SplatVal = StVal.getOperand(1);
8539   unsigned RemainInsertElts = NumVecElts - 1;
8540
8541   // Check that this is a splat.
8542   while (--RemainInsertElts) {
8543     SDValue NextInsertElt = StVal.getOperand(0);
8544     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8545       return SDValue();
8546     if (NextInsertElt.getOperand(1) != SplatVal)
8547       return SDValue();
8548     StVal = NextInsertElt;
8549   }
8550   unsigned OrigAlignment = St->getAlignment();
8551   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8552   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8553
8554   // Create scalar stores. This is at least as good as the code sequence for a
8555   // split unaligned store which is a dup.s, ext.b, and two stores.
8556   // Most of the time the three stores should be replaced by store pair
8557   // instructions (stp).
8558   SDLoc DL(St);
8559   SDValue BasePtr = St->getBasePtr();
8560   SDValue NewST1 =
8561       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8562                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8563
8564   unsigned Offset = EltOffset;
8565   while (--NumVecElts) {
8566     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8567                                     DAG.getConstant(Offset, DL, MVT::i64));
8568     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8569                           St->getPointerInfo(), St->isVolatile(),
8570                           St->isNonTemporal(), Alignment);
8571     Offset += EltOffset;
8572   }
8573   return NewST1;
8574 }
8575
8576 static SDValue performSTORECombine(SDNode *N,
8577                                    TargetLowering::DAGCombinerInfo &DCI,
8578                                    SelectionDAG &DAG,
8579                                    const AArch64Subtarget *Subtarget) {
8580   if (!DCI.isBeforeLegalize())
8581     return SDValue();
8582
8583   StoreSDNode *S = cast<StoreSDNode>(N);
8584   if (S->isVolatile())
8585     return SDValue();
8586
8587   // FIXME: The logic for deciding if an unaligned store should be split should
8588   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8589   // a call to that function here.
8590
8591   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8592   // page boundaries. We want to split such stores.
8593   if (!Subtarget->isCyclone())
8594     return SDValue();
8595
8596   // Don't split at -Oz.
8597   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8598     return SDValue();
8599
8600   SDValue StVal = S->getValue();
8601   EVT VT = StVal.getValueType();
8602
8603   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8604   // those up regresses performance on micro-benchmarks and olden/bh.
8605   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8606     return SDValue();
8607
8608   // Split unaligned 16B stores. They are terrible for performance.
8609   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8610   // extensions can use this to mark that it does not want splitting to happen
8611   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8612   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8613   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8614       S->getAlignment() <= 2)
8615     return SDValue();
8616
8617   // If we get a splat of a scalar convert this vector store to a store of
8618   // scalars. They will be merged into store pairs thereby removing two
8619   // instructions.
8620   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8621     return ReplacedSplat;
8622
8623   SDLoc DL(S);
8624   unsigned NumElts = VT.getVectorNumElements() / 2;
8625   // Split VT into two.
8626   EVT HalfVT =
8627       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8628   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8629                                    DAG.getConstant(0, DL, MVT::i64));
8630   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8631                                    DAG.getConstant(NumElts, DL, MVT::i64));
8632   SDValue BasePtr = S->getBasePtr();
8633   SDValue NewST1 =
8634       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8635                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8636   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8637                                   DAG.getConstant(8, DL, MVT::i64));
8638   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8639                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8640                       S->getAlignment());
8641 }
8642
8643 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8644 /// post-increment LD1R.
8645 static SDValue performPostLD1Combine(SDNode *N,
8646                                      TargetLowering::DAGCombinerInfo &DCI,
8647                                      bool IsLaneOp) {
8648   if (DCI.isBeforeLegalizeOps())
8649     return SDValue();
8650
8651   SelectionDAG &DAG = DCI.DAG;
8652   EVT VT = N->getValueType(0);
8653
8654   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8655   SDNode *LD = N->getOperand(LoadIdx).getNode();
8656   // If it is not LOAD, can not do such combine.
8657   if (LD->getOpcode() != ISD::LOAD)
8658     return SDValue();
8659
8660   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8661   EVT MemVT = LoadSDN->getMemoryVT();
8662   // Check if memory operand is the same type as the vector element.
8663   if (MemVT != VT.getVectorElementType())
8664     return SDValue();
8665
8666   // Check if there are other uses. If so, do not combine as it will introduce
8667   // an extra load.
8668   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8669        ++UI) {
8670     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8671       continue;
8672     if (*UI != N)
8673       return SDValue();
8674   }
8675
8676   SDValue Addr = LD->getOperand(1);
8677   SDValue Vector = N->getOperand(0);
8678   // Search for a use of the address operand that is an increment.
8679   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8680        Addr.getNode()->use_end(); UI != UE; ++UI) {
8681     SDNode *User = *UI;
8682     if (User->getOpcode() != ISD::ADD
8683         || UI.getUse().getResNo() != Addr.getResNo())
8684       continue;
8685
8686     // Check that the add is independent of the load.  Otherwise, folding it
8687     // would create a cycle.
8688     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8689       continue;
8690     // Also check that add is not used in the vector operand.  This would also
8691     // create a cycle.
8692     if (User->isPredecessorOf(Vector.getNode()))
8693       continue;
8694
8695     // If the increment is a constant, it must match the memory ref size.
8696     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8697     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8698       uint32_t IncVal = CInc->getZExtValue();
8699       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8700       if (IncVal != NumBytes)
8701         continue;
8702       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8703     }
8704
8705     // Finally, check that the vector doesn't depend on the load.
8706     // Again, this would create a cycle.
8707     // The load depending on the vector is fine, as that's the case for the
8708     // LD1*post we'll eventually generate anyway.
8709     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8710       continue;
8711
8712     SmallVector<SDValue, 8> Ops;
8713     Ops.push_back(LD->getOperand(0));  // Chain
8714     if (IsLaneOp) {
8715       Ops.push_back(Vector);           // The vector to be inserted
8716       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8717     }
8718     Ops.push_back(Addr);
8719     Ops.push_back(Inc);
8720
8721     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8722     SDVTList SDTys = DAG.getVTList(Tys);
8723     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8724     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8725                                            MemVT,
8726                                            LoadSDN->getMemOperand());
8727
8728     // Update the uses.
8729     SmallVector<SDValue, 2> NewResults;
8730     NewResults.push_back(SDValue(LD, 0));             // The result of load
8731     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8732     DCI.CombineTo(LD, NewResults);
8733     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8734     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8735
8736     break;
8737   }
8738   return SDValue();
8739 }
8740
8741 /// This function handles the log2-shuffle pattern produced by the
8742 /// LoopVectorizer for the across vector reduction. It consists of
8743 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8744 /// are reduced, where s is an induction variable from 0 to
8745 /// log2(NumVectorElements).
8746 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8747                                                      unsigned Op,
8748                                                      SelectionDAG &DAG) {
8749   EVT VTy = OpV->getOperand(0).getValueType();
8750   if (!VTy.isVector())
8751     return SDValue();
8752
8753   int NumVecElts = VTy.getVectorNumElements();
8754   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8755     if (NumVecElts != 4)
8756       return SDValue();
8757   } else {
8758     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8759       return SDValue();
8760   }
8761
8762   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8763   SDValue PreOp = OpV;
8764   // Iterate over each step of the across vector reduction.
8765   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8766     SDValue CurOp = PreOp.getOperand(0);
8767     SDValue Shuffle = PreOp.getOperand(1);
8768     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8769       // Try to swap the 1st and 2nd operand as add and min/max instructions
8770       // are commutative.
8771       CurOp = PreOp.getOperand(1);
8772       Shuffle = PreOp.getOperand(0);
8773       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8774         return SDValue();
8775     }
8776
8777     // Check if the input vector is fed by the operator we want to handle,
8778     // except the last step; the very first input vector is not necessarily
8779     // the same operator we are handling.
8780     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8781       return SDValue();
8782
8783     // Check if it forms one step of the across vector reduction.
8784     // E.g.,
8785     //   %cur = add %1, %0
8786     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8787     //   %pre = add %cur, %shuffle
8788     if (Shuffle.getOperand(0) != CurOp)
8789       return SDValue();
8790
8791     int NumMaskElts = 1 << CurStep;
8792     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8793     // Check mask values in each step.
8794     // We expect the shuffle mask in each step follows a specific pattern
8795     // denoted here by the <M, U> form, where M is a sequence of integers
8796     // starting from NumMaskElts, increasing by 1, and the number integers
8797     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8798     // of undef in U should be NumVecElts - NumMaskElts.
8799     // E.g., for <8 x i16>, mask values in each step should be :
8800     //   step 0 : <1,u,u,u,u,u,u,u>
8801     //   step 1 : <2,3,u,u,u,u,u,u>
8802     //   step 2 : <4,5,6,7,u,u,u,u>
8803     for (int i = 0; i < NumVecElts; ++i)
8804       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8805           (i >= NumMaskElts && !(Mask[i] < 0)))
8806         return SDValue();
8807
8808     PreOp = CurOp;
8809   }
8810   unsigned Opcode;
8811   bool IsIntrinsic = false;
8812
8813   switch (Op) {
8814   default:
8815     llvm_unreachable("Unexpected operator for across vector reduction");
8816   case ISD::ADD:
8817     Opcode = AArch64ISD::UADDV;
8818     break;
8819   case ISD::SMAX:
8820     Opcode = AArch64ISD::SMAXV;
8821     break;
8822   case ISD::UMAX:
8823     Opcode = AArch64ISD::UMAXV;
8824     break;
8825   case ISD::SMIN:
8826     Opcode = AArch64ISD::SMINV;
8827     break;
8828   case ISD::UMIN:
8829     Opcode = AArch64ISD::UMINV;
8830     break;
8831   case ISD::FMAXNUM:
8832     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8833     IsIntrinsic = true;
8834     break;
8835   case ISD::FMINNUM:
8836     Opcode = Intrinsic::aarch64_neon_fminnmv;
8837     IsIntrinsic = true;
8838     break;
8839   }
8840   SDLoc DL(N);
8841
8842   return IsIntrinsic
8843              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8844                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8845              : DAG.getNode(
8846                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8847                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8848                    DAG.getConstant(0, DL, MVT::i64));
8849 }
8850
8851 /// Target-specific DAG combine for the across vector min/max reductions.
8852 /// This function specifically handles the final clean-up step of the vector
8853 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8854 /// pattern, which narrows down and finds the final min/max value from all
8855 /// elements of the vector.
8856 /// For example, for a <16 x i8> vector :
8857 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8858 ///   %smax0 = smax %arr, svn0
8859 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8860 ///   %smax1 = smax %smax0, %svn1
8861 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8862 ///   %smax2 = smax %smax1, svn2
8863 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8864 ///   %sc = setcc %smax2, %svn3, gt
8865 ///   %n0 = extract_vector_elt %sc, #0
8866 ///   %n1 = extract_vector_elt %smax2, #0
8867 ///   %n2 = extract_vector_elt $smax2, #1
8868 ///   %result = select %n0, %n1, n2
8869 ///     becomes :
8870 ///   %1 = smaxv %0
8871 ///   %result = extract_vector_elt %1, 0
8872 static SDValue
8873 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8874                                         const AArch64Subtarget *Subtarget) {
8875   if (!Subtarget->hasNEON())
8876     return SDValue();
8877
8878   SDValue N0 = N->getOperand(0);
8879   SDValue IfTrue = N->getOperand(1);
8880   SDValue IfFalse = N->getOperand(2);
8881
8882   // Check if the SELECT merges up the final result of the min/max
8883   // from a vector.
8884   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8885       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8886       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8887     return SDValue();
8888
8889   // Expect N0 is fed by SETCC.
8890   SDValue SetCC = N0.getOperand(0);
8891   EVT SetCCVT = SetCC.getValueType();
8892   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8893       SetCCVT.getVectorElementType() != MVT::i1)
8894     return SDValue();
8895
8896   SDValue VectorOp = SetCC.getOperand(0);
8897   unsigned Op = VectorOp->getOpcode();
8898   // Check if the input vector is fed by the operator we want to handle.
8899   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8900       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8901     return SDValue();
8902
8903   EVT VTy = VectorOp.getValueType();
8904   if (!VTy.isVector())
8905     return SDValue();
8906
8907   if (VTy.getSizeInBits() < 64)
8908     return SDValue();
8909
8910   EVT EltTy = VTy.getVectorElementType();
8911   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8912     if (EltTy != MVT::f32)
8913       return SDValue();
8914   } else {
8915     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8916       return SDValue();
8917   }
8918
8919   // Check if extracting from the same vector.
8920   // For example,
8921   //   %sc = setcc %vector, %svn1, gt
8922   //   %n0 = extract_vector_elt %sc, #0
8923   //   %n1 = extract_vector_elt %vector, #0
8924   //   %n2 = extract_vector_elt $vector, #1
8925   if (!(VectorOp == IfTrue->getOperand(0) &&
8926         VectorOp == IfFalse->getOperand(0)))
8927     return SDValue();
8928
8929   // Check if the condition code is matched with the operator type.
8930   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8931   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8932       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8933       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8934       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8935       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8936        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8937        CC != ISD::SETGE) ||
8938       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8939        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8940        CC != ISD::SETLE))
8941     return SDValue();
8942
8943   // Expect to check only lane 0 from the vector SETCC.
8944   if (!isa<ConstantSDNode>(N0.getOperand(1)) ||
8945       cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue() != 0)
8946     return SDValue();
8947
8948   // Expect to extract the true value from lane 0.
8949   if (!isa<ConstantSDNode>(IfTrue.getOperand(1)) ||
8950       cast<ConstantSDNode>(IfTrue.getOperand(1))->getZExtValue() != 0)
8951     return SDValue();
8952
8953   // Expect to extract the false value from lane 1.
8954   if (!isa<ConstantSDNode>(IfFalse.getOperand(1)) ||
8955       cast<ConstantSDNode>(IfFalse.getOperand(1))->getZExtValue() != 1)
8956     return SDValue();
8957
8958   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8959 }
8960
8961 /// Target-specific DAG combine for the across vector add reduction.
8962 /// This function specifically handles the final clean-up step of the vector
8963 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8964 /// pattern, which adds all elements of a vector together.
8965 /// For example, for a <4 x i32> vector :
8966 ///   %1 = vector_shuffle %0, <2,3,u,u>
8967 ///   %2 = add %0, %1
8968 ///   %3 = vector_shuffle %2, <1,u,u,u>
8969 ///   %4 = add %2, %3
8970 ///   %result = extract_vector_elt %4, 0
8971 /// becomes :
8972 ///   %0 = uaddv %0
8973 ///   %result = extract_vector_elt %0, 0
8974 static SDValue
8975 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
8976                                      const AArch64Subtarget *Subtarget) {
8977   if (!Subtarget->hasNEON())
8978     return SDValue();
8979   SDValue N0 = N->getOperand(0);
8980   SDValue N1 = N->getOperand(1);
8981
8982   // Check if the input vector is fed by the ADD.
8983   if (N0->getOpcode() != ISD::ADD)
8984     return SDValue();
8985
8986   // The vector extract idx must constant zero because we only expect the final
8987   // result of the reduction is placed in lane 0.
8988   if (!isa<ConstantSDNode>(N1) || cast<ConstantSDNode>(N1)->getZExtValue() != 0)
8989     return SDValue();
8990
8991   EVT VTy = N0.getValueType();
8992   if (!VTy.isVector())
8993     return SDValue();
8994
8995   EVT EltTy = VTy.getVectorElementType();
8996   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8997     return SDValue();
8998
8999   if (VTy.getSizeInBits() < 64)
9000     return SDValue();
9001
9002   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9003 }
9004
9005 /// Target-specific DAG combine function for NEON load/store intrinsics
9006 /// to merge base address updates.
9007 static SDValue performNEONPostLDSTCombine(SDNode *N,
9008                                           TargetLowering::DAGCombinerInfo &DCI,
9009                                           SelectionDAG &DAG) {
9010   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9011     return SDValue();
9012
9013   unsigned AddrOpIdx = N->getNumOperands() - 1;
9014   SDValue Addr = N->getOperand(AddrOpIdx);
9015
9016   // Search for a use of the address operand that is an increment.
9017   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9018        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9019     SDNode *User = *UI;
9020     if (User->getOpcode() != ISD::ADD ||
9021         UI.getUse().getResNo() != Addr.getResNo())
9022       continue;
9023
9024     // Check that the add is independent of the load/store.  Otherwise, folding
9025     // it would create a cycle.
9026     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9027       continue;
9028
9029     // Find the new opcode for the updating load/store.
9030     bool IsStore = false;
9031     bool IsLaneOp = false;
9032     bool IsDupOp = false;
9033     unsigned NewOpc = 0;
9034     unsigned NumVecs = 0;
9035     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9036     switch (IntNo) {
9037     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9038     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9039       NumVecs = 2; break;
9040     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9041       NumVecs = 3; break;
9042     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9043       NumVecs = 4; break;
9044     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9045       NumVecs = 2; IsStore = true; break;
9046     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9047       NumVecs = 3; IsStore = true; break;
9048     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9049       NumVecs = 4; IsStore = true; break;
9050     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9051       NumVecs = 2; break;
9052     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9053       NumVecs = 3; break;
9054     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9055       NumVecs = 4; break;
9056     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9057       NumVecs = 2; IsStore = true; break;
9058     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9059       NumVecs = 3; IsStore = true; break;
9060     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9061       NumVecs = 4; IsStore = true; break;
9062     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9063       NumVecs = 2; IsDupOp = true; break;
9064     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9065       NumVecs = 3; IsDupOp = true; break;
9066     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9067       NumVecs = 4; IsDupOp = true; break;
9068     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9069       NumVecs = 2; IsLaneOp = true; break;
9070     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9071       NumVecs = 3; IsLaneOp = true; break;
9072     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9073       NumVecs = 4; IsLaneOp = true; break;
9074     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9075       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9076     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9077       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9078     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9079       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9080     }
9081
9082     EVT VecTy;
9083     if (IsStore)
9084       VecTy = N->getOperand(2).getValueType();
9085     else
9086       VecTy = N->getValueType(0);
9087
9088     // If the increment is a constant, it must match the memory ref size.
9089     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9090     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9091       uint32_t IncVal = CInc->getZExtValue();
9092       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9093       if (IsLaneOp || IsDupOp)
9094         NumBytes /= VecTy.getVectorNumElements();
9095       if (IncVal != NumBytes)
9096         continue;
9097       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9098     }
9099     SmallVector<SDValue, 8> Ops;
9100     Ops.push_back(N->getOperand(0)); // Incoming chain
9101     // Load lane and store have vector list as input.
9102     if (IsLaneOp || IsStore)
9103       for (unsigned i = 2; i < AddrOpIdx; ++i)
9104         Ops.push_back(N->getOperand(i));
9105     Ops.push_back(Addr); // Base register
9106     Ops.push_back(Inc);
9107
9108     // Return Types.
9109     EVT Tys[6];
9110     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9111     unsigned n;
9112     for (n = 0; n < NumResultVecs; ++n)
9113       Tys[n] = VecTy;
9114     Tys[n++] = MVT::i64;  // Type of write back register
9115     Tys[n] = MVT::Other;  // Type of the chain
9116     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9117
9118     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9119     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9120                                            MemInt->getMemoryVT(),
9121                                            MemInt->getMemOperand());
9122
9123     // Update the uses.
9124     std::vector<SDValue> NewResults;
9125     for (unsigned i = 0; i < NumResultVecs; ++i) {
9126       NewResults.push_back(SDValue(UpdN.getNode(), i));
9127     }
9128     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9129     DCI.CombineTo(N, NewResults);
9130     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9131
9132     break;
9133   }
9134   return SDValue();
9135 }
9136
9137 // Checks to see if the value is the prescribed width and returns information
9138 // about its extension mode.
9139 static
9140 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9141   ExtType = ISD::NON_EXTLOAD;
9142   switch(V.getNode()->getOpcode()) {
9143   default:
9144     return false;
9145   case ISD::LOAD: {
9146     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9147     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9148        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9149       ExtType = LoadNode->getExtensionType();
9150       return true;
9151     }
9152     return false;
9153   }
9154   case ISD::AssertSext: {
9155     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9156     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9157        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9158       ExtType = ISD::SEXTLOAD;
9159       return true;
9160     }
9161     return false;
9162   }
9163   case ISD::AssertZext: {
9164     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9165     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9166        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9167       ExtType = ISD::ZEXTLOAD;
9168       return true;
9169     }
9170     return false;
9171   }
9172   case ISD::Constant:
9173   case ISD::TargetConstant: {
9174     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9175         1LL << (width - 1))
9176       return true;
9177     return false;
9178   }
9179   }
9180
9181   return true;
9182 }
9183
9184 // This function does a whole lot of voodoo to determine if the tests are
9185 // equivalent without and with a mask. Essentially what happens is that given a
9186 // DAG resembling:
9187 //
9188 //  +-------------+ +-------------+ +-------------+ +-------------+
9189 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9190 //  +-------------+ +-------------+ +-------------+ +-------------+
9191 //           |           |           |               |
9192 //           V           V           |    +----------+
9193 //          +-------------+  +----+  |    |
9194 //          |     ADD     |  |0xff|  |    |
9195 //          +-------------+  +----+  |    |
9196 //                  |           |    |    |
9197 //                  V           V    |    |
9198 //                 +-------------+   |    |
9199 //                 |     AND     |   |    |
9200 //                 +-------------+   |    |
9201 //                      |            |    |
9202 //                      +-----+      |    |
9203 //                            |      |    |
9204 //                            V      V    V
9205 //                           +-------------+
9206 //                           |     CMP     |
9207 //                           +-------------+
9208 //
9209 // The AND node may be safely removed for some combinations of inputs. In
9210 // particular we need to take into account the extension type of the Input,
9211 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9212 // width of the input (this can work for any width inputs, the above graph is
9213 // specific to 8 bits.
9214 //
9215 // The specific equations were worked out by generating output tables for each
9216 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9217 // problem was simplified by working with 4 bit inputs, which means we only
9218 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9219 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9220 // patterns present in both extensions (0,7). For every distinct set of
9221 // AddConstant and CompConstants bit patterns we can consider the masked and
9222 // unmasked versions to be equivalent if the result of this function is true for
9223 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9224 //
9225 //   sub      w8, w0, w1
9226 //   and      w10, w8, #0x0f
9227 //   cmp      w8, w2
9228 //   cset     w9, AArch64CC
9229 //   cmp      w10, w2
9230 //   cset     w11, AArch64CC
9231 //   cmp      w9, w11
9232 //   cset     w0, eq
9233 //   ret
9234 //
9235 // Since the above function shows when the outputs are equivalent it defines
9236 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9237 // would be expensive to run during compiles. The equations below were written
9238 // in a test harness that confirmed they gave equivalent outputs to the above
9239 // for all inputs function, so they can be used determine if the removal is
9240 // legal instead.
9241 //
9242 // isEquivalentMaskless() is the code for testing if the AND can be removed
9243 // factored out of the DAG recognition as the DAG can take several forms.
9244
9245 static
9246 bool isEquivalentMaskless(unsigned CC, unsigned width,
9247                           ISD::LoadExtType ExtType, signed AddConstant,
9248                           signed CompConstant) {
9249   // By being careful about our equations and only writing the in term
9250   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9251   // make them generally applicable to all bit widths.
9252   signed MaxUInt = (1 << width);
9253
9254   // For the purposes of these comparisons sign extending the type is
9255   // equivalent to zero extending the add and displacing it by half the integer
9256   // width. Provided we are careful and make sure our equations are valid over
9257   // the whole range we can just adjust the input and avoid writing equations
9258   // for sign extended inputs.
9259   if (ExtType == ISD::SEXTLOAD)
9260     AddConstant -= (1 << (width-1));
9261
9262   switch(CC) {
9263   case AArch64CC::LE:
9264   case AArch64CC::GT: {
9265     if ((AddConstant == 0) ||
9266         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9267         (AddConstant >= 0 && CompConstant < 0) ||
9268         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9269       return true;
9270   } break;
9271   case AArch64CC::LT:
9272   case AArch64CC::GE: {
9273     if ((AddConstant == 0) ||
9274         (AddConstant >= 0 && CompConstant <= 0) ||
9275         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9276       return true;
9277   } break;
9278   case AArch64CC::HI:
9279   case AArch64CC::LS: {
9280     if ((AddConstant >= 0 && CompConstant < 0) ||
9281        (AddConstant <= 0 && CompConstant >= -1 &&
9282         CompConstant < AddConstant + MaxUInt))
9283       return true;
9284   } break;
9285   case AArch64CC::PL:
9286   case AArch64CC::MI: {
9287     if ((AddConstant == 0) ||
9288         (AddConstant > 0 && CompConstant <= 0) ||
9289         (AddConstant < 0 && CompConstant <= AddConstant))
9290       return true;
9291   } break;
9292   case AArch64CC::LO:
9293   case AArch64CC::HS: {
9294     if ((AddConstant >= 0 && CompConstant <= 0) ||
9295         (AddConstant <= 0 && CompConstant >= 0 &&
9296          CompConstant <= AddConstant + MaxUInt))
9297       return true;
9298   } break;
9299   case AArch64CC::EQ:
9300   case AArch64CC::NE: {
9301     if ((AddConstant > 0 && CompConstant < 0) ||
9302         (AddConstant < 0 && CompConstant >= 0 &&
9303          CompConstant < AddConstant + MaxUInt) ||
9304         (AddConstant >= 0 && CompConstant >= 0 &&
9305          CompConstant >= AddConstant) ||
9306         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9307
9308       return true;
9309   } break;
9310   case AArch64CC::VS:
9311   case AArch64CC::VC:
9312   case AArch64CC::AL:
9313   case AArch64CC::NV:
9314     return true;
9315   case AArch64CC::Invalid:
9316     break;
9317   }
9318
9319   return false;
9320 }
9321
9322 static
9323 SDValue performCONDCombine(SDNode *N,
9324                            TargetLowering::DAGCombinerInfo &DCI,
9325                            SelectionDAG &DAG, unsigned CCIndex,
9326                            unsigned CmpIndex) {
9327   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9328   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9329   unsigned CondOpcode = SubsNode->getOpcode();
9330
9331   if (CondOpcode != AArch64ISD::SUBS)
9332     return SDValue();
9333
9334   // There is a SUBS feeding this condition. Is it fed by a mask we can
9335   // use?
9336
9337   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9338   unsigned MaskBits = 0;
9339
9340   if (AndNode->getOpcode() != ISD::AND)
9341     return SDValue();
9342
9343   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9344     uint32_t CNV = CN->getZExtValue();
9345     if (CNV == 255)
9346       MaskBits = 8;
9347     else if (CNV == 65535)
9348       MaskBits = 16;
9349   }
9350
9351   if (!MaskBits)
9352     return SDValue();
9353
9354   SDValue AddValue = AndNode->getOperand(0);
9355
9356   if (AddValue.getOpcode() != ISD::ADD)
9357     return SDValue();
9358
9359   // The basic dag structure is correct, grab the inputs and validate them.
9360
9361   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9362   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9363   SDValue SubsInputValue = SubsNode->getOperand(1);
9364
9365   // The mask is present and the provenance of all the values is a smaller type,
9366   // lets see if the mask is superfluous.
9367
9368   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9369       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9370     return SDValue();
9371
9372   ISD::LoadExtType ExtType;
9373
9374   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9375       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9376       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9377     return SDValue();
9378
9379   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9380                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9381                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9382     return SDValue();
9383
9384   // The AND is not necessary, remove it.
9385
9386   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9387                                SubsNode->getValueType(1));
9388   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9389
9390   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9391   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9392
9393   return SDValue(N, 0);
9394 }
9395
9396 // Optimize compare with zero and branch.
9397 static SDValue performBRCONDCombine(SDNode *N,
9398                                     TargetLowering::DAGCombinerInfo &DCI,
9399                                     SelectionDAG &DAG) {
9400   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9401   if (NV.getNode())
9402     N = NV.getNode();
9403   SDValue Chain = N->getOperand(0);
9404   SDValue Dest = N->getOperand(1);
9405   SDValue CCVal = N->getOperand(2);
9406   SDValue Cmp = N->getOperand(3);
9407
9408   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9409   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9410   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9411     return SDValue();
9412
9413   unsigned CmpOpc = Cmp.getOpcode();
9414   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9415     return SDValue();
9416
9417   // Only attempt folding if there is only one use of the flag and no use of the
9418   // value.
9419   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9420     return SDValue();
9421
9422   SDValue LHS = Cmp.getOperand(0);
9423   SDValue RHS = Cmp.getOperand(1);
9424
9425   assert(LHS.getValueType() == RHS.getValueType() &&
9426          "Expected the value type to be the same for both operands!");
9427   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9428     return SDValue();
9429
9430   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9431     std::swap(LHS, RHS);
9432
9433   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9434     return SDValue();
9435
9436   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9437       LHS.getOpcode() == ISD::SRL)
9438     return SDValue();
9439
9440   // Fold the compare into the branch instruction.
9441   SDValue BR;
9442   if (CC == AArch64CC::EQ)
9443     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9444   else
9445     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9446
9447   // Do not add new nodes to DAG combiner worklist.
9448   DCI.CombineTo(N, BR, false);
9449
9450   return SDValue();
9451 }
9452
9453 // vselect (v1i1 setcc) ->
9454 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9455 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9456 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9457 // such VSELECT.
9458 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9459   SDValue N0 = N->getOperand(0);
9460   EVT CCVT = N0.getValueType();
9461
9462   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9463       CCVT.getVectorElementType() != MVT::i1)
9464     return SDValue();
9465
9466   EVT ResVT = N->getValueType(0);
9467   EVT CmpVT = N0.getOperand(0).getValueType();
9468   // Only combine when the result type is of the same size as the compared
9469   // operands.
9470   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9471     return SDValue();
9472
9473   SDValue IfTrue = N->getOperand(1);
9474   SDValue IfFalse = N->getOperand(2);
9475   SDValue SetCC =
9476       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9477                    N0.getOperand(0), N0.getOperand(1),
9478                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9479   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9480                      IfTrue, IfFalse);
9481 }
9482
9483 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9484 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9485 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9486 /// with a vector one followed by a DUP shuffle on the result.
9487 static SDValue performSelectCombine(SDNode *N,
9488                                     TargetLowering::DAGCombinerInfo &DCI) {
9489   SelectionDAG &DAG = DCI.DAG;
9490   SDValue N0 = N->getOperand(0);
9491   EVT ResVT = N->getValueType(0);
9492
9493   if (N0.getOpcode() != ISD::SETCC)
9494     return SDValue();
9495
9496   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9497   // scalar SetCCResultType. We also don't expect vectors, because we assume
9498   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9499   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9500          "Scalar-SETCC feeding SELECT has unexpected result type!");
9501
9502   // If NumMaskElts == 0, the comparison is larger than select result. The
9503   // largest real NEON comparison is 64-bits per lane, which means the result is
9504   // at most 32-bits and an illegal vector. Just bail out for now.
9505   EVT SrcVT = N0.getOperand(0).getValueType();
9506
9507   // Don't try to do this optimization when the setcc itself has i1 operands.
9508   // There are no legal vectors of i1, so this would be pointless.
9509   if (SrcVT == MVT::i1)
9510     return SDValue();
9511
9512   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9513   if (!ResVT.isVector() || NumMaskElts == 0)
9514     return SDValue();
9515
9516   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9517   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9518
9519   // Also bail out if the vector CCVT isn't the same size as ResVT.
9520   // This can happen if the SETCC operand size doesn't divide the ResVT size
9521   // (e.g., f64 vs v3f32).
9522   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9523     return SDValue();
9524
9525   // Make sure we didn't create illegal types, if we're not supposed to.
9526   assert(DCI.isBeforeLegalize() ||
9527          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9528
9529   // First perform a vector comparison, where lane 0 is the one we're interested
9530   // in.
9531   SDLoc DL(N0);
9532   SDValue LHS =
9533       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9534   SDValue RHS =
9535       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9536   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9537
9538   // Now duplicate the comparison mask we want across all other lanes.
9539   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9540   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9541   Mask = DAG.getNode(ISD::BITCAST, DL,
9542                      ResVT.changeVectorElementTypeToInteger(), Mask);
9543
9544   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9545 }
9546
9547 /// Get rid of unnecessary NVCASTs (that don't change the type).
9548 static SDValue performNVCASTCombine(SDNode *N) {
9549   if (N->getValueType(0) == N->getOperand(0).getValueType())
9550     return N->getOperand(0);
9551
9552   return SDValue();
9553 }
9554
9555 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9556                                                  DAGCombinerInfo &DCI) const {
9557   SelectionDAG &DAG = DCI.DAG;
9558   switch (N->getOpcode()) {
9559   default:
9560     break;
9561   case ISD::ADD:
9562   case ISD::SUB:
9563     return performAddSubLongCombine(N, DCI, DAG);
9564   case ISD::XOR:
9565     return performXorCombine(N, DAG, DCI, Subtarget);
9566   case ISD::MUL:
9567     return performMulCombine(N, DAG, DCI, Subtarget);
9568   case ISD::SINT_TO_FP:
9569   case ISD::UINT_TO_FP:
9570     return performIntToFpCombine(N, DAG, Subtarget);
9571   case ISD::FP_TO_SINT:
9572   case ISD::FP_TO_UINT:
9573     return performFpToIntCombine(N, DAG, Subtarget);
9574   case ISD::FDIV:
9575     return performFDivCombine(N, DAG, Subtarget);
9576   case ISD::OR:
9577     return performORCombine(N, DCI, Subtarget);
9578   case ISD::INTRINSIC_WO_CHAIN:
9579     return performIntrinsicCombine(N, DCI, Subtarget);
9580   case ISD::ANY_EXTEND:
9581   case ISD::ZERO_EXTEND:
9582   case ISD::SIGN_EXTEND:
9583     return performExtendCombine(N, DCI, DAG);
9584   case ISD::BITCAST:
9585     return performBitcastCombine(N, DCI, DAG);
9586   case ISD::CONCAT_VECTORS:
9587     return performConcatVectorsCombine(N, DCI, DAG);
9588   case ISD::SELECT: {
9589     SDValue RV = performSelectCombine(N, DCI);
9590     if (!RV.getNode())
9591       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9592     return RV;
9593   }
9594   case ISD::VSELECT:
9595     return performVSelectCombine(N, DCI.DAG);
9596   case ISD::STORE:
9597     return performSTORECombine(N, DCI, DAG, Subtarget);
9598   case AArch64ISD::BRCOND:
9599     return performBRCONDCombine(N, DCI, DAG);
9600   case AArch64ISD::CSEL:
9601     return performCONDCombine(N, DCI, DAG, 2, 3);
9602   case AArch64ISD::DUP:
9603     return performPostLD1Combine(N, DCI, false);
9604   case AArch64ISD::NVCAST:
9605     return performNVCASTCombine(N);
9606   case ISD::INSERT_VECTOR_ELT:
9607     return performPostLD1Combine(N, DCI, true);
9608   case ISD::EXTRACT_VECTOR_ELT:
9609     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9610   case ISD::INTRINSIC_VOID:
9611   case ISD::INTRINSIC_W_CHAIN:
9612     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9613     case Intrinsic::aarch64_neon_ld2:
9614     case Intrinsic::aarch64_neon_ld3:
9615     case Intrinsic::aarch64_neon_ld4:
9616     case Intrinsic::aarch64_neon_ld1x2:
9617     case Intrinsic::aarch64_neon_ld1x3:
9618     case Intrinsic::aarch64_neon_ld1x4:
9619     case Intrinsic::aarch64_neon_ld2lane:
9620     case Intrinsic::aarch64_neon_ld3lane:
9621     case Intrinsic::aarch64_neon_ld4lane:
9622     case Intrinsic::aarch64_neon_ld2r:
9623     case Intrinsic::aarch64_neon_ld3r:
9624     case Intrinsic::aarch64_neon_ld4r:
9625     case Intrinsic::aarch64_neon_st2:
9626     case Intrinsic::aarch64_neon_st3:
9627     case Intrinsic::aarch64_neon_st4:
9628     case Intrinsic::aarch64_neon_st1x2:
9629     case Intrinsic::aarch64_neon_st1x3:
9630     case Intrinsic::aarch64_neon_st1x4:
9631     case Intrinsic::aarch64_neon_st2lane:
9632     case Intrinsic::aarch64_neon_st3lane:
9633     case Intrinsic::aarch64_neon_st4lane:
9634       return performNEONPostLDSTCombine(N, DCI, DAG);
9635     default:
9636       break;
9637     }
9638   }
9639   return SDValue();
9640 }
9641
9642 // Check if the return value is used as only a return value, as otherwise
9643 // we can't perform a tail-call. In particular, we need to check for
9644 // target ISD nodes that are returns and any other "odd" constructs
9645 // that the generic analysis code won't necessarily catch.
9646 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9647                                                SDValue &Chain) const {
9648   if (N->getNumValues() != 1)
9649     return false;
9650   if (!N->hasNUsesOfValue(1, 0))
9651     return false;
9652
9653   SDValue TCChain = Chain;
9654   SDNode *Copy = *N->use_begin();
9655   if (Copy->getOpcode() == ISD::CopyToReg) {
9656     // If the copy has a glue operand, we conservatively assume it isn't safe to
9657     // perform a tail call.
9658     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9659         MVT::Glue)
9660       return false;
9661     TCChain = Copy->getOperand(0);
9662   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9663     return false;
9664
9665   bool HasRet = false;
9666   for (SDNode *Node : Copy->uses()) {
9667     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9668       return false;
9669     HasRet = true;
9670   }
9671
9672   if (!HasRet)
9673     return false;
9674
9675   Chain = TCChain;
9676   return true;
9677 }
9678
9679 // Return whether the an instruction can potentially be optimized to a tail
9680 // call. This will cause the optimizers to attempt to move, or duplicate,
9681 // return instructions to help enable tail call optimizations for this
9682 // instruction.
9683 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9684   if (!CI->isTailCall())
9685     return false;
9686
9687   return true;
9688 }
9689
9690 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9691                                                    SDValue &Offset,
9692                                                    ISD::MemIndexedMode &AM,
9693                                                    bool &IsInc,
9694                                                    SelectionDAG &DAG) const {
9695   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9696     return false;
9697
9698   Base = Op->getOperand(0);
9699   // All of the indexed addressing mode instructions take a signed
9700   // 9 bit immediate offset.
9701   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9702     int64_t RHSC = (int64_t)RHS->getZExtValue();
9703     if (RHSC >= 256 || RHSC <= -256)
9704       return false;
9705     IsInc = (Op->getOpcode() == ISD::ADD);
9706     Offset = Op->getOperand(1);
9707     return true;
9708   }
9709   return false;
9710 }
9711
9712 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9713                                                       SDValue &Offset,
9714                                                       ISD::MemIndexedMode &AM,
9715                                                       SelectionDAG &DAG) const {
9716   EVT VT;
9717   SDValue Ptr;
9718   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9719     VT = LD->getMemoryVT();
9720     Ptr = LD->getBasePtr();
9721   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9722     VT = ST->getMemoryVT();
9723     Ptr = ST->getBasePtr();
9724   } else
9725     return false;
9726
9727   bool IsInc;
9728   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9729     return false;
9730   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9731   return true;
9732 }
9733
9734 bool AArch64TargetLowering::getPostIndexedAddressParts(
9735     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9736     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9737   EVT VT;
9738   SDValue Ptr;
9739   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9740     VT = LD->getMemoryVT();
9741     Ptr = LD->getBasePtr();
9742   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9743     VT = ST->getMemoryVT();
9744     Ptr = ST->getBasePtr();
9745   } else
9746     return false;
9747
9748   bool IsInc;
9749   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9750     return false;
9751   // Post-indexing updates the base, so it's not a valid transform
9752   // if that's not the same as the load's pointer.
9753   if (Ptr != Base)
9754     return false;
9755   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9756   return true;
9757 }
9758
9759 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9760                                   SelectionDAG &DAG) {
9761   SDLoc DL(N);
9762   SDValue Op = N->getOperand(0);
9763
9764   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9765     return;
9766
9767   Op = SDValue(
9768       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9769                          DAG.getUNDEF(MVT::i32), Op,
9770                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9771       0);
9772   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9773   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9774 }
9775
9776 static void ReplaceReductionResults(SDNode *N,
9777                                     SmallVectorImpl<SDValue> &Results,
9778                                     SelectionDAG &DAG, unsigned InterOp,
9779                                     unsigned AcrossOp) {
9780   EVT LoVT, HiVT;
9781   SDValue Lo, Hi;
9782   SDLoc dl(N);
9783   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9784   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9785   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9786   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9787   Results.push_back(SplitVal);
9788 }
9789
9790 void AArch64TargetLowering::ReplaceNodeResults(
9791     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9792   switch (N->getOpcode()) {
9793   default:
9794     llvm_unreachable("Don't know how to custom expand this");
9795   case ISD::BITCAST:
9796     ReplaceBITCASTResults(N, Results, DAG);
9797     return;
9798   case AArch64ISD::SADDV:
9799     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9800     return;
9801   case AArch64ISD::UADDV:
9802     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9803     return;
9804   case AArch64ISD::SMINV:
9805     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9806     return;
9807   case AArch64ISD::UMINV:
9808     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9809     return;
9810   case AArch64ISD::SMAXV:
9811     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9812     return;
9813   case AArch64ISD::UMAXV:
9814     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9815     return;
9816   case ISD::FP_TO_UINT:
9817   case ISD::FP_TO_SINT:
9818     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9819     // Let normal code take care of it by not adding anything to Results.
9820     return;
9821   }
9822 }
9823
9824 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9825   return true;
9826 }
9827
9828 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9829   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9830   // reciprocal if there are three or more FDIVs.
9831   return 3;
9832 }
9833
9834 TargetLoweringBase::LegalizeTypeAction
9835 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9836   MVT SVT = VT.getSimpleVT();
9837   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9838   // v4i16, v2i32 instead of to promote.
9839   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9840       || SVT == MVT::v1f32)
9841     return TypeWidenVector;
9842
9843   return TargetLoweringBase::getPreferredVectorAction(VT);
9844 }
9845
9846 // Loads and stores less than 128-bits are already atomic; ones above that
9847 // are doomed anyway, so defer to the default libcall and blame the OS when
9848 // things go wrong.
9849 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9850   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9851   return Size == 128;
9852 }
9853
9854 // Loads and stores less than 128-bits are already atomic; ones above that
9855 // are doomed anyway, so defer to the default libcall and blame the OS when
9856 // things go wrong.
9857 TargetLowering::AtomicExpansionKind
9858 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9859   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9860   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9861 }
9862
9863 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9864 TargetLowering::AtomicExpansionKind
9865 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9866   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9867   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9868 }
9869
9870 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9871     AtomicCmpXchgInst *AI) const {
9872   return true;
9873 }
9874
9875 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9876                                              AtomicOrdering Ord) const {
9877   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9878   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9879   bool IsAcquire = isAtLeastAcquire(Ord);
9880
9881   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9882   // intrinsic must return {i64, i64} and we have to recombine them into a
9883   // single i128 here.
9884   if (ValTy->getPrimitiveSizeInBits() == 128) {
9885     Intrinsic::ID Int =
9886         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9887     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9888
9889     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9890     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9891
9892     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9893     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9894     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9895     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9896     return Builder.CreateOr(
9897         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9898   }
9899
9900   Type *Tys[] = { Addr->getType() };
9901   Intrinsic::ID Int =
9902       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9903   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9904
9905   return Builder.CreateTruncOrBitCast(
9906       Builder.CreateCall(Ldxr, Addr),
9907       cast<PointerType>(Addr->getType())->getElementType());
9908 }
9909
9910 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9911     IRBuilder<> &Builder) const {
9912   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9913   Builder.CreateCall(
9914       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9915 }
9916
9917 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9918                                                    Value *Val, Value *Addr,
9919                                                    AtomicOrdering Ord) const {
9920   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9921   bool IsRelease = isAtLeastRelease(Ord);
9922
9923   // Since the intrinsics must have legal type, the i128 intrinsics take two
9924   // parameters: "i64, i64". We must marshal Val into the appropriate form
9925   // before the call.
9926   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9927     Intrinsic::ID Int =
9928         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9929     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9930     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9931
9932     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9933     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9934     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9935     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9936   }
9937
9938   Intrinsic::ID Int =
9939       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9940   Type *Tys[] = { Addr->getType() };
9941   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9942
9943   return Builder.CreateCall(Stxr,
9944                             {Builder.CreateZExtOrBitCast(
9945                                  Val, Stxr->getFunctionType()->getParamType(0)),
9946                              Addr});
9947 }
9948
9949 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9950     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9951   return Ty->isArrayTy();
9952 }
9953
9954 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9955                                                             EVT) const {
9956   return false;
9957 }
9958
9959 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9960   if (!Subtarget->isTargetAndroid())
9961     return TargetLowering::getSafeStackPointerLocation(IRB);
9962
9963   // Android provides a fixed TLS slot for the SafeStack pointer. See the
9964   // definition of TLS_SLOT_SAFESTACK in
9965   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
9966   const unsigned TlsOffset = 0x48;
9967   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
9968   Function *ThreadPointerFunc =
9969       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
9970   return IRB.CreatePointerCast(
9971       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
9972       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
9973 }