Fix comment typo (test commit). NFC
[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 namespace {
44 enum AlignMode {
45   StrictAlign,
46   NoStrictAlign
47 };
48 }
49
50 static cl::opt<AlignMode>
51 Align(cl::desc("Load/store alignment support"),
52       cl::Hidden, cl::init(NoStrictAlign),
53       cl::values(
54           clEnumValN(StrictAlign,   "aarch64-strict-align",
55                      "Disallow all unaligned memory accesses"),
56           clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
57                      "Allow unaligned memory accesses"),
58           clEnumValEnd));
59
60 // Place holder until extr generation is tested fully.
61 static cl::opt<bool>
62 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
63                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
64                           cl::init(true));
65
66 static cl::opt<bool>
67 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
68                            cl::desc("Allow AArch64 SLI/SRI formation"),
69                            cl::init(false));
70
71 // FIXME: The necessary dtprel relocations don't seem to be supported
72 // well in the GNU bfd and gold linkers at the moment. Therefore, by
73 // default, for now, fall back to GeneralDynamic code generation.
74 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
75     "aarch64-elf-ldtls-generation", cl::Hidden,
76     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
77     cl::init(false));
78
79 /// Value type used for condition codes.
80 static const MVT MVT_CC = MVT::i32;
81
82 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
83                                              const AArch64Subtarget &STI)
84     : TargetLowering(TM), Subtarget(&STI) {
85
86   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
87   // we have to make something up. Arbitrarily, choose ZeroOrOne.
88   setBooleanContents(ZeroOrOneBooleanContent);
89   // When comparing vectors the result sets the different elements in the
90   // vector to all-one or all-zero.
91   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
92
93   // Set up the register classes.
94   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
95   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
96
97   if (Subtarget->hasFPARMv8()) {
98     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
99     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
100     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
101     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
102   }
103
104   if (Subtarget->hasNEON()) {
105     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
106     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
107     // Someone set us up the NEON.
108     addDRTypeForNEON(MVT::v2f32);
109     addDRTypeForNEON(MVT::v8i8);
110     addDRTypeForNEON(MVT::v4i16);
111     addDRTypeForNEON(MVT::v2i32);
112     addDRTypeForNEON(MVT::v1i64);
113     addDRTypeForNEON(MVT::v1f64);
114     addDRTypeForNEON(MVT::v4f16);
115
116     addQRTypeForNEON(MVT::v4f32);
117     addQRTypeForNEON(MVT::v2f64);
118     addQRTypeForNEON(MVT::v16i8);
119     addQRTypeForNEON(MVT::v8i16);
120     addQRTypeForNEON(MVT::v4i32);
121     addQRTypeForNEON(MVT::v2i64);
122     addQRTypeForNEON(MVT::v8f16);
123   }
124
125   // Compute derived properties from the register classes
126   computeRegisterProperties(Subtarget->getRegisterInfo());
127
128   // Provide all sorts of operation actions
129   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
130   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
131   setOperationAction(ISD::SETCC, MVT::i32, Custom);
132   setOperationAction(ISD::SETCC, MVT::i64, Custom);
133   setOperationAction(ISD::SETCC, MVT::f32, Custom);
134   setOperationAction(ISD::SETCC, MVT::f64, Custom);
135   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
136   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
137   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
138   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
139   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
140   setOperationAction(ISD::SELECT, MVT::i32, Custom);
141   setOperationAction(ISD::SELECT, MVT::i64, Custom);
142   setOperationAction(ISD::SELECT, MVT::f32, Custom);
143   setOperationAction(ISD::SELECT, MVT::f64, Custom);
144   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
145   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
146   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
147   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
148   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
149   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
150
151   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
152   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
153   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
154
155   setOperationAction(ISD::FREM, MVT::f32, Expand);
156   setOperationAction(ISD::FREM, MVT::f64, Expand);
157   setOperationAction(ISD::FREM, MVT::f80, Expand);
158
159   // Custom lowering hooks are needed for XOR
160   // to fold it into CSINC/CSINV.
161   setOperationAction(ISD::XOR, MVT::i32, Custom);
162   setOperationAction(ISD::XOR, MVT::i64, Custom);
163
164   // Virtually no operation on f128 is legal, but LLVM can't expand them when
165   // there's a valid register class, so we need custom operations in most cases.
166   setOperationAction(ISD::FABS, MVT::f128, Expand);
167   setOperationAction(ISD::FADD, MVT::f128, Custom);
168   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
169   setOperationAction(ISD::FCOS, MVT::f128, Expand);
170   setOperationAction(ISD::FDIV, MVT::f128, Custom);
171   setOperationAction(ISD::FMA, MVT::f128, Expand);
172   setOperationAction(ISD::FMUL, MVT::f128, Custom);
173   setOperationAction(ISD::FNEG, MVT::f128, Expand);
174   setOperationAction(ISD::FPOW, MVT::f128, Expand);
175   setOperationAction(ISD::FREM, MVT::f128, Expand);
176   setOperationAction(ISD::FRINT, MVT::f128, Expand);
177   setOperationAction(ISD::FSIN, MVT::f128, Expand);
178   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
179   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
180   setOperationAction(ISD::FSUB, MVT::f128, Custom);
181   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
182   setOperationAction(ISD::SETCC, MVT::f128, Custom);
183   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
184   setOperationAction(ISD::SELECT, MVT::f128, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
186   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
187
188   // Lowering for many of the conversions is actually specified by the non-f128
189   // type. The LowerXXX function will be trivial when f128 isn't involved.
190   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
191   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
192   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
193   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
194   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
195   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
196   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
197   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
198   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
199   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
200   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
201   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
202   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
203   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
204
205   // Variable arguments.
206   setOperationAction(ISD::VASTART, MVT::Other, Custom);
207   setOperationAction(ISD::VAARG, MVT::Other, Custom);
208   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
209   setOperationAction(ISD::VAEND, MVT::Other, Expand);
210
211   // Variable-sized objects.
212   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
215
216   // Exception handling.
217   // FIXME: These are guesses. Has this been defined yet?
218   setExceptionPointerRegister(AArch64::X0);
219   setExceptionSelectorRegister(AArch64::X1);
220
221   // Constant pool entries
222   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
223
224   // BlockAddress
225   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
226
227   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
228   setOperationAction(ISD::ADDC, MVT::i32, Custom);
229   setOperationAction(ISD::ADDE, MVT::i32, Custom);
230   setOperationAction(ISD::SUBC, MVT::i32, Custom);
231   setOperationAction(ISD::SUBE, MVT::i32, Custom);
232   setOperationAction(ISD::ADDC, MVT::i64, Custom);
233   setOperationAction(ISD::ADDE, MVT::i64, Custom);
234   setOperationAction(ISD::SUBC, MVT::i64, Custom);
235   setOperationAction(ISD::SUBE, MVT::i64, Custom);
236
237   // AArch64 lacks both left-rotate and popcount instructions.
238   setOperationAction(ISD::ROTL, MVT::i32, Expand);
239   setOperationAction(ISD::ROTL, MVT::i64, Expand);
240
241   // AArch64 doesn't have {U|S}MUL_LOHI.
242   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
243   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
244
245
246   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
247   // counterparts, which AArch64 supports directly.
248   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
249   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
250   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
251   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
252
253   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
254   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
255
256   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
257   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
258   setOperationAction(ISD::SREM, MVT::i32, Expand);
259   setOperationAction(ISD::SREM, MVT::i64, Expand);
260   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
262   setOperationAction(ISD::UREM, MVT::i32, Expand);
263   setOperationAction(ISD::UREM, MVT::i64, Expand);
264
265   // Custom lower Add/Sub/Mul with overflow.
266   setOperationAction(ISD::SADDO, MVT::i32, Custom);
267   setOperationAction(ISD::SADDO, MVT::i64, Custom);
268   setOperationAction(ISD::UADDO, MVT::i32, Custom);
269   setOperationAction(ISD::UADDO, MVT::i64, Custom);
270   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
271   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
272   setOperationAction(ISD::USUBO, MVT::i32, Custom);
273   setOperationAction(ISD::USUBO, MVT::i64, Custom);
274   setOperationAction(ISD::SMULO, MVT::i32, Custom);
275   setOperationAction(ISD::SMULO, MVT::i64, Custom);
276   setOperationAction(ISD::UMULO, MVT::i32, Custom);
277   setOperationAction(ISD::UMULO, MVT::i64, Custom);
278
279   setOperationAction(ISD::FSIN, MVT::f32, Expand);
280   setOperationAction(ISD::FSIN, MVT::f64, Expand);
281   setOperationAction(ISD::FCOS, MVT::f32, Expand);
282   setOperationAction(ISD::FCOS, MVT::f64, Expand);
283   setOperationAction(ISD::FPOW, MVT::f32, Expand);
284   setOperationAction(ISD::FPOW, MVT::f64, Expand);
285   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
287
288   // f16 is a storage-only type, always promote it to f32.
289   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
290   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
291   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
292   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
293   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
294   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
295   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
296   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
297   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
298   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
299   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
300   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
301   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
302   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
303   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
304   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
305   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
306   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
307   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
308   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
309   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
310   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
311   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
312   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
313   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
314   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
315   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
316   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
317   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
318   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
319   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
320   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
321
322   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
323   // known to be safe.
324   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
325   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
326   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
327   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
328   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
329   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
330   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
331   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
332   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
333   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
334   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
335   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
336
337   // Expand all other v4f16 operations.
338   // FIXME: We could generate better code by promoting some operations to
339   // a pair of v4f32s
340   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
341   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
342   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
343   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
344   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
345   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
346   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
347   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
348   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
349   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
350   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
351   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
352   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
353   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
354   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
355   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
356   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
357   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
358   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
359   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
360   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
361   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
362   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
363   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
364   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
365   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
366
367
368   // v8f16 is also a storage-only type, so expand it.
369   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
370   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
371   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
372   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
373   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
374   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
375   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
376   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
377   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
378   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
379   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
380   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
381   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
382   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
383   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
384   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
385   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
386   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
387   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
388   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
389   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
390   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
391   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
392   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
393   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
394   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
395   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
396   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
397   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
398   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
399   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
400
401   // AArch64 has implementations of a lot of rounding-like FP operations.
402   for (MVT Ty : {MVT::f32, MVT::f64}) {
403     setOperationAction(ISD::FFLOOR, Ty, Legal);
404     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
405     setOperationAction(ISD::FCEIL, Ty, Legal);
406     setOperationAction(ISD::FRINT, Ty, Legal);
407     setOperationAction(ISD::FTRUNC, Ty, Legal);
408     setOperationAction(ISD::FROUND, Ty, Legal);
409   }
410
411   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
412
413   if (Subtarget->isTargetMachO()) {
414     // For iOS, we don't want to the normal expansion of a libcall to
415     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
416     // traffic.
417     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
418     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
419   } else {
420     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
421     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
422   }
423
424   // Make floating-point constants legal for the large code model, so they don't
425   // become loads from the constant pool.
426   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
427     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
428     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
429   }
430
431   // AArch64 does not have floating-point extending loads, i1 sign-extending
432   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
433   for (MVT VT : MVT::fp_valuetypes()) {
434     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
435     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
436     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
437     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
438   }
439   for (MVT VT : MVT::integer_valuetypes())
440     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
441
442   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
443   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
444   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
445   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
446   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
447   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
448   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
449
450   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
451   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
452
453   // Indexed loads and stores are supported.
454   for (unsigned im = (unsigned)ISD::PRE_INC;
455        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
456     setIndexedLoadAction(im, MVT::i8, Legal);
457     setIndexedLoadAction(im, MVT::i16, Legal);
458     setIndexedLoadAction(im, MVT::i32, Legal);
459     setIndexedLoadAction(im, MVT::i64, Legal);
460     setIndexedLoadAction(im, MVT::f64, Legal);
461     setIndexedLoadAction(im, MVT::f32, Legal);
462     setIndexedStoreAction(im, MVT::i8, Legal);
463     setIndexedStoreAction(im, MVT::i16, Legal);
464     setIndexedStoreAction(im, MVT::i32, Legal);
465     setIndexedStoreAction(im, MVT::i64, Legal);
466     setIndexedStoreAction(im, MVT::f64, Legal);
467     setIndexedStoreAction(im, MVT::f32, 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::INTRINSIC_WO_CHAIN);
486
487   setTargetDAGCombine(ISD::ANY_EXTEND);
488   setTargetDAGCombine(ISD::ZERO_EXTEND);
489   setTargetDAGCombine(ISD::SIGN_EXTEND);
490   setTargetDAGCombine(ISD::BITCAST);
491   setTargetDAGCombine(ISD::CONCAT_VECTORS);
492   setTargetDAGCombine(ISD::STORE);
493
494   setTargetDAGCombine(ISD::MUL);
495
496   setTargetDAGCombine(ISD::SELECT);
497   setTargetDAGCombine(ISD::VSELECT);
498   setTargetDAGCombine(ISD::SELECT_CC);
499
500   setTargetDAGCombine(ISD::INTRINSIC_VOID);
501   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
503
504   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
505   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
506   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
507
508   setStackPointerRegisterToSaveRestore(AArch64::SP);
509
510   setSchedulingPreference(Sched::Hybrid);
511
512   // Enable TBZ/TBNZ
513   MaskAndBranchFoldingIsLegal = true;
514   EnableExtLdPromotion = true;
515
516   setMinFunctionAlignment(2);
517
518   RequireStrictAlign = (Align == StrictAlign);
519
520   setHasExtractBitsInsn(true);
521
522   if (Subtarget->hasNEON()) {
523     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
524     // silliness like this:
525     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
526     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
528     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
529     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
532     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
533     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
534     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
535     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
536     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
537     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
538     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
539     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
542     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
543     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
544     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
545     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
546     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
547     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
548     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
549     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
550
551     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
552     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
553     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
554     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
555     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
556
557     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
558
559     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
560     // elements smaller than i32, so promote the input to i32 first.
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
564     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
565     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
566     // -> v8f16 conversions.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
571     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
576     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
577     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
578     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
580
581     // AArch64 doesn't have MUL.2d:
582     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
583     // Custom handling for some quad-vector types to detect MULL.
584     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
585     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
586     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
587
588     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
589     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
590     // Likewise, narrowing and extending vector loads/stores aren't handled
591     // directly.
592     for (MVT VT : MVT::vector_valuetypes()) {
593       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
594
595       setOperationAction(ISD::MULHS, VT, Expand);
596       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
597       setOperationAction(ISD::MULHU, VT, Expand);
598       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
599
600       setOperationAction(ISD::BSWAP, VT, Expand);
601
602       for (MVT InnerVT : MVT::vector_valuetypes()) {
603         setTruncStoreAction(VT, InnerVT, Expand);
604         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
607       }
608     }
609
610     // AArch64 has implementations of a lot of rounding-like FP operations.
611     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
612       setOperationAction(ISD::FFLOOR, Ty, Legal);
613       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
614       setOperationAction(ISD::FCEIL, Ty, Legal);
615       setOperationAction(ISD::FRINT, Ty, Legal);
616       setOperationAction(ISD::FTRUNC, Ty, Legal);
617       setOperationAction(ISD::FROUND, Ty, Legal);
618     }
619   }
620
621   // Prefer likely predicted branches to selects on out-of-order cores.
622   if (Subtarget->isCortexA57())
623     PredictableSelectIsExpensive = true;
624 }
625
626 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
627   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
628     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
629     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
630
631     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
632     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
633   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
634     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
635     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
636
637     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
638     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
639   }
640
641   // Mark vector float intrinsics as expand.
642   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
643     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
652   }
653
654   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
655   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
656   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
657   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
666
667   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
668   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
669   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
670   for (MVT InnerVT : MVT::all_valuetypes())
671     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
672
673   // CNT supports only B element sizes.
674   if (VT != MVT::v8i8 && VT != MVT::v16i8)
675     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
676
677   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
678   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
679   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
680   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
681   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
682
683   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
684   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
685
686   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
687   // i64.
688   if (!VT.isFloatingPoint() &&
689       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
690     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
691                             ISD::SABSDIFF, ISD::UABSDIFF})
692       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
693
694   if (Subtarget->isLittleEndian()) {
695     for (unsigned im = (unsigned)ISD::PRE_INC;
696          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
697       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
698       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
699     }
700   }
701 }
702
703 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
704   addRegisterClass(VT, &AArch64::FPR64RegClass);
705   addTypeForNEON(VT, MVT::v2i32);
706 }
707
708 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
709   addRegisterClass(VT, &AArch64::FPR128RegClass);
710   addTypeForNEON(VT, MVT::v4i32);
711 }
712
713 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
714                                               EVT VT) const {
715   if (!VT.isVector())
716     return MVT::i32;
717   return VT.changeVectorElementTypeToInteger();
718 }
719
720 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
721 /// Mask are known to be either zero or one and return them in the
722 /// KnownZero/KnownOne bitsets.
723 void AArch64TargetLowering::computeKnownBitsForTargetNode(
724     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
725     const SelectionDAG &DAG, unsigned Depth) const {
726   switch (Op.getOpcode()) {
727   default:
728     break;
729   case AArch64ISD::CSEL: {
730     APInt KnownZero2, KnownOne2;
731     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
732     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
733     KnownZero &= KnownZero2;
734     KnownOne &= KnownOne2;
735     break;
736   }
737   case ISD::INTRINSIC_W_CHAIN: {
738    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
739     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
740     switch (IntID) {
741     default: return;
742     case Intrinsic::aarch64_ldaxr:
743     case Intrinsic::aarch64_ldxr: {
744       unsigned BitWidth = KnownOne.getBitWidth();
745       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
746       unsigned MemBits = VT.getScalarType().getSizeInBits();
747       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
748       return;
749     }
750     }
751     break;
752   }
753   case ISD::INTRINSIC_WO_CHAIN:
754   case ISD::INTRINSIC_VOID: {
755     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
756     switch (IntNo) {
757     default:
758       break;
759     case Intrinsic::aarch64_neon_umaxv:
760     case Intrinsic::aarch64_neon_uminv: {
761       // Figure out the datatype of the vector operand. The UMINV instruction
762       // will zero extend the result, so we can mark as known zero all the
763       // bits larger than the element datatype. 32-bit or larget doesn't need
764       // this as those are legal types and will be handled by isel directly.
765       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
766       unsigned BitWidth = KnownZero.getBitWidth();
767       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
768         assert(BitWidth >= 8 && "Unexpected width!");
769         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
770         KnownZero |= Mask;
771       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
772         assert(BitWidth >= 16 && "Unexpected width!");
773         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
774         KnownZero |= Mask;
775       }
776       break;
777     } break;
778     }
779   }
780   }
781 }
782
783 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
784                                                   EVT) const {
785   return MVT::i64;
786 }
787
788 FastISel *
789 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
790                                       const TargetLibraryInfo *libInfo) const {
791   return AArch64::createFastISel(funcInfo, libInfo);
792 }
793
794 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
795   switch ((AArch64ISD::NodeType)Opcode) {
796   case AArch64ISD::FIRST_NUMBER:      break;
797   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
798   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
799   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
800   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
801   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
802   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
803   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
804   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
805   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
806   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
807   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
808   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
809   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
810   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
811   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
812   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
813   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
814   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
815   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
816   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
817   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
818   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
819   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
820   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
821   case AArch64ISD::FMIN:              return "AArch64ISD::FMIN";
822   case AArch64ISD::FMAX:              return "AArch64ISD::FMAX";
823   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
824   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
825   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
826   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
827   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
828   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
829   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
830   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
831   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
832   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
833   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
834   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
835   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
836   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
837   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
838   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
839   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
840   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
841   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
842   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
843   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
844   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
845   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
846   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
847   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
848   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
849   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
850   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
851   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
852   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
853   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
854   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
855   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
856   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
857   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
858   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
859   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
860   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
861   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
862   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
863   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
864   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
865   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
866   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
867   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
868   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
869   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
870   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
871   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
872   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
873   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
874   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
875   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
876   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
877   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
878   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
879   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
880   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
881   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
882   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
883   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
884   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
885   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
886   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
887   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
888   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
889   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
890   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
891   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
892   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
893   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
894   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
895   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
896   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
897   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
898   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
899   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
900   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
901   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
902   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
903   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
904   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
905   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
906   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
907   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
908   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
909   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
910   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
911   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
912   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
913   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
914   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
915   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
916   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
917   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
918   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
919   }
920   return nullptr;
921 }
922
923 MachineBasicBlock *
924 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
925                                     MachineBasicBlock *MBB) const {
926   // We materialise the F128CSEL pseudo-instruction as some control flow and a
927   // phi node:
928
929   // OrigBB:
930   //     [... previous instrs leading to comparison ...]
931   //     b.ne TrueBB
932   //     b EndBB
933   // TrueBB:
934   //     ; Fallthrough
935   // EndBB:
936   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
937
938   MachineFunction *MF = MBB->getParent();
939   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
940   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
941   DebugLoc DL = MI->getDebugLoc();
942   MachineFunction::iterator It = MBB;
943   ++It;
944
945   unsigned DestReg = MI->getOperand(0).getReg();
946   unsigned IfTrueReg = MI->getOperand(1).getReg();
947   unsigned IfFalseReg = MI->getOperand(2).getReg();
948   unsigned CondCode = MI->getOperand(3).getImm();
949   bool NZCVKilled = MI->getOperand(4).isKill();
950
951   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
952   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
953   MF->insert(It, TrueBB);
954   MF->insert(It, EndBB);
955
956   // Transfer rest of current basic-block to EndBB
957   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
958                 MBB->end());
959   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
960
961   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
962   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
963   MBB->addSuccessor(TrueBB);
964   MBB->addSuccessor(EndBB);
965
966   // TrueBB falls through to the end.
967   TrueBB->addSuccessor(EndBB);
968
969   if (!NZCVKilled) {
970     TrueBB->addLiveIn(AArch64::NZCV);
971     EndBB->addLiveIn(AArch64::NZCV);
972   }
973
974   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
975       .addReg(IfTrueReg)
976       .addMBB(TrueBB)
977       .addReg(IfFalseReg)
978       .addMBB(MBB);
979
980   MI->eraseFromParent();
981   return EndBB;
982 }
983
984 MachineBasicBlock *
985 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
986                                                  MachineBasicBlock *BB) const {
987   switch (MI->getOpcode()) {
988   default:
989 #ifndef NDEBUG
990     MI->dump();
991 #endif
992     llvm_unreachable("Unexpected instruction for custom inserter!");
993
994   case AArch64::F128CSEL:
995     return EmitF128CSEL(MI, BB);
996
997   case TargetOpcode::STACKMAP:
998   case TargetOpcode::PATCHPOINT:
999     return emitPatchPoint(MI, BB);
1000   }
1001 }
1002
1003 //===----------------------------------------------------------------------===//
1004 // AArch64 Lowering private implementation.
1005 //===----------------------------------------------------------------------===//
1006
1007 //===----------------------------------------------------------------------===//
1008 // Lowering Code
1009 //===----------------------------------------------------------------------===//
1010
1011 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1012 /// CC
1013 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1014   switch (CC) {
1015   default:
1016     llvm_unreachable("Unknown condition code!");
1017   case ISD::SETNE:
1018     return AArch64CC::NE;
1019   case ISD::SETEQ:
1020     return AArch64CC::EQ;
1021   case ISD::SETGT:
1022     return AArch64CC::GT;
1023   case ISD::SETGE:
1024     return AArch64CC::GE;
1025   case ISD::SETLT:
1026     return AArch64CC::LT;
1027   case ISD::SETLE:
1028     return AArch64CC::LE;
1029   case ISD::SETUGT:
1030     return AArch64CC::HI;
1031   case ISD::SETUGE:
1032     return AArch64CC::HS;
1033   case ISD::SETULT:
1034     return AArch64CC::LO;
1035   case ISD::SETULE:
1036     return AArch64CC::LS;
1037   }
1038 }
1039
1040 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1041 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1042                                   AArch64CC::CondCode &CondCode,
1043                                   AArch64CC::CondCode &CondCode2) {
1044   CondCode2 = AArch64CC::AL;
1045   switch (CC) {
1046   default:
1047     llvm_unreachable("Unknown FP condition!");
1048   case ISD::SETEQ:
1049   case ISD::SETOEQ:
1050     CondCode = AArch64CC::EQ;
1051     break;
1052   case ISD::SETGT:
1053   case ISD::SETOGT:
1054     CondCode = AArch64CC::GT;
1055     break;
1056   case ISD::SETGE:
1057   case ISD::SETOGE:
1058     CondCode = AArch64CC::GE;
1059     break;
1060   case ISD::SETOLT:
1061     CondCode = AArch64CC::MI;
1062     break;
1063   case ISD::SETOLE:
1064     CondCode = AArch64CC::LS;
1065     break;
1066   case ISD::SETONE:
1067     CondCode = AArch64CC::MI;
1068     CondCode2 = AArch64CC::GT;
1069     break;
1070   case ISD::SETO:
1071     CondCode = AArch64CC::VC;
1072     break;
1073   case ISD::SETUO:
1074     CondCode = AArch64CC::VS;
1075     break;
1076   case ISD::SETUEQ:
1077     CondCode = AArch64CC::EQ;
1078     CondCode2 = AArch64CC::VS;
1079     break;
1080   case ISD::SETUGT:
1081     CondCode = AArch64CC::HI;
1082     break;
1083   case ISD::SETUGE:
1084     CondCode = AArch64CC::PL;
1085     break;
1086   case ISD::SETLT:
1087   case ISD::SETULT:
1088     CondCode = AArch64CC::LT;
1089     break;
1090   case ISD::SETLE:
1091   case ISD::SETULE:
1092     CondCode = AArch64CC::LE;
1093     break;
1094   case ISD::SETNE:
1095   case ISD::SETUNE:
1096     CondCode = AArch64CC::NE;
1097     break;
1098   }
1099 }
1100
1101 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1102 /// CC usable with the vector instructions. Fewer operations are available
1103 /// without a real NZCV register, so we have to use less efficient combinations
1104 /// to get the same effect.
1105 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1106                                         AArch64CC::CondCode &CondCode,
1107                                         AArch64CC::CondCode &CondCode2,
1108                                         bool &Invert) {
1109   Invert = false;
1110   switch (CC) {
1111   default:
1112     // Mostly the scalar mappings work fine.
1113     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1114     break;
1115   case ISD::SETUO:
1116     Invert = true; // Fallthrough
1117   case ISD::SETO:
1118     CondCode = AArch64CC::MI;
1119     CondCode2 = AArch64CC::GE;
1120     break;
1121   case ISD::SETUEQ:
1122   case ISD::SETULT:
1123   case ISD::SETULE:
1124   case ISD::SETUGT:
1125   case ISD::SETUGE:
1126     // All of the compare-mask comparisons are ordered, but we can switch
1127     // between the two by a double inversion. E.g. ULE == !OGT.
1128     Invert = true;
1129     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1130     break;
1131   }
1132 }
1133
1134 static bool isLegalArithImmed(uint64_t C) {
1135   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1136   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1137 }
1138
1139 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1140                               SDLoc dl, SelectionDAG &DAG) {
1141   EVT VT = LHS.getValueType();
1142
1143   if (VT.isFloatingPoint())
1144     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1145
1146   // The CMP instruction is just an alias for SUBS, and representing it as
1147   // SUBS means that it's possible to get CSE with subtract operations.
1148   // A later phase can perform the optimization of setting the destination
1149   // register to WZR/XZR if it ends up being unused.
1150   unsigned Opcode = AArch64ISD::SUBS;
1151
1152   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1153       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1154       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1155     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1156     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1157     // can be set differently by this operation. It comes down to whether
1158     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1159     // everything is fine. If not then the optimization is wrong. Thus general
1160     // comparisons are only valid if op2 != 0.
1161
1162     // So, finally, the only LLVM-native comparisons that don't mention C and V
1163     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1164     // the absence of information about op2.
1165     Opcode = AArch64ISD::ADDS;
1166     RHS = RHS.getOperand(1);
1167   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1168              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1169              !isUnsignedIntSetCC(CC)) {
1170     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1171     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1172     // of the signed comparisons.
1173     Opcode = AArch64ISD::ANDS;
1174     RHS = LHS.getOperand(1);
1175     LHS = LHS.getOperand(0);
1176   }
1177
1178   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1179       .getValue(1);
1180 }
1181
1182 /// \defgroup AArch64CCMP CMP;CCMP matching
1183 ///
1184 /// These functions deal with the formation of CMP;CCMP;... sequences.
1185 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1186 /// a comparison. They set the NZCV flags to a predefined value if their
1187 /// predicate is false. This allows to express arbitrary conjunctions, for
1188 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1189 /// expressed as:
1190 ///   cmp A
1191 ///   ccmp B, inv(CB), CA
1192 ///   check for CB flags
1193 ///
1194 /// In general we can create code for arbitrary "... (and (and A B) C)"
1195 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1196 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1197 /// negation operations:
1198 /// We can negate the results of a single comparison by inverting the flags
1199 /// used when the predicate fails and inverting the flags tested in the next
1200 /// instruction; We can also negate the results of the whole previous
1201 /// conditional compare sequence by inverting the flags tested in the next
1202 /// instruction. However there is no way to negate the result of a partial
1203 /// sequence.
1204 ///
1205 /// Therefore on encountering an "or" expression we can negate the subtree on
1206 /// one side and have to be able to push the negate to the leafs of the subtree
1207 /// on the other side (see also the comments in code). As complete example:
1208 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1209 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1210 /// is transformed to
1211 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1212 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1213 /// and implemented as:
1214 ///   cmp C
1215 ///   ccmp D, inv(CD), CC
1216 ///   ccmp A, CA, inv(CD)
1217 ///   ccmp B, CB, inv(CA)
1218 ///   check for CB flags
1219 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1220 /// by conditional compare sequences.
1221 /// @{
1222
1223 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1224 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1225                                          ISD::CondCode CC, SDValue CCOp,
1226                                          SDValue Condition, unsigned NZCV,
1227                                          SDLoc DL, SelectionDAG &DAG) {
1228   unsigned Opcode = 0;
1229   if (LHS.getValueType().isFloatingPoint())
1230     Opcode = AArch64ISD::FCCMP;
1231   else if (RHS.getOpcode() == ISD::SUB) {
1232     SDValue SubOp0 = RHS.getOperand(0);
1233     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1234       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1235         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1236         Opcode = AArch64ISD::CCMN;
1237         RHS = RHS.getOperand(1);
1238       }
1239   }
1240   if (Opcode == 0)
1241     Opcode = AArch64ISD::CCMP;
1242
1243   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1244   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1245 }
1246
1247 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1248 /// CanPushNegate is set to true if we can push a negate operation through
1249 /// the tree in a was that we are left with AND operations and negate operations
1250 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1251 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1252 /// brought into such a form.
1253 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1254                                          unsigned Depth = 0) {
1255   if (!Val.hasOneUse())
1256     return false;
1257   unsigned Opcode = Val->getOpcode();
1258   if (Opcode == ISD::SETCC) {
1259     CanPushNegate = true;
1260     return true;
1261   }
1262   // Protect against stack overflow.
1263   if (Depth > 15)
1264     return false;
1265   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1266     SDValue O0 = Val->getOperand(0);
1267     SDValue O1 = Val->getOperand(1);
1268     bool CanPushNegateL;
1269     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1270       return false;
1271     bool CanPushNegateR;
1272     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1273       return false;
1274     // We cannot push a negate through an AND operation (it would become an OR),
1275     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1276     // push the negate through the x/y subtrees.
1277     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1278     return true;
1279   }
1280   return false;
1281 }
1282
1283 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1284 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1285 /// Tries to transform the given i1 producing node @p Val to a series compare
1286 /// and conditional compare operations. @returns an NZCV flags producing node
1287 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1288 /// transformation was not possible.
1289 /// On recursive invocations @p PushNegate may be set to true to have negation
1290 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1291 /// for the comparisons in the current subtree; @p Depth limits the search
1292 /// depth to avoid stack overflow.
1293 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1294     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1295     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1296     unsigned Depth = 0) {
1297   // We're at a tree leaf, produce a conditional comparison operation.
1298   unsigned Opcode = Val->getOpcode();
1299   if (Opcode == ISD::SETCC) {
1300     SDValue LHS = Val->getOperand(0);
1301     SDValue RHS = Val->getOperand(1);
1302     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1303     bool isInteger = LHS.getValueType().isInteger();
1304     if (PushNegate)
1305       CC = getSetCCInverse(CC, isInteger);
1306     SDLoc DL(Val);
1307     // Determine OutCC and handle FP special case.
1308     if (isInteger) {
1309       OutCC = changeIntCCToAArch64CC(CC);
1310     } else {
1311       assert(LHS.getValueType().isFloatingPoint());
1312       AArch64CC::CondCode ExtraCC;
1313       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1314       // Surpisingly some floating point conditions can't be tested with a
1315       // single condition code. Construct an additional comparison in this case.
1316       // See comment below on how we deal with OR conditions.
1317       if (ExtraCC != AArch64CC::AL) {
1318         SDValue ExtraCmp;
1319         if (!CCOp.getNode())
1320           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1321         else {
1322           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1323           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1324           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1325           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1326                                                NZCV, DL, DAG);
1327         }
1328         CCOp = ExtraCmp;
1329         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1330         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1331       }
1332     }
1333
1334     // Produce a normal comparison if we are first in the chain
1335     if (!CCOp.getNode())
1336       return emitComparison(LHS, RHS, CC, DL, DAG);
1337     // Otherwise produce a ccmp.
1338     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1339     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1340     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1341     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1342                                      DAG);
1343   } else if (Opcode != ISD::AND && Opcode != ISD::OR)
1344     return SDValue();
1345
1346   assert((Opcode == ISD::OR || !PushNegate)
1347          && "Can only push negate through OR operation");
1348
1349   // Check if both sides can be transformed.
1350   SDValue LHS = Val->getOperand(0);
1351   SDValue RHS = Val->getOperand(1);
1352   bool CanPushNegateL;
1353   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1354     return SDValue();
1355   bool CanPushNegateR;
1356   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1357     return SDValue();
1358
1359   // Do we need to negate our operands?
1360   bool NegateOperands = Opcode == ISD::OR;
1361   // We can negate the results of all previous operations by inverting the
1362   // predicate flags giving us a free negation for one side. For the other side
1363   // we need to be able to push the negation to the leafs of the tree.
1364   if (NegateOperands) {
1365     if (!CanPushNegateL && !CanPushNegateR)
1366       return SDValue();
1367     // Order the side where we can push the negate through to LHS.
1368     if (!CanPushNegateL && CanPushNegateR) {
1369       std::swap(LHS, RHS);
1370       CanPushNegateL = true;
1371     }
1372   }
1373
1374   // Emit RHS. If we want to negate the tree we only need to push a negate
1375   // through if we are already in a PushNegate case, otherwise we can negate
1376   // the "flags to test" afterwards.
1377   AArch64CC::CondCode RHSCC;
1378   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1379                                                 CCOp, Predicate, Depth+1);
1380   if (NegateOperands && !PushNegate)
1381     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1382   // Emit LHS. We must push the negate through if we need to negate it.
1383   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1384                                                 CmpR, RHSCC, Depth+1);
1385   // If we transformed an OR to and AND then we have to negate the result
1386   // (or absorb a PushNegate resulting in a double negation).
1387   if (Opcode == ISD::OR && !PushNegate)
1388     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1389   return CmpL;
1390 }
1391
1392 /// @}
1393
1394 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1395                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1396   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1397     EVT VT = RHS.getValueType();
1398     uint64_t C = RHSC->getZExtValue();
1399     if (!isLegalArithImmed(C)) {
1400       // Constant does not fit, try adjusting it by one?
1401       switch (CC) {
1402       default:
1403         break;
1404       case ISD::SETLT:
1405       case ISD::SETGE:
1406         if ((VT == MVT::i32 && C != 0x80000000 &&
1407              isLegalArithImmed((uint32_t)(C - 1))) ||
1408             (VT == MVT::i64 && C != 0x80000000ULL &&
1409              isLegalArithImmed(C - 1ULL))) {
1410           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1411           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1412           RHS = DAG.getConstant(C, dl, VT);
1413         }
1414         break;
1415       case ISD::SETULT:
1416       case ISD::SETUGE:
1417         if ((VT == MVT::i32 && C != 0 &&
1418              isLegalArithImmed((uint32_t)(C - 1))) ||
1419             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1420           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1421           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1422           RHS = DAG.getConstant(C, dl, VT);
1423         }
1424         break;
1425       case ISD::SETLE:
1426       case ISD::SETGT:
1427         if ((VT == MVT::i32 && C != INT32_MAX &&
1428              isLegalArithImmed((uint32_t)(C + 1))) ||
1429             (VT == MVT::i64 && C != INT64_MAX &&
1430              isLegalArithImmed(C + 1ULL))) {
1431           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1432           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1433           RHS = DAG.getConstant(C, dl, VT);
1434         }
1435         break;
1436       case ISD::SETULE:
1437       case ISD::SETUGT:
1438         if ((VT == MVT::i32 && C != UINT32_MAX &&
1439              isLegalArithImmed((uint32_t)(C + 1))) ||
1440             (VT == MVT::i64 && C != UINT64_MAX &&
1441              isLegalArithImmed(C + 1ULL))) {
1442           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1443           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1444           RHS = DAG.getConstant(C, dl, VT);
1445         }
1446         break;
1447       }
1448     }
1449   }
1450   SDValue Cmp;
1451   AArch64CC::CondCode AArch64CC;
1452   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1453     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1454
1455     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1456     // For the i8 operand, the largest immediate is 255, so this can be easily
1457     // encoded in the compare instruction. For the i16 operand, however, the
1458     // largest immediate cannot be encoded in the compare.
1459     // Therefore, use a sign extending load and cmn to avoid materializing the
1460     // -1 constant. For example,
1461     // movz w1, #65535
1462     // ldrh w0, [x0, #0]
1463     // cmp w0, w1
1464     // >
1465     // ldrsh w0, [x0, #0]
1466     // cmn w0, #1
1467     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1468     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1469     // ensure both the LHS and RHS are truely zero extended and to make sure the
1470     // transformation is profitable.
1471     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1472         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1473         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1474         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1475       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1476       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1477         SDValue SExt =
1478             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1479                         DAG.getValueType(MVT::i16));
1480         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1481                                                    RHS.getValueType()),
1482                              CC, dl, DAG);
1483         AArch64CC = changeIntCCToAArch64CC(CC);
1484       }
1485     }
1486
1487     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1488       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1489         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1490           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1491       }
1492     }
1493   }
1494
1495   if (!Cmp) {
1496     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1497     AArch64CC = changeIntCCToAArch64CC(CC);
1498   }
1499   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1500   return Cmp;
1501 }
1502
1503 static std::pair<SDValue, SDValue>
1504 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1505   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1506          "Unsupported value type");
1507   SDValue Value, Overflow;
1508   SDLoc DL(Op);
1509   SDValue LHS = Op.getOperand(0);
1510   SDValue RHS = Op.getOperand(1);
1511   unsigned Opc = 0;
1512   switch (Op.getOpcode()) {
1513   default:
1514     llvm_unreachable("Unknown overflow instruction!");
1515   case ISD::SADDO:
1516     Opc = AArch64ISD::ADDS;
1517     CC = AArch64CC::VS;
1518     break;
1519   case ISD::UADDO:
1520     Opc = AArch64ISD::ADDS;
1521     CC = AArch64CC::HS;
1522     break;
1523   case ISD::SSUBO:
1524     Opc = AArch64ISD::SUBS;
1525     CC = AArch64CC::VS;
1526     break;
1527   case ISD::USUBO:
1528     Opc = AArch64ISD::SUBS;
1529     CC = AArch64CC::LO;
1530     break;
1531   // Multiply needs a little bit extra work.
1532   case ISD::SMULO:
1533   case ISD::UMULO: {
1534     CC = AArch64CC::NE;
1535     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1536     if (Op.getValueType() == MVT::i32) {
1537       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1538       // For a 32 bit multiply with overflow check we want the instruction
1539       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1540       // need to generate the following pattern:
1541       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1542       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1543       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1544       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1545       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1546                                 DAG.getConstant(0, DL, MVT::i64));
1547       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1548       // operation. We need to clear out the upper 32 bits, because we used a
1549       // widening multiply that wrote all 64 bits. In the end this should be a
1550       // noop.
1551       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1552       if (IsSigned) {
1553         // The signed overflow check requires more than just a simple check for
1554         // any bit set in the upper 32 bits of the result. These bits could be
1555         // just the sign bits of a negative number. To perform the overflow
1556         // check we have to arithmetic shift right the 32nd bit of the result by
1557         // 31 bits. Then we compare the result to the upper 32 bits.
1558         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1559                                         DAG.getConstant(32, DL, MVT::i64));
1560         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1561         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1562                                         DAG.getConstant(31, DL, MVT::i64));
1563         // It is important that LowerBits is last, otherwise the arithmetic
1564         // shift will not be folded into the compare (SUBS).
1565         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1566         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1567                        .getValue(1);
1568       } else {
1569         // The overflow check for unsigned multiply is easy. We only need to
1570         // check if any of the upper 32 bits are set. This can be done with a
1571         // CMP (shifted register). For that we need to generate the following
1572         // pattern:
1573         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1574         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1575                                         DAG.getConstant(32, DL, MVT::i64));
1576         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1577         Overflow =
1578             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1579                         DAG.getConstant(0, DL, MVT::i64),
1580                         UpperBits).getValue(1);
1581       }
1582       break;
1583     }
1584     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1585     // For the 64 bit multiply
1586     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1587     if (IsSigned) {
1588       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1589       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1590                                       DAG.getConstant(63, DL, MVT::i64));
1591       // It is important that LowerBits is last, otherwise the arithmetic
1592       // shift will not be folded into the compare (SUBS).
1593       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1594       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1595                      .getValue(1);
1596     } else {
1597       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1598       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1599       Overflow =
1600           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1601                       DAG.getConstant(0, DL, MVT::i64),
1602                       UpperBits).getValue(1);
1603     }
1604     break;
1605   }
1606   } // switch (...)
1607
1608   if (Opc) {
1609     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1610
1611     // Emit the AArch64 operation with overflow check.
1612     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1613     Overflow = Value.getValue(1);
1614   }
1615   return std::make_pair(Value, Overflow);
1616 }
1617
1618 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1619                                              RTLIB::Libcall Call) const {
1620   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1621   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1622                      SDLoc(Op)).first;
1623 }
1624
1625 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1626   SDValue Sel = Op.getOperand(0);
1627   SDValue Other = Op.getOperand(1);
1628
1629   // If neither operand is a SELECT_CC, give up.
1630   if (Sel.getOpcode() != ISD::SELECT_CC)
1631     std::swap(Sel, Other);
1632   if (Sel.getOpcode() != ISD::SELECT_CC)
1633     return Op;
1634
1635   // The folding we want to perform is:
1636   // (xor x, (select_cc a, b, cc, 0, -1) )
1637   //   -->
1638   // (csel x, (xor x, -1), cc ...)
1639   //
1640   // The latter will get matched to a CSINV instruction.
1641
1642   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1643   SDValue LHS = Sel.getOperand(0);
1644   SDValue RHS = Sel.getOperand(1);
1645   SDValue TVal = Sel.getOperand(2);
1646   SDValue FVal = Sel.getOperand(3);
1647   SDLoc dl(Sel);
1648
1649   // FIXME: This could be generalized to non-integer comparisons.
1650   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1651     return Op;
1652
1653   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1654   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1655
1656   // The values aren't constants, this isn't the pattern we're looking for.
1657   if (!CFVal || !CTVal)
1658     return Op;
1659
1660   // We can commute the SELECT_CC by inverting the condition.  This
1661   // might be needed to make this fit into a CSINV pattern.
1662   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1663     std::swap(TVal, FVal);
1664     std::swap(CTVal, CFVal);
1665     CC = ISD::getSetCCInverse(CC, true);
1666   }
1667
1668   // If the constants line up, perform the transform!
1669   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1670     SDValue CCVal;
1671     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1672
1673     FVal = Other;
1674     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1675                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1676
1677     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1678                        CCVal, Cmp);
1679   }
1680
1681   return Op;
1682 }
1683
1684 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1685   EVT VT = Op.getValueType();
1686
1687   // Let legalize expand this if it isn't a legal type yet.
1688   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1689     return SDValue();
1690
1691   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1692
1693   unsigned Opc;
1694   bool ExtraOp = false;
1695   switch (Op.getOpcode()) {
1696   default:
1697     llvm_unreachable("Invalid code");
1698   case ISD::ADDC:
1699     Opc = AArch64ISD::ADDS;
1700     break;
1701   case ISD::SUBC:
1702     Opc = AArch64ISD::SUBS;
1703     break;
1704   case ISD::ADDE:
1705     Opc = AArch64ISD::ADCS;
1706     ExtraOp = true;
1707     break;
1708   case ISD::SUBE:
1709     Opc = AArch64ISD::SBCS;
1710     ExtraOp = true;
1711     break;
1712   }
1713
1714   if (!ExtraOp)
1715     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1716   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1717                      Op.getOperand(2));
1718 }
1719
1720 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1721   // Let legalize expand this if it isn't a legal type yet.
1722   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1723     return SDValue();
1724
1725   SDLoc dl(Op);
1726   AArch64CC::CondCode CC;
1727   // The actual operation that sets the overflow or carry flag.
1728   SDValue Value, Overflow;
1729   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1730
1731   // We use 0 and 1 as false and true values.
1732   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1733   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1734
1735   // We use an inverted condition, because the conditional select is inverted
1736   // too. This will allow it to be selected to a single instruction:
1737   // CSINC Wd, WZR, WZR, invert(cond).
1738   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1739   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1740                          CCVal, Overflow);
1741
1742   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1743   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1744 }
1745
1746 // Prefetch operands are:
1747 // 1: Address to prefetch
1748 // 2: bool isWrite
1749 // 3: int locality (0 = no locality ... 3 = extreme locality)
1750 // 4: bool isDataCache
1751 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1752   SDLoc DL(Op);
1753   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1754   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1755   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1756
1757   bool IsStream = !Locality;
1758   // When the locality number is set
1759   if (Locality) {
1760     // The front-end should have filtered out the out-of-range values
1761     assert(Locality <= 3 && "Prefetch locality out-of-range");
1762     // The locality degree is the opposite of the cache speed.
1763     // Put the number the other way around.
1764     // The encoding starts at 0 for level 1
1765     Locality = 3 - Locality;
1766   }
1767
1768   // built the mask value encoding the expected behavior.
1769   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1770                    (!IsData << 3) |     // IsDataCache bit
1771                    (Locality << 1) |    // Cache level bits
1772                    (unsigned)IsStream;  // Stream bit
1773   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1774                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1775 }
1776
1777 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1778                                               SelectionDAG &DAG) const {
1779   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1780
1781   RTLIB::Libcall LC;
1782   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1783
1784   return LowerF128Call(Op, DAG, LC);
1785 }
1786
1787 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1788                                              SelectionDAG &DAG) const {
1789   if (Op.getOperand(0).getValueType() != MVT::f128) {
1790     // It's legal except when f128 is involved
1791     return Op;
1792   }
1793
1794   RTLIB::Libcall LC;
1795   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1796
1797   // FP_ROUND node has a second operand indicating whether it is known to be
1798   // precise. That doesn't take part in the LibCall so we can't directly use
1799   // LowerF128Call.
1800   SDValue SrcVal = Op.getOperand(0);
1801   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1802                      /*isSigned*/ false, SDLoc(Op)).first;
1803 }
1804
1805 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1806   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1807   // Any additional optimization in this function should be recorded
1808   // in the cost tables.
1809   EVT InVT = Op.getOperand(0).getValueType();
1810   EVT VT = Op.getValueType();
1811
1812   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1813     SDLoc dl(Op);
1814     SDValue Cv =
1815         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1816                     Op.getOperand(0));
1817     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1818   }
1819
1820   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1821     SDLoc dl(Op);
1822     MVT ExtVT =
1823         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1824                          VT.getVectorNumElements());
1825     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1826     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1827   }
1828
1829   // Type changing conversions are illegal.
1830   return Op;
1831 }
1832
1833 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1834                                               SelectionDAG &DAG) const {
1835   if (Op.getOperand(0).getValueType().isVector())
1836     return LowerVectorFP_TO_INT(Op, DAG);
1837
1838   // f16 conversions are promoted to f32.
1839   if (Op.getOperand(0).getValueType() == MVT::f16) {
1840     SDLoc dl(Op);
1841     return DAG.getNode(
1842         Op.getOpcode(), dl, Op.getValueType(),
1843         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1844   }
1845
1846   if (Op.getOperand(0).getValueType() != MVT::f128) {
1847     // It's legal except when f128 is involved
1848     return Op;
1849   }
1850
1851   RTLIB::Libcall LC;
1852   if (Op.getOpcode() == ISD::FP_TO_SINT)
1853     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1854   else
1855     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1856
1857   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1858   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1859                      SDLoc(Op)).first;
1860 }
1861
1862 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1863   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1864   // Any additional optimization in this function should be recorded
1865   // in the cost tables.
1866   EVT VT = Op.getValueType();
1867   SDLoc dl(Op);
1868   SDValue In = Op.getOperand(0);
1869   EVT InVT = In.getValueType();
1870
1871   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1872     MVT CastVT =
1873         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1874                          InVT.getVectorNumElements());
1875     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1876     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1877   }
1878
1879   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1880     unsigned CastOpc =
1881         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1882     EVT CastVT = VT.changeVectorElementTypeToInteger();
1883     In = DAG.getNode(CastOpc, dl, CastVT, In);
1884     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1885   }
1886
1887   return Op;
1888 }
1889
1890 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1891                                             SelectionDAG &DAG) const {
1892   if (Op.getValueType().isVector())
1893     return LowerVectorINT_TO_FP(Op, DAG);
1894
1895   // f16 conversions are promoted to f32.
1896   if (Op.getValueType() == MVT::f16) {
1897     SDLoc dl(Op);
1898     return DAG.getNode(
1899         ISD::FP_ROUND, dl, MVT::f16,
1900         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1901         DAG.getIntPtrConstant(0, dl));
1902   }
1903
1904   // i128 conversions are libcalls.
1905   if (Op.getOperand(0).getValueType() == MVT::i128)
1906     return SDValue();
1907
1908   // Other conversions are legal, unless it's to the completely software-based
1909   // fp128.
1910   if (Op.getValueType() != MVT::f128)
1911     return Op;
1912
1913   RTLIB::Libcall LC;
1914   if (Op.getOpcode() == ISD::SINT_TO_FP)
1915     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1916   else
1917     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1918
1919   return LowerF128Call(Op, DAG, LC);
1920 }
1921
1922 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1923                                             SelectionDAG &DAG) const {
1924   // For iOS, we want to call an alternative entry point: __sincos_stret,
1925   // which returns the values in two S / D registers.
1926   SDLoc dl(Op);
1927   SDValue Arg = Op.getOperand(0);
1928   EVT ArgVT = Arg.getValueType();
1929   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1930
1931   ArgListTy Args;
1932   ArgListEntry Entry;
1933
1934   Entry.Node = Arg;
1935   Entry.Ty = ArgTy;
1936   Entry.isSExt = false;
1937   Entry.isZExt = false;
1938   Args.push_back(Entry);
1939
1940   const char *LibcallName =
1941       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1942   SDValue Callee =
1943       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1944
1945   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1946   TargetLowering::CallLoweringInfo CLI(DAG);
1947   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1948     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1949
1950   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1951   return CallResult.first;
1952 }
1953
1954 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1955   if (Op.getValueType() != MVT::f16)
1956     return SDValue();
1957
1958   assert(Op.getOperand(0).getValueType() == MVT::i16);
1959   SDLoc DL(Op);
1960
1961   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1962   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1963   return SDValue(
1964       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1965                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1966       0);
1967 }
1968
1969 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1970   if (OrigVT.getSizeInBits() >= 64)
1971     return OrigVT;
1972
1973   assert(OrigVT.isSimple() && "Expecting a simple value type");
1974
1975   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1976   switch (OrigSimpleTy) {
1977   default: llvm_unreachable("Unexpected Vector Type");
1978   case MVT::v2i8:
1979   case MVT::v2i16:
1980      return MVT::v2i32;
1981   case MVT::v4i8:
1982     return  MVT::v4i16;
1983   }
1984 }
1985
1986 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1987                                                  const EVT &OrigTy,
1988                                                  const EVT &ExtTy,
1989                                                  unsigned ExtOpcode) {
1990   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1991   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1992   // 64-bits we need to insert a new extension so that it will be 64-bits.
1993   assert(ExtTy.is128BitVector() && "Unexpected extension size");
1994   if (OrigTy.getSizeInBits() >= 64)
1995     return N;
1996
1997   // Must extend size to at least 64 bits to be used as an operand for VMULL.
1998   EVT NewVT = getExtensionTo64Bits(OrigTy);
1999
2000   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2001 }
2002
2003 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2004                                    bool isSigned) {
2005   EVT VT = N->getValueType(0);
2006
2007   if (N->getOpcode() != ISD::BUILD_VECTOR)
2008     return false;
2009
2010   for (const SDValue &Elt : N->op_values()) {
2011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2012       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2013       unsigned HalfSize = EltSize / 2;
2014       if (isSigned) {
2015         if (!isIntN(HalfSize, C->getSExtValue()))
2016           return false;
2017       } else {
2018         if (!isUIntN(HalfSize, C->getZExtValue()))
2019           return false;
2020       }
2021       continue;
2022     }
2023     return false;
2024   }
2025
2026   return true;
2027 }
2028
2029 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2030   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2031     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2032                                              N->getOperand(0)->getValueType(0),
2033                                              N->getValueType(0),
2034                                              N->getOpcode());
2035
2036   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2037   EVT VT = N->getValueType(0);
2038   SDLoc dl(N);
2039   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2040   unsigned NumElts = VT.getVectorNumElements();
2041   MVT TruncVT = MVT::getIntegerVT(EltSize);
2042   SmallVector<SDValue, 8> Ops;
2043   for (unsigned i = 0; i != NumElts; ++i) {
2044     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2045     const APInt &CInt = C->getAPIntValue();
2046     // Element types smaller than 32 bits are not legal, so use i32 elements.
2047     // The values are implicitly truncated so sext vs. zext doesn't matter.
2048     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2049   }
2050   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2051                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2052 }
2053
2054 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2055   if (N->getOpcode() == ISD::SIGN_EXTEND)
2056     return true;
2057   if (isExtendedBUILD_VECTOR(N, DAG, true))
2058     return true;
2059   return false;
2060 }
2061
2062 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2063   if (N->getOpcode() == ISD::ZERO_EXTEND)
2064     return true;
2065   if (isExtendedBUILD_VECTOR(N, DAG, false))
2066     return true;
2067   return false;
2068 }
2069
2070 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2071   unsigned Opcode = N->getOpcode();
2072   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2073     SDNode *N0 = N->getOperand(0).getNode();
2074     SDNode *N1 = N->getOperand(1).getNode();
2075     return N0->hasOneUse() && N1->hasOneUse() &&
2076       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2077   }
2078   return false;
2079 }
2080
2081 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2082   unsigned Opcode = N->getOpcode();
2083   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2084     SDNode *N0 = N->getOperand(0).getNode();
2085     SDNode *N1 = N->getOperand(1).getNode();
2086     return N0->hasOneUse() && N1->hasOneUse() &&
2087       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2088   }
2089   return false;
2090 }
2091
2092 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2093   // Multiplications are only custom-lowered for 128-bit vectors so that
2094   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2095   EVT VT = Op.getValueType();
2096   assert(VT.is128BitVector() && VT.isInteger() &&
2097          "unexpected type for custom-lowering ISD::MUL");
2098   SDNode *N0 = Op.getOperand(0).getNode();
2099   SDNode *N1 = Op.getOperand(1).getNode();
2100   unsigned NewOpc = 0;
2101   bool isMLA = false;
2102   bool isN0SExt = isSignExtended(N0, DAG);
2103   bool isN1SExt = isSignExtended(N1, DAG);
2104   if (isN0SExt && isN1SExt)
2105     NewOpc = AArch64ISD::SMULL;
2106   else {
2107     bool isN0ZExt = isZeroExtended(N0, DAG);
2108     bool isN1ZExt = isZeroExtended(N1, DAG);
2109     if (isN0ZExt && isN1ZExt)
2110       NewOpc = AArch64ISD::UMULL;
2111     else if (isN1SExt || isN1ZExt) {
2112       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2113       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2114       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2115         NewOpc = AArch64ISD::SMULL;
2116         isMLA = true;
2117       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2118         NewOpc =  AArch64ISD::UMULL;
2119         isMLA = true;
2120       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2121         std::swap(N0, N1);
2122         NewOpc =  AArch64ISD::UMULL;
2123         isMLA = true;
2124       }
2125     }
2126
2127     if (!NewOpc) {
2128       if (VT == MVT::v2i64)
2129         // Fall through to expand this.  It is not legal.
2130         return SDValue();
2131       else
2132         // Other vector multiplications are legal.
2133         return Op;
2134     }
2135   }
2136
2137   // Legalize to a S/UMULL instruction
2138   SDLoc DL(Op);
2139   SDValue Op0;
2140   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2141   if (!isMLA) {
2142     Op0 = skipExtensionForVectorMULL(N0, DAG);
2143     assert(Op0.getValueType().is64BitVector() &&
2144            Op1.getValueType().is64BitVector() &&
2145            "unexpected types for extended operands to VMULL");
2146     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2147   }
2148   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2149   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2150   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2151   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2152   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2153   EVT Op1VT = Op1.getValueType();
2154   return DAG.getNode(N0->getOpcode(), DL, VT,
2155                      DAG.getNode(NewOpc, DL, VT,
2156                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2157                      DAG.getNode(NewOpc, DL, VT,
2158                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2159 }
2160
2161 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2162                                               SelectionDAG &DAG) const {
2163   switch (Op.getOpcode()) {
2164   default:
2165     llvm_unreachable("unimplemented operand");
2166     return SDValue();
2167   case ISD::BITCAST:
2168     return LowerBITCAST(Op, DAG);
2169   case ISD::GlobalAddress:
2170     return LowerGlobalAddress(Op, DAG);
2171   case ISD::GlobalTLSAddress:
2172     return LowerGlobalTLSAddress(Op, DAG);
2173   case ISD::SETCC:
2174     return LowerSETCC(Op, DAG);
2175   case ISD::BR_CC:
2176     return LowerBR_CC(Op, DAG);
2177   case ISD::SELECT:
2178     return LowerSELECT(Op, DAG);
2179   case ISD::SELECT_CC:
2180     return LowerSELECT_CC(Op, DAG);
2181   case ISD::JumpTable:
2182     return LowerJumpTable(Op, DAG);
2183   case ISD::ConstantPool:
2184     return LowerConstantPool(Op, DAG);
2185   case ISD::BlockAddress:
2186     return LowerBlockAddress(Op, DAG);
2187   case ISD::VASTART:
2188     return LowerVASTART(Op, DAG);
2189   case ISD::VACOPY:
2190     return LowerVACOPY(Op, DAG);
2191   case ISD::VAARG:
2192     return LowerVAARG(Op, DAG);
2193   case ISD::ADDC:
2194   case ISD::ADDE:
2195   case ISD::SUBC:
2196   case ISD::SUBE:
2197     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2198   case ISD::SADDO:
2199   case ISD::UADDO:
2200   case ISD::SSUBO:
2201   case ISD::USUBO:
2202   case ISD::SMULO:
2203   case ISD::UMULO:
2204     return LowerXALUO(Op, DAG);
2205   case ISD::FADD:
2206     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2207   case ISD::FSUB:
2208     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2209   case ISD::FMUL:
2210     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2211   case ISD::FDIV:
2212     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2213   case ISD::FP_ROUND:
2214     return LowerFP_ROUND(Op, DAG);
2215   case ISD::FP_EXTEND:
2216     return LowerFP_EXTEND(Op, DAG);
2217   case ISD::FRAMEADDR:
2218     return LowerFRAMEADDR(Op, DAG);
2219   case ISD::RETURNADDR:
2220     return LowerRETURNADDR(Op, DAG);
2221   case ISD::INSERT_VECTOR_ELT:
2222     return LowerINSERT_VECTOR_ELT(Op, DAG);
2223   case ISD::EXTRACT_VECTOR_ELT:
2224     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2225   case ISD::BUILD_VECTOR:
2226     return LowerBUILD_VECTOR(Op, DAG);
2227   case ISD::VECTOR_SHUFFLE:
2228     return LowerVECTOR_SHUFFLE(Op, DAG);
2229   case ISD::EXTRACT_SUBVECTOR:
2230     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2231   case ISD::SRA:
2232   case ISD::SRL:
2233   case ISD::SHL:
2234     return LowerVectorSRA_SRL_SHL(Op, DAG);
2235   case ISD::SHL_PARTS:
2236     return LowerShiftLeftParts(Op, DAG);
2237   case ISD::SRL_PARTS:
2238   case ISD::SRA_PARTS:
2239     return LowerShiftRightParts(Op, DAG);
2240   case ISD::CTPOP:
2241     return LowerCTPOP(Op, DAG);
2242   case ISD::FCOPYSIGN:
2243     return LowerFCOPYSIGN(Op, DAG);
2244   case ISD::AND:
2245     return LowerVectorAND(Op, DAG);
2246   case ISD::OR:
2247     return LowerVectorOR(Op, DAG);
2248   case ISD::XOR:
2249     return LowerXOR(Op, DAG);
2250   case ISD::PREFETCH:
2251     return LowerPREFETCH(Op, DAG);
2252   case ISD::SINT_TO_FP:
2253   case ISD::UINT_TO_FP:
2254     return LowerINT_TO_FP(Op, DAG);
2255   case ISD::FP_TO_SINT:
2256   case ISD::FP_TO_UINT:
2257     return LowerFP_TO_INT(Op, DAG);
2258   case ISD::FSINCOS:
2259     return LowerFSINCOS(Op, DAG);
2260   case ISD::MUL:
2261     return LowerMUL(Op, DAG);
2262   }
2263 }
2264
2265 /// getFunctionAlignment - Return the Log2 alignment of this function.
2266 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2267   return 2;
2268 }
2269
2270 //===----------------------------------------------------------------------===//
2271 //                      Calling Convention Implementation
2272 //===----------------------------------------------------------------------===//
2273
2274 #include "AArch64GenCallingConv.inc"
2275
2276 /// Selects the correct CCAssignFn for a given CallingConvention value.
2277 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2278                                                      bool IsVarArg) const {
2279   switch (CC) {
2280   default:
2281     llvm_unreachable("Unsupported calling convention.");
2282   case CallingConv::WebKit_JS:
2283     return CC_AArch64_WebKit_JS;
2284   case CallingConv::GHC:
2285     return CC_AArch64_GHC;
2286   case CallingConv::C:
2287   case CallingConv::Fast:
2288     if (!Subtarget->isTargetDarwin())
2289       return CC_AArch64_AAPCS;
2290     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2291   }
2292 }
2293
2294 SDValue AArch64TargetLowering::LowerFormalArguments(
2295     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2296     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2297     SmallVectorImpl<SDValue> &InVals) const {
2298   MachineFunction &MF = DAG.getMachineFunction();
2299   MachineFrameInfo *MFI = MF.getFrameInfo();
2300
2301   // Assign locations to all of the incoming arguments.
2302   SmallVector<CCValAssign, 16> ArgLocs;
2303   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2304                  *DAG.getContext());
2305
2306   // At this point, Ins[].VT may already be promoted to i32. To correctly
2307   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2308   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2309   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2310   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2311   // LocVT.
2312   unsigned NumArgs = Ins.size();
2313   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2314   unsigned CurArgIdx = 0;
2315   for (unsigned i = 0; i != NumArgs; ++i) {
2316     MVT ValVT = Ins[i].VT;
2317     if (Ins[i].isOrigArg()) {
2318       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2319       CurArgIdx = Ins[i].getOrigArgIndex();
2320
2321       // Get type of the original argument.
2322       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2323                                   /*AllowUnknown*/ true);
2324       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2325       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2326       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2327         ValVT = MVT::i8;
2328       else if (ActualMVT == MVT::i16)
2329         ValVT = MVT::i16;
2330     }
2331     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2332     bool Res =
2333         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2334     assert(!Res && "Call operand has unhandled type");
2335     (void)Res;
2336   }
2337   assert(ArgLocs.size() == Ins.size());
2338   SmallVector<SDValue, 16> ArgValues;
2339   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2340     CCValAssign &VA = ArgLocs[i];
2341
2342     if (Ins[i].Flags.isByVal()) {
2343       // Byval is used for HFAs in the PCS, but the system should work in a
2344       // non-compliant manner for larger structs.
2345       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2346       int Size = Ins[i].Flags.getByValSize();
2347       unsigned NumRegs = (Size + 7) / 8;
2348
2349       // FIXME: This works on big-endian for composite byvals, which are the common
2350       // case. It should also work for fundamental types too.
2351       unsigned FrameIdx =
2352         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2353       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2354       InVals.push_back(FrameIdxN);
2355
2356       continue;
2357     }
2358     
2359     if (VA.isRegLoc()) {
2360       // Arguments stored in registers.
2361       EVT RegVT = VA.getLocVT();
2362
2363       SDValue ArgValue;
2364       const TargetRegisterClass *RC;
2365
2366       if (RegVT == MVT::i32)
2367         RC = &AArch64::GPR32RegClass;
2368       else if (RegVT == MVT::i64)
2369         RC = &AArch64::GPR64RegClass;
2370       else if (RegVT == MVT::f16)
2371         RC = &AArch64::FPR16RegClass;
2372       else if (RegVT == MVT::f32)
2373         RC = &AArch64::FPR32RegClass;
2374       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2375         RC = &AArch64::FPR64RegClass;
2376       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2377         RC = &AArch64::FPR128RegClass;
2378       else
2379         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2380
2381       // Transform the arguments in physical registers into virtual ones.
2382       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2383       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2384
2385       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2386       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2387       // truncate to the right size.
2388       switch (VA.getLocInfo()) {
2389       default:
2390         llvm_unreachable("Unknown loc info!");
2391       case CCValAssign::Full:
2392         break;
2393       case CCValAssign::BCvt:
2394         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2395         break;
2396       case CCValAssign::AExt:
2397       case CCValAssign::SExt:
2398       case CCValAssign::ZExt:
2399         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2400         // nodes after our lowering.
2401         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2402         break;
2403       }
2404
2405       InVals.push_back(ArgValue);
2406
2407     } else { // VA.isRegLoc()
2408       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2409       unsigned ArgOffset = VA.getLocMemOffset();
2410       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2411
2412       uint32_t BEAlign = 0;
2413       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2414           !Ins[i].Flags.isInConsecutiveRegs())
2415         BEAlign = 8 - ArgSize;
2416
2417       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2418
2419       // Create load nodes to retrieve arguments from the stack.
2420       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2421       SDValue ArgValue;
2422
2423       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2424       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2425       MVT MemVT = VA.getValVT();
2426
2427       switch (VA.getLocInfo()) {
2428       default:
2429         break;
2430       case CCValAssign::BCvt:
2431         MemVT = VA.getLocVT();
2432         break;
2433       case CCValAssign::SExt:
2434         ExtType = ISD::SEXTLOAD;
2435         break;
2436       case CCValAssign::ZExt:
2437         ExtType = ISD::ZEXTLOAD;
2438         break;
2439       case CCValAssign::AExt:
2440         ExtType = ISD::EXTLOAD;
2441         break;
2442       }
2443
2444       ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
2445                                 MachinePointerInfo::getFixedStack(FI),
2446                                 MemVT, false, false, false, 0);
2447
2448       InVals.push_back(ArgValue);
2449     }
2450   }
2451
2452   // varargs
2453   if (isVarArg) {
2454     if (!Subtarget->isTargetDarwin()) {
2455       // The AAPCS variadic function ABI is identical to the non-variadic
2456       // one. As a result there may be more arguments in registers and we should
2457       // save them for future reference.
2458       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2459     }
2460
2461     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2462     // This will point to the next argument passed via stack.
2463     unsigned StackOffset = CCInfo.getNextStackOffset();
2464     // We currently pass all varargs at 8-byte alignment.
2465     StackOffset = ((StackOffset + 7) & ~7);
2466     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2467   }
2468
2469   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2470   unsigned StackArgSize = CCInfo.getNextStackOffset();
2471   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2472   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2473     // This is a non-standard ABI so by fiat I say we're allowed to make full
2474     // use of the stack area to be popped, which must be aligned to 16 bytes in
2475     // any case:
2476     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2477
2478     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2479     // a multiple of 16.
2480     FuncInfo->setArgumentStackToRestore(StackArgSize);
2481
2482     // This realignment carries over to the available bytes below. Our own
2483     // callers will guarantee the space is free by giving an aligned value to
2484     // CALLSEQ_START.
2485   }
2486   // Even if we're not expected to free up the space, it's useful to know how
2487   // much is there while considering tail calls (because we can reuse it).
2488   FuncInfo->setBytesInStackArgArea(StackArgSize);
2489
2490   return Chain;
2491 }
2492
2493 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2494                                                 SelectionDAG &DAG, SDLoc DL,
2495                                                 SDValue &Chain) const {
2496   MachineFunction &MF = DAG.getMachineFunction();
2497   MachineFrameInfo *MFI = MF.getFrameInfo();
2498   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2499   auto PtrVT = getPointerTy(DAG.getDataLayout());
2500
2501   SmallVector<SDValue, 8> MemOps;
2502
2503   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2504                                           AArch64::X3, AArch64::X4, AArch64::X5,
2505                                           AArch64::X6, AArch64::X7 };
2506   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2507   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2508
2509   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2510   int GPRIdx = 0;
2511   if (GPRSaveSize != 0) {
2512     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2513
2514     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2515
2516     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2517       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2518       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2519       SDValue Store =
2520           DAG.getStore(Val.getValue(1), DL, Val, FIN,
2521                        MachinePointerInfo::getStack(i * 8), false, false, 0);
2522       MemOps.push_back(Store);
2523       FIN =
2524           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2525     }
2526   }
2527   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2528   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2529
2530   if (Subtarget->hasFPARMv8()) {
2531     static const MCPhysReg FPRArgRegs[] = {
2532         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2533         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2534     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2535     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2536
2537     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2538     int FPRIdx = 0;
2539     if (FPRSaveSize != 0) {
2540       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2541
2542       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2543
2544       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2545         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2546         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2547
2548         SDValue Store =
2549             DAG.getStore(Val.getValue(1), DL, Val, FIN,
2550                          MachinePointerInfo::getStack(i * 16), false, false, 0);
2551         MemOps.push_back(Store);
2552         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2553                           DAG.getConstant(16, DL, PtrVT));
2554       }
2555     }
2556     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2557     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2558   }
2559
2560   if (!MemOps.empty()) {
2561     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2562   }
2563 }
2564
2565 /// LowerCallResult - Lower the result values of a call into the
2566 /// appropriate copies out of appropriate physical registers.
2567 SDValue AArch64TargetLowering::LowerCallResult(
2568     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2569     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2570     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2571     SDValue ThisVal) const {
2572   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2573                           ? RetCC_AArch64_WebKit_JS
2574                           : RetCC_AArch64_AAPCS;
2575   // Assign locations to each value returned by this call.
2576   SmallVector<CCValAssign, 16> RVLocs;
2577   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2578                  *DAG.getContext());
2579   CCInfo.AnalyzeCallResult(Ins, RetCC);
2580
2581   // Copy all of the result registers out of their specified physreg.
2582   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2583     CCValAssign VA = RVLocs[i];
2584
2585     // Pass 'this' value directly from the argument to return value, to avoid
2586     // reg unit interference
2587     if (i == 0 && isThisReturn) {
2588       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2589              "unexpected return calling convention register assignment");
2590       InVals.push_back(ThisVal);
2591       continue;
2592     }
2593
2594     SDValue Val =
2595         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2596     Chain = Val.getValue(1);
2597     InFlag = Val.getValue(2);
2598
2599     switch (VA.getLocInfo()) {
2600     default:
2601       llvm_unreachable("Unknown loc info!");
2602     case CCValAssign::Full:
2603       break;
2604     case CCValAssign::BCvt:
2605       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2606       break;
2607     }
2608
2609     InVals.push_back(Val);
2610   }
2611
2612   return Chain;
2613 }
2614
2615 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2616     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2617     bool isCalleeStructRet, bool isCallerStructRet,
2618     const SmallVectorImpl<ISD::OutputArg> &Outs,
2619     const SmallVectorImpl<SDValue> &OutVals,
2620     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2621   // For CallingConv::C this function knows whether the ABI needs
2622   // changing. That's not true for other conventions so they will have to opt in
2623   // manually.
2624   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2625     return false;
2626
2627   const MachineFunction &MF = DAG.getMachineFunction();
2628   const Function *CallerF = MF.getFunction();
2629   CallingConv::ID CallerCC = CallerF->getCallingConv();
2630   bool CCMatch = CallerCC == CalleeCC;
2631
2632   // Byval parameters hand the function a pointer directly into the stack area
2633   // we want to reuse during a tail call. Working around this *is* possible (see
2634   // X86) but less efficient and uglier in LowerCall.
2635   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2636                                     e = CallerF->arg_end();
2637        i != e; ++i)
2638     if (i->hasByValAttr())
2639       return false;
2640
2641   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2642     if (IsTailCallConvention(CalleeCC) && CCMatch)
2643       return true;
2644     return false;
2645   }
2646
2647   // Externally-defined functions with weak linkage should not be
2648   // tail-called on AArch64 when the OS does not support dynamic
2649   // pre-emption of symbols, as the AAELF spec requires normal calls
2650   // to undefined weak functions to be replaced with a NOP or jump to the
2651   // next instruction. The behaviour of branch instructions in this
2652   // situation (as used for tail calls) is implementation-defined, so we
2653   // cannot rely on the linker replacing the tail call with a return.
2654   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2655     const GlobalValue *GV = G->getGlobal();
2656     const Triple &TT = getTargetMachine().getTargetTriple();
2657     if (GV->hasExternalWeakLinkage() &&
2658         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2659       return false;
2660   }
2661
2662   // Now we search for cases where we can use a tail call without changing the
2663   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2664   // concept.
2665
2666   // I want anyone implementing a new calling convention to think long and hard
2667   // about this assert.
2668   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2669          "Unexpected variadic calling convention");
2670
2671   if (isVarArg && !Outs.empty()) {
2672     // At least two cases here: if caller is fastcc then we can't have any
2673     // memory arguments (we'd be expected to clean up the stack afterwards). If
2674     // caller is C then we could potentially use its argument area.
2675
2676     // FIXME: for now we take the most conservative of these in both cases:
2677     // disallow all variadic memory operands.
2678     SmallVector<CCValAssign, 16> ArgLocs;
2679     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2680                    *DAG.getContext());
2681
2682     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2683     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2684       if (!ArgLocs[i].isRegLoc())
2685         return false;
2686   }
2687
2688   // If the calling conventions do not match, then we'd better make sure the
2689   // results are returned in the same way as what the caller expects.
2690   if (!CCMatch) {
2691     SmallVector<CCValAssign, 16> RVLocs1;
2692     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2693                     *DAG.getContext());
2694     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2695
2696     SmallVector<CCValAssign, 16> RVLocs2;
2697     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2698                     *DAG.getContext());
2699     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2700
2701     if (RVLocs1.size() != RVLocs2.size())
2702       return false;
2703     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2704       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2705         return false;
2706       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2707         return false;
2708       if (RVLocs1[i].isRegLoc()) {
2709         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2710           return false;
2711       } else {
2712         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2713           return false;
2714       }
2715     }
2716   }
2717
2718   // Nothing more to check if the callee is taking no arguments
2719   if (Outs.empty())
2720     return true;
2721
2722   SmallVector<CCValAssign, 16> ArgLocs;
2723   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2724                  *DAG.getContext());
2725
2726   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2727
2728   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2729
2730   // If the stack arguments for this call would fit into our own save area then
2731   // the call can be made tail.
2732   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2733 }
2734
2735 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2736                                                    SelectionDAG &DAG,
2737                                                    MachineFrameInfo *MFI,
2738                                                    int ClobberedFI) const {
2739   SmallVector<SDValue, 8> ArgChains;
2740   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2741   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2742
2743   // Include the original chain at the beginning of the list. When this is
2744   // used by target LowerCall hooks, this helps legalize find the
2745   // CALLSEQ_BEGIN node.
2746   ArgChains.push_back(Chain);
2747
2748   // Add a chain value for each stack argument corresponding
2749   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2750                             UE = DAG.getEntryNode().getNode()->use_end();
2751        U != UE; ++U)
2752     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2753       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2754         if (FI->getIndex() < 0) {
2755           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2756           int64_t InLastByte = InFirstByte;
2757           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2758
2759           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2760               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2761             ArgChains.push_back(SDValue(L, 1));
2762         }
2763
2764   // Build a tokenfactor for all the chains.
2765   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2766 }
2767
2768 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2769                                                    bool TailCallOpt) const {
2770   return CallCC == CallingConv::Fast && TailCallOpt;
2771 }
2772
2773 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2774   return CallCC == CallingConv::Fast;
2775 }
2776
2777 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2778 /// and add input and output parameter nodes.
2779 SDValue
2780 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2781                                  SmallVectorImpl<SDValue> &InVals) const {
2782   SelectionDAG &DAG = CLI.DAG;
2783   SDLoc &DL = CLI.DL;
2784   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2785   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2786   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2787   SDValue Chain = CLI.Chain;
2788   SDValue Callee = CLI.Callee;
2789   bool &IsTailCall = CLI.IsTailCall;
2790   CallingConv::ID CallConv = CLI.CallConv;
2791   bool IsVarArg = CLI.IsVarArg;
2792
2793   MachineFunction &MF = DAG.getMachineFunction();
2794   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2795   bool IsThisReturn = false;
2796
2797   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2798   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2799   bool IsSibCall = false;
2800
2801   if (IsTailCall) {
2802     // Check if it's really possible to do a tail call.
2803     IsTailCall = isEligibleForTailCallOptimization(
2804         Callee, CallConv, IsVarArg, IsStructRet,
2805         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2806     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2807       report_fatal_error("failed to perform tail call elimination on a call "
2808                          "site marked musttail");
2809
2810     // A sibling call is one where we're under the usual C ABI and not planning
2811     // to change that but can still do a tail call:
2812     if (!TailCallOpt && IsTailCall)
2813       IsSibCall = true;
2814
2815     if (IsTailCall)
2816       ++NumTailCalls;
2817   }
2818
2819   // Analyze operands of the call, assigning locations to each operand.
2820   SmallVector<CCValAssign, 16> ArgLocs;
2821   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2822                  *DAG.getContext());
2823
2824   if (IsVarArg) {
2825     // Handle fixed and variable vector arguments differently.
2826     // Variable vector arguments always go into memory.
2827     unsigned NumArgs = Outs.size();
2828
2829     for (unsigned i = 0; i != NumArgs; ++i) {
2830       MVT ArgVT = Outs[i].VT;
2831       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2832       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2833                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2834       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2835       assert(!Res && "Call operand has unhandled type");
2836       (void)Res;
2837     }
2838   } else {
2839     // At this point, Outs[].VT may already be promoted to i32. To correctly
2840     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2841     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2842     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2843     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2844     // LocVT.
2845     unsigned NumArgs = Outs.size();
2846     for (unsigned i = 0; i != NumArgs; ++i) {
2847       MVT ValVT = Outs[i].VT;
2848       // Get type of the original argument.
2849       EVT ActualVT = getValueType(DAG.getDataLayout(),
2850                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2851                                   /*AllowUnknown*/ true);
2852       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2853       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2854       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2855       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2856         ValVT = MVT::i8;
2857       else if (ActualMVT == MVT::i16)
2858         ValVT = MVT::i16;
2859
2860       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2861       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2862       assert(!Res && "Call operand has unhandled type");
2863       (void)Res;
2864     }
2865   }
2866
2867   // Get a count of how many bytes are to be pushed on the stack.
2868   unsigned NumBytes = CCInfo.getNextStackOffset();
2869
2870   if (IsSibCall) {
2871     // Since we're not changing the ABI to make this a tail call, the memory
2872     // operands are already available in the caller's incoming argument space.
2873     NumBytes = 0;
2874   }
2875
2876   // FPDiff is the byte offset of the call's argument area from the callee's.
2877   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2878   // by this amount for a tail call. In a sibling call it must be 0 because the
2879   // caller will deallocate the entire stack and the callee still expects its
2880   // arguments to begin at SP+0. Completely unused for non-tail calls.
2881   int FPDiff = 0;
2882
2883   if (IsTailCall && !IsSibCall) {
2884     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2885
2886     // Since callee will pop argument stack as a tail call, we must keep the
2887     // popped size 16-byte aligned.
2888     NumBytes = RoundUpToAlignment(NumBytes, 16);
2889
2890     // FPDiff will be negative if this tail call requires more space than we
2891     // would automatically have in our incoming argument space. Positive if we
2892     // can actually shrink the stack.
2893     FPDiff = NumReusableBytes - NumBytes;
2894
2895     // The stack pointer must be 16-byte aligned at all times it's used for a
2896     // memory operation, which in practice means at *all* times and in
2897     // particular across call boundaries. Therefore our own arguments started at
2898     // a 16-byte aligned SP and the delta applied for the tail call should
2899     // satisfy the same constraint.
2900     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2901   }
2902
2903   // Adjust the stack pointer for the new arguments...
2904   // These operations are automatically eliminated by the prolog/epilog pass
2905   if (!IsSibCall)
2906     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2907                                                               true),
2908                                  DL);
2909
2910   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2911                                         getPointerTy(DAG.getDataLayout()));
2912
2913   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2914   SmallVector<SDValue, 8> MemOpChains;
2915   auto PtrVT = getPointerTy(DAG.getDataLayout());
2916
2917   // Walk the register/memloc assignments, inserting copies/loads.
2918   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2919        ++i, ++realArgIdx) {
2920     CCValAssign &VA = ArgLocs[i];
2921     SDValue Arg = OutVals[realArgIdx];
2922     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2923
2924     // Promote the value if needed.
2925     switch (VA.getLocInfo()) {
2926     default:
2927       llvm_unreachable("Unknown loc info!");
2928     case CCValAssign::Full:
2929       break;
2930     case CCValAssign::SExt:
2931       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2932       break;
2933     case CCValAssign::ZExt:
2934       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2935       break;
2936     case CCValAssign::AExt:
2937       if (Outs[realArgIdx].ArgVT == MVT::i1) {
2938         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2939         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2940         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2941       }
2942       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2943       break;
2944     case CCValAssign::BCvt:
2945       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2946       break;
2947     case CCValAssign::FPExt:
2948       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2949       break;
2950     }
2951
2952     if (VA.isRegLoc()) {
2953       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2954         assert(VA.getLocVT() == MVT::i64 &&
2955                "unexpected calling convention register assignment");
2956         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2957                "unexpected use of 'returned'");
2958         IsThisReturn = true;
2959       }
2960       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2961     } else {
2962       assert(VA.isMemLoc());
2963
2964       SDValue DstAddr;
2965       MachinePointerInfo DstInfo;
2966
2967       // FIXME: This works on big-endian for composite byvals, which are the
2968       // common case. It should also work for fundamental types too.
2969       uint32_t BEAlign = 0;
2970       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2971                                         : VA.getValVT().getSizeInBits();
2972       OpSize = (OpSize + 7) / 8;
2973       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2974           !Flags.isInConsecutiveRegs()) {
2975         if (OpSize < 8)
2976           BEAlign = 8 - OpSize;
2977       }
2978       unsigned LocMemOffset = VA.getLocMemOffset();
2979       int32_t Offset = LocMemOffset + BEAlign;
2980       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2981       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
2982
2983       if (IsTailCall) {
2984         Offset = Offset + FPDiff;
2985         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2986
2987         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2988         DstInfo = MachinePointerInfo::getFixedStack(FI);
2989
2990         // Make sure any stack arguments overlapping with where we're storing
2991         // are loaded before this eventual operation. Otherwise they'll be
2992         // clobbered.
2993         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2994       } else {
2995         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2996
2997         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
2998         DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2999       }
3000
3001       if (Outs[i].Flags.isByVal()) {
3002         SDValue SizeNode =
3003             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3004         SDValue Cpy = DAG.getMemcpy(
3005             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3006             /*isVol = */ false, /*AlwaysInline = */ false,
3007             /*isTailCall = */ false,
3008             DstInfo, MachinePointerInfo());
3009
3010         MemOpChains.push_back(Cpy);
3011       } else {
3012         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3013         // promoted to a legal register type i32, we should truncate Arg back to
3014         // i1/i8/i16.
3015         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3016             VA.getValVT() == MVT::i16)
3017           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3018
3019         SDValue Store =
3020             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3021         MemOpChains.push_back(Store);
3022       }
3023     }
3024   }
3025
3026   if (!MemOpChains.empty())
3027     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3028
3029   // Build a sequence of copy-to-reg nodes chained together with token chain
3030   // and flag operands which copy the outgoing args into the appropriate regs.
3031   SDValue InFlag;
3032   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3033     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
3034                              RegsToPass[i].second, InFlag);
3035     InFlag = Chain.getValue(1);
3036   }
3037
3038   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3039   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3040   // node so that legalize doesn't hack it.
3041   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3042       Subtarget->isTargetMachO()) {
3043     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3044       const GlobalValue *GV = G->getGlobal();
3045       bool InternalLinkage = GV->hasInternalLinkage();
3046       if (InternalLinkage)
3047         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3048       else {
3049         Callee =
3050             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3051         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3052       }
3053     } else if (ExternalSymbolSDNode *S =
3054                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3055       const char *Sym = S->getSymbol();
3056       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3057       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3058     }
3059   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3060     const GlobalValue *GV = G->getGlobal();
3061     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3062   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3063     const char *Sym = S->getSymbol();
3064     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3065   }
3066
3067   // We don't usually want to end the call-sequence here because we would tidy
3068   // the frame up *after* the call, however in the ABI-changing tail-call case
3069   // we've carefully laid out the parameters so that when sp is reset they'll be
3070   // in the correct location.
3071   if (IsTailCall && !IsSibCall) {
3072     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3073                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3074     InFlag = Chain.getValue(1);
3075   }
3076
3077   std::vector<SDValue> Ops;
3078   Ops.push_back(Chain);
3079   Ops.push_back(Callee);
3080
3081   if (IsTailCall) {
3082     // Each tail call may have to adjust the stack by a different amount, so
3083     // this information must travel along with the operation for eventual
3084     // consumption by emitEpilogue.
3085     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3086   }
3087
3088   // Add argument registers to the end of the list so that they are known live
3089   // into the call.
3090   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3091     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3092                                   RegsToPass[i].second.getValueType()));
3093
3094   // Add a register mask operand representing the call-preserved registers.
3095   const uint32_t *Mask;
3096   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3097   if (IsThisReturn) {
3098     // For 'this' returns, use the X0-preserving mask if applicable
3099     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3100     if (!Mask) {
3101       IsThisReturn = false;
3102       Mask = TRI->getCallPreservedMask(MF, CallConv);
3103     }
3104   } else
3105     Mask = TRI->getCallPreservedMask(MF, CallConv);
3106
3107   assert(Mask && "Missing call preserved mask for calling convention");
3108   Ops.push_back(DAG.getRegisterMask(Mask));
3109
3110   if (InFlag.getNode())
3111     Ops.push_back(InFlag);
3112
3113   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3114
3115   // If we're doing a tall call, use a TC_RETURN here rather than an
3116   // actual call instruction.
3117   if (IsTailCall) {
3118     MF.getFrameInfo()->setHasTailCall();
3119     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3120   }
3121
3122   // Returns a chain and a flag for retval copy to use.
3123   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3124   InFlag = Chain.getValue(1);
3125
3126   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3127                                 ? RoundUpToAlignment(NumBytes, 16)
3128                                 : 0;
3129
3130   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3131                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3132                              InFlag, DL);
3133   if (!Ins.empty())
3134     InFlag = Chain.getValue(1);
3135
3136   // Handle result values, copying them out of physregs into vregs that we
3137   // return.
3138   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3139                          InVals, IsThisReturn,
3140                          IsThisReturn ? OutVals[0] : SDValue());
3141 }
3142
3143 bool AArch64TargetLowering::CanLowerReturn(
3144     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3145     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3146   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3147                           ? RetCC_AArch64_WebKit_JS
3148                           : RetCC_AArch64_AAPCS;
3149   SmallVector<CCValAssign, 16> RVLocs;
3150   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3151   return CCInfo.CheckReturn(Outs, RetCC);
3152 }
3153
3154 SDValue
3155 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3156                                    bool isVarArg,
3157                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3158                                    const SmallVectorImpl<SDValue> &OutVals,
3159                                    SDLoc DL, SelectionDAG &DAG) const {
3160   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3161                           ? RetCC_AArch64_WebKit_JS
3162                           : RetCC_AArch64_AAPCS;
3163   SmallVector<CCValAssign, 16> RVLocs;
3164   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3165                  *DAG.getContext());
3166   CCInfo.AnalyzeReturn(Outs, RetCC);
3167
3168   // Copy the result values into the output registers.
3169   SDValue Flag;
3170   SmallVector<SDValue, 4> RetOps(1, Chain);
3171   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3172        ++i, ++realRVLocIdx) {
3173     CCValAssign &VA = RVLocs[i];
3174     assert(VA.isRegLoc() && "Can only return in registers!");
3175     SDValue Arg = OutVals[realRVLocIdx];
3176
3177     switch (VA.getLocInfo()) {
3178     default:
3179       llvm_unreachable("Unknown loc info!");
3180     case CCValAssign::Full:
3181       if (Outs[i].ArgVT == MVT::i1) {
3182         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3183         // value. This is strictly redundant on Darwin (which uses "zeroext
3184         // i1"), but will be optimised out before ISel.
3185         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3186         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3187       }
3188       break;
3189     case CCValAssign::BCvt:
3190       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3191       break;
3192     }
3193
3194     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3195     Flag = Chain.getValue(1);
3196     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3197   }
3198
3199   RetOps[0] = Chain; // Update chain.
3200
3201   // Add the flag if we have it.
3202   if (Flag.getNode())
3203     RetOps.push_back(Flag);
3204
3205   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3206 }
3207
3208 //===----------------------------------------------------------------------===//
3209 //  Other Lowering Code
3210 //===----------------------------------------------------------------------===//
3211
3212 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3213                                                   SelectionDAG &DAG) const {
3214   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3215   SDLoc DL(Op);
3216   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3217   const GlobalValue *GV = GN->getGlobal();
3218   unsigned char OpFlags =
3219       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3220
3221   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3222          "unexpected offset in global node");
3223
3224   // This also catched the large code model case for Darwin.
3225   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3226     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3227     // FIXME: Once remat is capable of dealing with instructions with register
3228     // operands, expand this into two nodes instead of using a wrapper node.
3229     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3230   }
3231
3232   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3233     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3234            "use of MO_CONSTPOOL only supported on small model");
3235     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3236     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3237     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3238     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3239     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3240     SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3241                                      MachinePointerInfo::getConstantPool(),
3242                                      /*isVolatile=*/ false,
3243                                      /*isNonTemporal=*/ true,
3244                                      /*isInvariant=*/ true, 8);
3245     if (GN->getOffset() != 0)
3246       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3247                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3248     return GlobalAddr;
3249   }
3250
3251   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3252     const unsigned char MO_NC = AArch64II::MO_NC;
3253     return DAG.getNode(
3254         AArch64ISD::WrapperLarge, DL, PtrVT,
3255         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3256         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3257         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3258         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3259   } else {
3260     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3261     // the only correct model on Darwin.
3262     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3263                                             OpFlags | AArch64II::MO_PAGE);
3264     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3265     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3266
3267     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3268     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3269   }
3270 }
3271
3272 /// \brief Convert a TLS address reference into the correct sequence of loads
3273 /// and calls to compute the variable's address (for Darwin, currently) and
3274 /// return an SDValue containing the final node.
3275
3276 /// Darwin only has one TLS scheme which must be capable of dealing with the
3277 /// fully general situation, in the worst case. This means:
3278 ///     + "extern __thread" declaration.
3279 ///     + Defined in a possibly unknown dynamic library.
3280 ///
3281 /// The general system is that each __thread variable has a [3 x i64] descriptor
3282 /// which contains information used by the runtime to calculate the address. The
3283 /// only part of this the compiler needs to know about is the first xword, which
3284 /// contains a function pointer that must be called with the address of the
3285 /// entire descriptor in "x0".
3286 ///
3287 /// Since this descriptor may be in a different unit, in general even the
3288 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3289 /// is:
3290 ///     adrp x0, _var@TLVPPAGE
3291 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3292 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3293 ///                                      ; the function pointer
3294 ///     blr x1                           ; Uses descriptor address in x0
3295 ///     ; Address of _var is now in x0.
3296 ///
3297 /// If the address of _var's descriptor *is* known to the linker, then it can
3298 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3299 /// a slight efficiency gain.
3300 SDValue
3301 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3302                                                    SelectionDAG &DAG) const {
3303   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3304
3305   SDLoc DL(Op);
3306   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3307   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3308
3309   SDValue TLVPAddr =
3310       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3311   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3312
3313   // The first entry in the descriptor is a function pointer that we must call
3314   // to obtain the address of the variable.
3315   SDValue Chain = DAG.getEntryNode();
3316   SDValue FuncTLVGet =
3317       DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3318                   false, true, true, 8);
3319   Chain = FuncTLVGet.getValue(1);
3320
3321   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3322   MFI->setAdjustsStack(true);
3323
3324   // TLS calls preserve all registers except those that absolutely must be
3325   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3326   // silly).
3327   const uint32_t *Mask =
3328       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3329
3330   // Finally, we can make the call. This is just a degenerate version of a
3331   // normal AArch64 call node: x0 takes the address of the descriptor, and
3332   // returns the address of the variable in this thread.
3333   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3334   Chain =
3335       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3336                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3337                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3338   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3339 }
3340
3341 /// When accessing thread-local variables under either the general-dynamic or
3342 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3343 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3344 /// is a function pointer to carry out the resolution.
3345 ///
3346 /// The sequence is:
3347 ///    adrp  x0, :tlsdesc:var
3348 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3349 ///    add   x0, x0, #:tlsdesc_lo12:var
3350 ///    .tlsdesccall var
3351 ///    blr   x1
3352 ///    (TPIDR_EL0 offset now in x0)
3353 ///
3354 ///  The above sequence must be produced unscheduled, to enable the linker to
3355 ///  optimize/relax this sequence.
3356 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3357 ///  above sequence, and expanded really late in the compilation flow, to ensure
3358 ///  the sequence is produced as per above.
3359 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3360                                                       SelectionDAG &DAG) const {
3361   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3362
3363   SDValue Chain = DAG.getEntryNode();
3364   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3365
3366   SmallVector<SDValue, 2> Ops;
3367   Ops.push_back(Chain);
3368   Ops.push_back(SymAddr);
3369
3370   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3371   SDValue Glue = Chain.getValue(1);
3372
3373   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3374 }
3375
3376 SDValue
3377 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3378                                                 SelectionDAG &DAG) const {
3379   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3380   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3381          "ELF TLS only supported in small memory model");
3382   // Different choices can be made for the maximum size of the TLS area for a
3383   // module. For the small address model, the default TLS size is 16MiB and the
3384   // maximum TLS size is 4GiB.
3385   // FIXME: add -mtls-size command line option and make it control the 16MiB
3386   // vs. 4GiB code sequence generation.
3387   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3388
3389   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3390   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3391     if (Model == TLSModel::LocalDynamic)
3392       Model = TLSModel::GeneralDynamic;
3393   }
3394
3395   SDValue TPOff;
3396   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3397   SDLoc DL(Op);
3398   const GlobalValue *GV = GA->getGlobal();
3399
3400   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3401
3402   if (Model == TLSModel::LocalExec) {
3403     SDValue HiVar = DAG.getTargetGlobalAddress(
3404         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3405     SDValue LoVar = DAG.getTargetGlobalAddress(
3406         GV, DL, PtrVT, 0,
3407         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3408
3409     SDValue TPWithOff_lo =
3410         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3411                                    HiVar,
3412                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3413                 0);
3414     SDValue TPWithOff =
3415         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3416                                    LoVar,
3417                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3418                 0);
3419     return TPWithOff;
3420   } else if (Model == TLSModel::InitialExec) {
3421     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3422     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3423   } else if (Model == TLSModel::LocalDynamic) {
3424     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3425     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3426     // the beginning of the module's TLS region, followed by a DTPREL offset
3427     // calculation.
3428
3429     // These accesses will need deduplicating if there's more than one.
3430     AArch64FunctionInfo *MFI =
3431         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3432     MFI->incNumLocalDynamicTLSAccesses();
3433
3434     // The call needs a relocation too for linker relaxation. It doesn't make
3435     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3436     // the address.
3437     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3438                                                   AArch64II::MO_TLS);
3439
3440     // Now we can calculate the offset from TPIDR_EL0 to this module's
3441     // thread-local area.
3442     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3443
3444     // Now use :dtprel_whatever: operations to calculate this variable's offset
3445     // in its thread-storage area.
3446     SDValue HiVar = DAG.getTargetGlobalAddress(
3447         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3448     SDValue LoVar = DAG.getTargetGlobalAddress(
3449         GV, DL, MVT::i64, 0,
3450         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3451
3452     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3453                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3454                     0);
3455     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3456                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3457                     0);
3458   } else if (Model == TLSModel::GeneralDynamic) {
3459     // The call needs a relocation too for linker relaxation. It doesn't make
3460     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3461     // the address.
3462     SDValue SymAddr =
3463         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3464
3465     // Finally we can make a call to calculate the offset from tpidr_el0.
3466     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3467   } else
3468     llvm_unreachable("Unsupported ELF TLS access model");
3469
3470   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3471 }
3472
3473 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3474                                                      SelectionDAG &DAG) const {
3475   if (Subtarget->isTargetDarwin())
3476     return LowerDarwinGlobalTLSAddress(Op, DAG);
3477   else if (Subtarget->isTargetELF())
3478     return LowerELFGlobalTLSAddress(Op, DAG);
3479
3480   llvm_unreachable("Unexpected platform trying to use TLS");
3481 }
3482 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3483   SDValue Chain = Op.getOperand(0);
3484   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3485   SDValue LHS = Op.getOperand(2);
3486   SDValue RHS = Op.getOperand(3);
3487   SDValue Dest = Op.getOperand(4);
3488   SDLoc dl(Op);
3489
3490   // Handle f128 first, since lowering it will result in comparing the return
3491   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3492   // is expecting to deal with.
3493   if (LHS.getValueType() == MVT::f128) {
3494     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3495
3496     // If softenSetCCOperands returned a scalar, we need to compare the result
3497     // against zero to select between true and false values.
3498     if (!RHS.getNode()) {
3499       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3500       CC = ISD::SETNE;
3501     }
3502   }
3503
3504   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3505   // instruction.
3506   unsigned Opc = LHS.getOpcode();
3507   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3508       cast<ConstantSDNode>(RHS)->isOne() &&
3509       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3510        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3511     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3512            "Unexpected condition code.");
3513     // Only lower legal XALUO ops.
3514     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3515       return SDValue();
3516
3517     // The actual operation with overflow check.
3518     AArch64CC::CondCode OFCC;
3519     SDValue Value, Overflow;
3520     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3521
3522     if (CC == ISD::SETNE)
3523       OFCC = getInvertedCondCode(OFCC);
3524     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3525
3526     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3527                        Overflow);
3528   }
3529
3530   if (LHS.getValueType().isInteger()) {
3531     assert((LHS.getValueType() == RHS.getValueType()) &&
3532            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3533
3534     // If the RHS of the comparison is zero, we can potentially fold this
3535     // to a specialized branch.
3536     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3537     if (RHSC && RHSC->getZExtValue() == 0) {
3538       if (CC == ISD::SETEQ) {
3539         // See if we can use a TBZ to fold in an AND as well.
3540         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3541         // out of bounds, a late MI-layer pass rewrites branches.
3542         // 403.gcc is an example that hits this case.
3543         if (LHS.getOpcode() == ISD::AND &&
3544             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3545             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3546           SDValue Test = LHS.getOperand(0);
3547           uint64_t Mask = LHS.getConstantOperandVal(1);
3548           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3549                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3550                              Dest);
3551         }
3552
3553         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3554       } else if (CC == ISD::SETNE) {
3555         // See if we can use a TBZ to fold in an AND as well.
3556         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3557         // out of bounds, a late MI-layer pass rewrites branches.
3558         // 403.gcc is an example that hits this case.
3559         if (LHS.getOpcode() == ISD::AND &&
3560             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3561             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3562           SDValue Test = LHS.getOperand(0);
3563           uint64_t Mask = LHS.getConstantOperandVal(1);
3564           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3565                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3566                              Dest);
3567         }
3568
3569         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3570       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3571         // Don't combine AND since emitComparison converts the AND to an ANDS
3572         // (a.k.a. TST) and the test in the test bit and branch instruction
3573         // becomes redundant.  This would also increase register pressure.
3574         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3575         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3576                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3577       }
3578     }
3579     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3580         LHS.getOpcode() != ISD::AND) {
3581       // Don't combine AND since emitComparison converts the AND to an ANDS
3582       // (a.k.a. TST) and the test in the test bit and branch instruction
3583       // becomes redundant.  This would also increase register pressure.
3584       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3585       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3586                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3587     }
3588
3589     SDValue CCVal;
3590     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3591     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3592                        Cmp);
3593   }
3594
3595   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3596
3597   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3598   // clean.  Some of them require two branches to implement.
3599   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3600   AArch64CC::CondCode CC1, CC2;
3601   changeFPCCToAArch64CC(CC, CC1, CC2);
3602   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3603   SDValue BR1 =
3604       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3605   if (CC2 != AArch64CC::AL) {
3606     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3607     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3608                        Cmp);
3609   }
3610
3611   return BR1;
3612 }
3613
3614 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3615                                               SelectionDAG &DAG) const {
3616   EVT VT = Op.getValueType();
3617   SDLoc DL(Op);
3618
3619   SDValue In1 = Op.getOperand(0);
3620   SDValue In2 = Op.getOperand(1);
3621   EVT SrcVT = In2.getValueType();
3622   if (SrcVT != VT) {
3623     if (SrcVT == MVT::f32 && VT == MVT::f64)
3624       In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3625     else if (SrcVT == MVT::f64 && VT == MVT::f32)
3626       In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2,
3627                         DAG.getIntPtrConstant(0, DL));
3628     else
3629       // FIXME: Src type is different, bail out for now. Can VT really be a
3630       // vector type?
3631       return SDValue();
3632   }
3633
3634   EVT VecVT;
3635   EVT EltVT;
3636   uint64_t EltMask;
3637   SDValue VecVal1, VecVal2;
3638   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3639     EltVT = MVT::i32;
3640     VecVT = MVT::v4i32;
3641     EltMask = 0x80000000ULL;
3642
3643     if (!VT.isVector()) {
3644       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3645                                           DAG.getUNDEF(VecVT), In1);
3646       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3647                                           DAG.getUNDEF(VecVT), In2);
3648     } else {
3649       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3650       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3651     }
3652   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3653     EltVT = MVT::i64;
3654     VecVT = MVT::v2i64;
3655
3656     // We want to materialize a mask with the high bit set, but the AdvSIMD
3657     // immediate moves cannot materialize that in a single instruction for
3658     // 64-bit elements. Instead, materialize zero and then negate it.
3659     EltMask = 0;
3660
3661     if (!VT.isVector()) {
3662       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3663                                           DAG.getUNDEF(VecVT), In1);
3664       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3665                                           DAG.getUNDEF(VecVT), In2);
3666     } else {
3667       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3668       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3669     }
3670   } else {
3671     llvm_unreachable("Invalid type for copysign!");
3672   }
3673
3674   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3675
3676   // If we couldn't materialize the mask above, then the mask vector will be
3677   // the zero vector, and we need to negate it here.
3678   if (VT == MVT::f64 || VT == MVT::v2f64) {
3679     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3680     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3681     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3682   }
3683
3684   SDValue Sel =
3685       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3686
3687   if (VT == MVT::f32)
3688     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3689   else if (VT == MVT::f64)
3690     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3691   else
3692     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3693 }
3694
3695 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3696   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3697           Attribute::NoImplicitFloat))
3698     return SDValue();
3699
3700   if (!Subtarget->hasNEON())
3701     return SDValue();
3702
3703   // While there is no integer popcount instruction, it can
3704   // be more efficiently lowered to the following sequence that uses
3705   // AdvSIMD registers/instructions as long as the copies to/from
3706   // the AdvSIMD registers are cheap.
3707   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3708   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3709   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3710   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3711   SDValue Val = Op.getOperand(0);
3712   SDLoc DL(Op);
3713   EVT VT = Op.getValueType();
3714
3715   if (VT == MVT::i32)
3716     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3717   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3718
3719   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3720   SDValue UaddLV = DAG.getNode(
3721       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3722       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3723
3724   if (VT == MVT::i64)
3725     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3726   return UaddLV;
3727 }
3728
3729 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3730
3731   if (Op.getValueType().isVector())
3732     return LowerVSETCC(Op, DAG);
3733
3734   SDValue LHS = Op.getOperand(0);
3735   SDValue RHS = Op.getOperand(1);
3736   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3737   SDLoc dl(Op);
3738
3739   // We chose ZeroOrOneBooleanContents, so use zero and one.
3740   EVT VT = Op.getValueType();
3741   SDValue TVal = DAG.getConstant(1, dl, VT);
3742   SDValue FVal = DAG.getConstant(0, dl, VT);
3743
3744   // Handle f128 first, since one possible outcome is a normal integer
3745   // comparison which gets picked up by the next if statement.
3746   if (LHS.getValueType() == MVT::f128) {
3747     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3748
3749     // If softenSetCCOperands returned a scalar, use it.
3750     if (!RHS.getNode()) {
3751       assert(LHS.getValueType() == Op.getValueType() &&
3752              "Unexpected setcc expansion!");
3753       return LHS;
3754     }
3755   }
3756
3757   if (LHS.getValueType().isInteger()) {
3758     SDValue CCVal;
3759     SDValue Cmp =
3760         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3761
3762     // Note that we inverted the condition above, so we reverse the order of
3763     // the true and false operands here.  This will allow the setcc to be
3764     // matched to a single CSINC instruction.
3765     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3766   }
3767
3768   // Now we know we're dealing with FP values.
3769   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3770
3771   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3772   // and do the comparison.
3773   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3774
3775   AArch64CC::CondCode CC1, CC2;
3776   changeFPCCToAArch64CC(CC, CC1, CC2);
3777   if (CC2 == AArch64CC::AL) {
3778     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3779     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3780
3781     // Note that we inverted the condition above, so we reverse the order of
3782     // the true and false operands here.  This will allow the setcc to be
3783     // matched to a single CSINC instruction.
3784     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3785   } else {
3786     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3787     // totally clean.  Some of them require two CSELs to implement.  As is in
3788     // this case, we emit the first CSEL and then emit a second using the output
3789     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3790
3791     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3792     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3793     SDValue CS1 =
3794         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3795
3796     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3797     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3798   }
3799 }
3800
3801 /// A SELECT_CC operation is really some kind of max or min if both values being
3802 /// compared are, in some sense, equal to the results in either case. However,
3803 /// it is permissible to compare f32 values and produce directly extended f64
3804 /// values.
3805 ///
3806 /// Extending the comparison operands would also be allowed, but is less likely
3807 /// to happen in practice since their use is right here. Note that truncate
3808 /// operations would *not* be semantically equivalent.
3809 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3810   if (Cmp == Result)
3811     return (Cmp.getValueType() == MVT::f32 ||
3812             Cmp.getValueType() == MVT::f64);
3813
3814   ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3815   ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3816   if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3817       Result.getValueType() == MVT::f64) {
3818     bool Lossy;
3819     APFloat CmpVal = CCmp->getValueAPF();
3820     CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3821     return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3822   }
3823
3824   return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3825 }
3826
3827 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3828                                               SDValue RHS, SDValue TVal,
3829                                               SDValue FVal, SDLoc dl,
3830                                               SelectionDAG &DAG) const {
3831   // Handle f128 first, because it will result in a comparison of some RTLIB
3832   // call result against zero.
3833   if (LHS.getValueType() == MVT::f128) {
3834     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3835
3836     // If softenSetCCOperands returned a scalar, we need to compare the result
3837     // against zero to select between true and false values.
3838     if (!RHS.getNode()) {
3839       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3840       CC = ISD::SETNE;
3841     }
3842   }
3843
3844   // Handle integers first.
3845   if (LHS.getValueType().isInteger()) {
3846     assert((LHS.getValueType() == RHS.getValueType()) &&
3847            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3848
3849     unsigned Opcode = AArch64ISD::CSEL;
3850
3851     // If both the TVal and the FVal are constants, see if we can swap them in
3852     // order to for a CSINV or CSINC out of them.
3853     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3854     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3855
3856     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3857       std::swap(TVal, FVal);
3858       std::swap(CTVal, CFVal);
3859       CC = ISD::getSetCCInverse(CC, true);
3860     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3861       std::swap(TVal, FVal);
3862       std::swap(CTVal, CFVal);
3863       CC = ISD::getSetCCInverse(CC, true);
3864     } else if (TVal.getOpcode() == ISD::XOR) {
3865       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3866       // with a CSINV rather than a CSEL.
3867       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3868
3869       if (CVal && CVal->isAllOnesValue()) {
3870         std::swap(TVal, FVal);
3871         std::swap(CTVal, CFVal);
3872         CC = ISD::getSetCCInverse(CC, true);
3873       }
3874     } else if (TVal.getOpcode() == ISD::SUB) {
3875       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3876       // that we can match with a CSNEG rather than a CSEL.
3877       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3878
3879       if (CVal && CVal->isNullValue()) {
3880         std::swap(TVal, FVal);
3881         std::swap(CTVal, CFVal);
3882         CC = ISD::getSetCCInverse(CC, true);
3883       }
3884     } else if (CTVal && CFVal) {
3885       const int64_t TrueVal = CTVal->getSExtValue();
3886       const int64_t FalseVal = CFVal->getSExtValue();
3887       bool Swap = false;
3888
3889       // If both TVal and FVal are constants, see if FVal is the
3890       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3891       // instead of a CSEL in that case.
3892       if (TrueVal == ~FalseVal) {
3893         Opcode = AArch64ISD::CSINV;
3894       } else if (TrueVal == -FalseVal) {
3895         Opcode = AArch64ISD::CSNEG;
3896       } else if (TVal.getValueType() == MVT::i32) {
3897         // If our operands are only 32-bit wide, make sure we use 32-bit
3898         // arithmetic for the check whether we can use CSINC. This ensures that
3899         // the addition in the check will wrap around properly in case there is
3900         // an overflow (which would not be the case if we do the check with
3901         // 64-bit arithmetic).
3902         const uint32_t TrueVal32 = CTVal->getZExtValue();
3903         const uint32_t FalseVal32 = CFVal->getZExtValue();
3904
3905         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3906           Opcode = AArch64ISD::CSINC;
3907
3908           if (TrueVal32 > FalseVal32) {
3909             Swap = true;
3910           }
3911         }
3912         // 64-bit check whether we can use CSINC.
3913       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3914         Opcode = AArch64ISD::CSINC;
3915
3916         if (TrueVal > FalseVal) {
3917           Swap = true;
3918         }
3919       }
3920
3921       // Swap TVal and FVal if necessary.
3922       if (Swap) {
3923         std::swap(TVal, FVal);
3924         std::swap(CTVal, CFVal);
3925         CC = ISD::getSetCCInverse(CC, true);
3926       }
3927
3928       if (Opcode != AArch64ISD::CSEL) {
3929         // Drop FVal since we can get its value by simply inverting/negating
3930         // TVal.
3931         FVal = TVal;
3932       }
3933     }
3934
3935     SDValue CCVal;
3936     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3937
3938     EVT VT = TVal.getValueType();
3939     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3940   }
3941
3942   // Now we know we're dealing with FP values.
3943   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3944   assert(LHS.getValueType() == RHS.getValueType());
3945   EVT VT = TVal.getValueType();
3946   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3947
3948   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3949   // clean.  Some of them require two CSELs to implement.
3950   AArch64CC::CondCode CC1, CC2;
3951   changeFPCCToAArch64CC(CC, CC1, CC2);
3952   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3953   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3954
3955   // If we need a second CSEL, emit it, using the output of the first as the
3956   // RHS.  We're effectively OR'ing the two CC's together.
3957   if (CC2 != AArch64CC::AL) {
3958     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3959     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3960   }
3961
3962   // Otherwise, return the output of the first CSEL.
3963   return CS1;
3964 }
3965
3966 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3967                                               SelectionDAG &DAG) const {
3968   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3969   SDValue LHS = Op.getOperand(0);
3970   SDValue RHS = Op.getOperand(1);
3971   SDValue TVal = Op.getOperand(2);
3972   SDValue FVal = Op.getOperand(3);
3973   SDLoc DL(Op);
3974   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3975 }
3976
3977 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3978                                            SelectionDAG &DAG) const {
3979   SDValue CCVal = Op->getOperand(0);
3980   SDValue TVal = Op->getOperand(1);
3981   SDValue FVal = Op->getOperand(2);
3982   SDLoc DL(Op);
3983
3984   unsigned Opc = CCVal.getOpcode();
3985   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3986   // instruction.
3987   if (CCVal.getResNo() == 1 &&
3988       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3989        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3990     // Only lower legal XALUO ops.
3991     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3992       return SDValue();
3993
3994     AArch64CC::CondCode OFCC;
3995     SDValue Value, Overflow;
3996     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
3997     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
3998
3999     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4000                        CCVal, Overflow);
4001   }
4002
4003   // Lower it the same way as we would lower a SELECT_CC node.
4004   ISD::CondCode CC;
4005   SDValue LHS, RHS;
4006   if (CCVal.getOpcode() == ISD::SETCC) {
4007     LHS = CCVal.getOperand(0);
4008     RHS = CCVal.getOperand(1);
4009     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4010   } else {
4011     LHS = CCVal;
4012     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4013     CC = ISD::SETNE;
4014   }
4015   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4016 }
4017
4018 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4019                                               SelectionDAG &DAG) const {
4020   // Jump table entries as PC relative offsets. No additional tweaking
4021   // is necessary here. Just get the address of the jump table.
4022   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4023   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4024   SDLoc DL(Op);
4025
4026   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4027       !Subtarget->isTargetMachO()) {
4028     const unsigned char MO_NC = AArch64II::MO_NC;
4029     return DAG.getNode(
4030         AArch64ISD::WrapperLarge, DL, PtrVT,
4031         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4032         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4033         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4034         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4035                                AArch64II::MO_G0 | MO_NC));
4036   }
4037
4038   SDValue Hi =
4039       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4040   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4041                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4042   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4043   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4044 }
4045
4046 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4047                                                  SelectionDAG &DAG) const {
4048   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4049   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4050   SDLoc DL(Op);
4051
4052   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4053     // Use the GOT for the large code model on iOS.
4054     if (Subtarget->isTargetMachO()) {
4055       SDValue GotAddr = DAG.getTargetConstantPool(
4056           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4057           AArch64II::MO_GOT);
4058       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4059     }
4060
4061     const unsigned char MO_NC = AArch64II::MO_NC;
4062     return DAG.getNode(
4063         AArch64ISD::WrapperLarge, DL, PtrVT,
4064         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4065                                   CP->getOffset(), AArch64II::MO_G3),
4066         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4067                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4068         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4069                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4070         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4071                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4072   } else {
4073     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4074     // ELF, the only valid one on Darwin.
4075     SDValue Hi =
4076         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4077                                   CP->getOffset(), AArch64II::MO_PAGE);
4078     SDValue Lo = DAG.getTargetConstantPool(
4079         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4080         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4081
4082     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4083     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4084   }
4085 }
4086
4087 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4088                                                SelectionDAG &DAG) const {
4089   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4090   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4091   SDLoc DL(Op);
4092   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4093       !Subtarget->isTargetMachO()) {
4094     const unsigned char MO_NC = AArch64II::MO_NC;
4095     return DAG.getNode(
4096         AArch64ISD::WrapperLarge, DL, PtrVT,
4097         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4098         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4099         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4100         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4101   } else {
4102     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4103     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4104                                                              AArch64II::MO_NC);
4105     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4106     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4107   }
4108 }
4109
4110 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4111                                                  SelectionDAG &DAG) const {
4112   AArch64FunctionInfo *FuncInfo =
4113       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4114
4115   SDLoc DL(Op);
4116   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4117                                  getPointerTy(DAG.getDataLayout()));
4118   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4119   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4120                       MachinePointerInfo(SV), false, false, 0);
4121 }
4122
4123 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4124                                                 SelectionDAG &DAG) const {
4125   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4126   // Standard, section B.3.
4127   MachineFunction &MF = DAG.getMachineFunction();
4128   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4129   auto PtrVT = getPointerTy(DAG.getDataLayout());
4130   SDLoc DL(Op);
4131
4132   SDValue Chain = Op.getOperand(0);
4133   SDValue VAList = Op.getOperand(1);
4134   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4135   SmallVector<SDValue, 4> MemOps;
4136
4137   // void *__stack at offset 0
4138   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4139   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4140                                 MachinePointerInfo(SV), false, false, 8));
4141
4142   // void *__gr_top at offset 8
4143   int GPRSize = FuncInfo->getVarArgsGPRSize();
4144   if (GPRSize > 0) {
4145     SDValue GRTop, GRTopAddr;
4146
4147     GRTopAddr =
4148         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4149
4150     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4151     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4152                         DAG.getConstant(GPRSize, DL, PtrVT));
4153
4154     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4155                                   MachinePointerInfo(SV, 8), false, false, 8));
4156   }
4157
4158   // void *__vr_top at offset 16
4159   int FPRSize = FuncInfo->getVarArgsFPRSize();
4160   if (FPRSize > 0) {
4161     SDValue VRTop, VRTopAddr;
4162     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4163                             DAG.getConstant(16, DL, PtrVT));
4164
4165     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4166     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4167                         DAG.getConstant(FPRSize, DL, PtrVT));
4168
4169     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4170                                   MachinePointerInfo(SV, 16), false, false, 8));
4171   }
4172
4173   // int __gr_offs at offset 24
4174   SDValue GROffsAddr =
4175       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4176   MemOps.push_back(DAG.getStore(Chain, DL,
4177                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4178                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4179                                 false, 4));
4180
4181   // int __vr_offs at offset 28
4182   SDValue VROffsAddr =
4183       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4184   MemOps.push_back(DAG.getStore(Chain, DL,
4185                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4186                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4187                                 false, 4));
4188
4189   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4190 }
4191
4192 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4193                                             SelectionDAG &DAG) const {
4194   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4195                                      : LowerAAPCS_VASTART(Op, DAG);
4196 }
4197
4198 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4199                                            SelectionDAG &DAG) const {
4200   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4201   // pointer.
4202   SDLoc DL(Op);
4203   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4204   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4205   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4206
4207   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4208                        Op.getOperand(2),
4209                        DAG.getConstant(VaListSize, DL, MVT::i32),
4210                        8, false, false, false, MachinePointerInfo(DestSV),
4211                        MachinePointerInfo(SrcSV));
4212 }
4213
4214 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4215   assert(Subtarget->isTargetDarwin() &&
4216          "automatic va_arg instruction only works on Darwin");
4217
4218   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4219   EVT VT = Op.getValueType();
4220   SDLoc DL(Op);
4221   SDValue Chain = Op.getOperand(0);
4222   SDValue Addr = Op.getOperand(1);
4223   unsigned Align = Op.getConstantOperandVal(3);
4224   auto PtrVT = getPointerTy(DAG.getDataLayout());
4225
4226   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4227                                false, false, false, 0);
4228   Chain = VAList.getValue(1);
4229
4230   if (Align > 8) {
4231     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4232     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4233                          DAG.getConstant(Align - 1, DL, PtrVT));
4234     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4235                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4236   }
4237
4238   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4239   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4240
4241   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4242   // up to 64 bits.  At the very least, we have to increase the striding of the
4243   // vaargs list to match this, and for FP values we need to introduce
4244   // FP_ROUND nodes as well.
4245   if (VT.isInteger() && !VT.isVector())
4246     ArgSize = 8;
4247   bool NeedFPTrunc = false;
4248   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4249     ArgSize = 8;
4250     NeedFPTrunc = true;
4251   }
4252
4253   // Increment the pointer, VAList, to the next vaarg
4254   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4255                                DAG.getConstant(ArgSize, DL, PtrVT));
4256   // Store the incremented VAList to the legalized pointer
4257   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4258                                  false, false, 0);
4259
4260   // Load the actual argument out of the pointer VAList
4261   if (NeedFPTrunc) {
4262     // Load the value as an f64.
4263     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4264                                  MachinePointerInfo(), false, false, false, 0);
4265     // Round the value down to an f32.
4266     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4267                                    DAG.getIntPtrConstant(1, DL));
4268     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4269     // Merge the rounded value with the chain output of the load.
4270     return DAG.getMergeValues(Ops, DL);
4271   }
4272
4273   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4274                      false, false, 0);
4275 }
4276
4277 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4278                                               SelectionDAG &DAG) const {
4279   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4280   MFI->setFrameAddressIsTaken(true);
4281
4282   EVT VT = Op.getValueType();
4283   SDLoc DL(Op);
4284   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4285   SDValue FrameAddr =
4286       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4287   while (Depth--)
4288     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4289                             MachinePointerInfo(), false, false, false, 0);
4290   return FrameAddr;
4291 }
4292
4293 // FIXME? Maybe this could be a TableGen attribute on some registers and
4294 // this table could be generated automatically from RegInfo.
4295 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4296                                                   SelectionDAG &DAG) const {
4297   unsigned Reg = StringSwitch<unsigned>(RegName)
4298                        .Case("sp", AArch64::SP)
4299                        .Default(0);
4300   if (Reg)
4301     return Reg;
4302   report_fatal_error(Twine("Invalid register name \""
4303                               + StringRef(RegName)  + "\"."));
4304 }
4305
4306 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4307                                                SelectionDAG &DAG) const {
4308   MachineFunction &MF = DAG.getMachineFunction();
4309   MachineFrameInfo *MFI = MF.getFrameInfo();
4310   MFI->setReturnAddressIsTaken(true);
4311
4312   EVT VT = Op.getValueType();
4313   SDLoc DL(Op);
4314   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4315   if (Depth) {
4316     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4317     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4318     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4319                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4320                        MachinePointerInfo(), false, false, false, 0);
4321   }
4322
4323   // Return LR, which contains the return address. Mark it an implicit live-in.
4324   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4325   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4326 }
4327
4328 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4329 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4330 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4331                                                     SelectionDAG &DAG) const {
4332   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4333   EVT VT = Op.getValueType();
4334   unsigned VTBits = VT.getSizeInBits();
4335   SDLoc dl(Op);
4336   SDValue ShOpLo = Op.getOperand(0);
4337   SDValue ShOpHi = Op.getOperand(1);
4338   SDValue ShAmt = Op.getOperand(2);
4339   SDValue ARMcc;
4340   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4341
4342   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4343
4344   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4345                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4346   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4347   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4348                                    DAG.getConstant(VTBits, dl, MVT::i64));
4349   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4350
4351   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4352                                ISD::SETGE, dl, DAG);
4353   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4354
4355   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4356   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4357   SDValue Lo =
4358       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4359
4360   // AArch64 shifts larger than the register width are wrapped rather than
4361   // clamped, so we can't just emit "hi >> x".
4362   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4363   SDValue TrueValHi = Opc == ISD::SRA
4364                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4365                                         DAG.getConstant(VTBits - 1, dl,
4366                                                         MVT::i64))
4367                           : DAG.getConstant(0, dl, VT);
4368   SDValue Hi =
4369       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4370
4371   SDValue Ops[2] = { Lo, Hi };
4372   return DAG.getMergeValues(Ops, dl);
4373 }
4374
4375 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4376 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4377 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4378                                                  SelectionDAG &DAG) const {
4379   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4380   EVT VT = Op.getValueType();
4381   unsigned VTBits = VT.getSizeInBits();
4382   SDLoc dl(Op);
4383   SDValue ShOpLo = Op.getOperand(0);
4384   SDValue ShOpHi = Op.getOperand(1);
4385   SDValue ShAmt = Op.getOperand(2);
4386   SDValue ARMcc;
4387
4388   assert(Op.getOpcode() == ISD::SHL_PARTS);
4389   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4390                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4391   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4392   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4393                                    DAG.getConstant(VTBits, dl, MVT::i64));
4394   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4395   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4396
4397   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4398
4399   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4400                                ISD::SETGE, dl, DAG);
4401   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4402   SDValue Hi =
4403       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4404
4405   // AArch64 shifts of larger than register sizes are wrapped rather than
4406   // clamped, so we can't just emit "lo << a" if a is too big.
4407   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4408   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4409   SDValue Lo =
4410       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4411
4412   SDValue Ops[2] = { Lo, Hi };
4413   return DAG.getMergeValues(Ops, dl);
4414 }
4415
4416 bool AArch64TargetLowering::isOffsetFoldingLegal(
4417     const GlobalAddressSDNode *GA) const {
4418   // The AArch64 target doesn't support folding offsets into global addresses.
4419   return false;
4420 }
4421
4422 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4423   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4424   // FIXME: We should be able to handle f128 as well with a clever lowering.
4425   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4426     return true;
4427
4428   if (VT == MVT::f64)
4429     return AArch64_AM::getFP64Imm(Imm) != -1;
4430   else if (VT == MVT::f32)
4431     return AArch64_AM::getFP32Imm(Imm) != -1;
4432   return false;
4433 }
4434
4435 //===----------------------------------------------------------------------===//
4436 //                          AArch64 Optimization Hooks
4437 //===----------------------------------------------------------------------===//
4438
4439 //===----------------------------------------------------------------------===//
4440 //                          AArch64 Inline Assembly Support
4441 //===----------------------------------------------------------------------===//
4442
4443 // Table of Constraints
4444 // TODO: This is the current set of constraints supported by ARM for the
4445 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4446 //
4447 // r - A general register
4448 // w - An FP/SIMD register of some size in the range v0-v31
4449 // x - An FP/SIMD register of some size in the range v0-v15
4450 // I - Constant that can be used with an ADD instruction
4451 // J - Constant that can be used with a SUB instruction
4452 // K - Constant that can be used with a 32-bit logical instruction
4453 // L - Constant that can be used with a 64-bit logical instruction
4454 // M - Constant that can be used as a 32-bit MOV immediate
4455 // N - Constant that can be used as a 64-bit MOV immediate
4456 // Q - A memory reference with base register and no offset
4457 // S - A symbolic address
4458 // Y - Floating point constant zero
4459 // Z - Integer constant zero
4460 //
4461 //   Note that general register operands will be output using their 64-bit x
4462 // register name, whatever the size of the variable, unless the asm operand
4463 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4464 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4465 // %q modifier.
4466
4467 /// getConstraintType - Given a constraint letter, return the type of
4468 /// constraint it is for this target.
4469 AArch64TargetLowering::ConstraintType
4470 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4471   if (Constraint.size() == 1) {
4472     switch (Constraint[0]) {
4473     default:
4474       break;
4475     case 'z':
4476       return C_Other;
4477     case 'x':
4478     case 'w':
4479       return C_RegisterClass;
4480     // An address with a single base register. Due to the way we
4481     // currently handle addresses it is the same as 'r'.
4482     case 'Q':
4483       return C_Memory;
4484     }
4485   }
4486   return TargetLowering::getConstraintType(Constraint);
4487 }
4488
4489 /// Examine constraint type and operand type and determine a weight value.
4490 /// This object must already have been set up with the operand type
4491 /// and the current alternative constraint selected.
4492 TargetLowering::ConstraintWeight
4493 AArch64TargetLowering::getSingleConstraintMatchWeight(
4494     AsmOperandInfo &info, const char *constraint) const {
4495   ConstraintWeight weight = CW_Invalid;
4496   Value *CallOperandVal = info.CallOperandVal;
4497   // If we don't have a value, we can't do a match,
4498   // but allow it at the lowest weight.
4499   if (!CallOperandVal)
4500     return CW_Default;
4501   Type *type = CallOperandVal->getType();
4502   // Look at the constraint type.
4503   switch (*constraint) {
4504   default:
4505     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4506     break;
4507   case 'x':
4508   case 'w':
4509     if (type->isFloatingPointTy() || type->isVectorTy())
4510       weight = CW_Register;
4511     break;
4512   case 'z':
4513     weight = CW_Constant;
4514     break;
4515   }
4516   return weight;
4517 }
4518
4519 std::pair<unsigned, const TargetRegisterClass *>
4520 AArch64TargetLowering::getRegForInlineAsmConstraint(
4521     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4522   if (Constraint.size() == 1) {
4523     switch (Constraint[0]) {
4524     case 'r':
4525       if (VT.getSizeInBits() == 64)
4526         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4527       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4528     case 'w':
4529       if (VT == MVT::f32)
4530         return std::make_pair(0U, &AArch64::FPR32RegClass);
4531       if (VT.getSizeInBits() == 64)
4532         return std::make_pair(0U, &AArch64::FPR64RegClass);
4533       if (VT.getSizeInBits() == 128)
4534         return std::make_pair(0U, &AArch64::FPR128RegClass);
4535       break;
4536     // The instructions that this constraint is designed for can
4537     // only take 128-bit registers so just use that regclass.
4538     case 'x':
4539       if (VT.getSizeInBits() == 128)
4540         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4541       break;
4542     }
4543   }
4544   if (StringRef("{cc}").equals_lower(Constraint))
4545     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4546
4547   // Use the default implementation in TargetLowering to convert the register
4548   // constraint into a member of a register class.
4549   std::pair<unsigned, const TargetRegisterClass *> Res;
4550   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4551
4552   // Not found as a standard register?
4553   if (!Res.second) {
4554     unsigned Size = Constraint.size();
4555     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4556         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4557       int RegNo;
4558       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4559       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4560         // v0 - v31 are aliases of q0 - q31.
4561         // By default we'll emit v0-v31 for this unless there's a modifier where
4562         // we'll emit the correct register as well.
4563         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4564         Res.second = &AArch64::FPR128RegClass;
4565       }
4566     }
4567   }
4568
4569   return Res;
4570 }
4571
4572 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4573 /// vector.  If it is invalid, don't add anything to Ops.
4574 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4575     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4576     SelectionDAG &DAG) const {
4577   SDValue Result;
4578
4579   // Currently only support length 1 constraints.
4580   if (Constraint.length() != 1)
4581     return;
4582
4583   char ConstraintLetter = Constraint[0];
4584   switch (ConstraintLetter) {
4585   default:
4586     break;
4587
4588   // This set of constraints deal with valid constants for various instructions.
4589   // Validate and return a target constant for them if we can.
4590   case 'z': {
4591     // 'z' maps to xzr or wzr so it needs an input of 0.
4592     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4593     if (!C || C->getZExtValue() != 0)
4594       return;
4595
4596     if (Op.getValueType() == MVT::i64)
4597       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4598     else
4599       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4600     break;
4601   }
4602
4603   case 'I':
4604   case 'J':
4605   case 'K':
4606   case 'L':
4607   case 'M':
4608   case 'N':
4609     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4610     if (!C)
4611       return;
4612
4613     // Grab the value and do some validation.
4614     uint64_t CVal = C->getZExtValue();
4615     switch (ConstraintLetter) {
4616     // The I constraint applies only to simple ADD or SUB immediate operands:
4617     // i.e. 0 to 4095 with optional shift by 12
4618     // The J constraint applies only to ADD or SUB immediates that would be
4619     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4620     // instruction [or vice versa], in other words -1 to -4095 with optional
4621     // left shift by 12.
4622     case 'I':
4623       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4624         break;
4625       return;
4626     case 'J': {
4627       uint64_t NVal = -C->getSExtValue();
4628       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4629         CVal = C->getSExtValue();
4630         break;
4631       }
4632       return;
4633     }
4634     // The K and L constraints apply *only* to logical immediates, including
4635     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4636     // been removed and MOV should be used). So these constraints have to
4637     // distinguish between bit patterns that are valid 32-bit or 64-bit
4638     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4639     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4640     // versa.
4641     case 'K':
4642       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4643         break;
4644       return;
4645     case 'L':
4646       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4647         break;
4648       return;
4649     // The M and N constraints are a superset of K and L respectively, for use
4650     // with the MOV (immediate) alias. As well as the logical immediates they
4651     // also match 32 or 64-bit immediates that can be loaded either using a
4652     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4653     // (M) or 64-bit 0x1234000000000000 (N) etc.
4654     // As a note some of this code is liberally stolen from the asm parser.
4655     case 'M': {
4656       if (!isUInt<32>(CVal))
4657         return;
4658       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4659         break;
4660       if ((CVal & 0xFFFF) == CVal)
4661         break;
4662       if ((CVal & 0xFFFF0000ULL) == CVal)
4663         break;
4664       uint64_t NCVal = ~(uint32_t)CVal;
4665       if ((NCVal & 0xFFFFULL) == NCVal)
4666         break;
4667       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4668         break;
4669       return;
4670     }
4671     case 'N': {
4672       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4673         break;
4674       if ((CVal & 0xFFFFULL) == CVal)
4675         break;
4676       if ((CVal & 0xFFFF0000ULL) == CVal)
4677         break;
4678       if ((CVal & 0xFFFF00000000ULL) == CVal)
4679         break;
4680       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4681         break;
4682       uint64_t NCVal = ~CVal;
4683       if ((NCVal & 0xFFFFULL) == NCVal)
4684         break;
4685       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4686         break;
4687       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4688         break;
4689       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4690         break;
4691       return;
4692     }
4693     default:
4694       return;
4695     }
4696
4697     // All assembler immediates are 64-bit integers.
4698     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4699     break;
4700   }
4701
4702   if (Result.getNode()) {
4703     Ops.push_back(Result);
4704     return;
4705   }
4706
4707   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4708 }
4709
4710 //===----------------------------------------------------------------------===//
4711 //                     AArch64 Advanced SIMD Support
4712 //===----------------------------------------------------------------------===//
4713
4714 /// WidenVector - Given a value in the V64 register class, produce the
4715 /// equivalent value in the V128 register class.
4716 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4717   EVT VT = V64Reg.getValueType();
4718   unsigned NarrowSize = VT.getVectorNumElements();
4719   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4720   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4721   SDLoc DL(V64Reg);
4722
4723   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4724                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4725 }
4726
4727 /// getExtFactor - Determine the adjustment factor for the position when
4728 /// generating an "extract from vector registers" instruction.
4729 static unsigned getExtFactor(SDValue &V) {
4730   EVT EltType = V.getValueType().getVectorElementType();
4731   return EltType.getSizeInBits() / 8;
4732 }
4733
4734 /// NarrowVector - Given a value in the V128 register class, produce the
4735 /// equivalent value in the V64 register class.
4736 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4737   EVT VT = V128Reg.getValueType();
4738   unsigned WideSize = VT.getVectorNumElements();
4739   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4740   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4741   SDLoc DL(V128Reg);
4742
4743   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4744 }
4745
4746 // Gather data to see if the operation can be modelled as a
4747 // shuffle in combination with VEXTs.
4748 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4749                                                   SelectionDAG &DAG) const {
4750   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4751   SDLoc dl(Op);
4752   EVT VT = Op.getValueType();
4753   unsigned NumElts = VT.getVectorNumElements();
4754
4755   struct ShuffleSourceInfo {
4756     SDValue Vec;
4757     unsigned MinElt;
4758     unsigned MaxElt;
4759
4760     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4761     // be compatible with the shuffle we intend to construct. As a result
4762     // ShuffleVec will be some sliding window into the original Vec.
4763     SDValue ShuffleVec;
4764
4765     // Code should guarantee that element i in Vec starts at element "WindowBase
4766     // + i * WindowScale in ShuffleVec".
4767     int WindowBase;
4768     int WindowScale;
4769
4770     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4771     ShuffleSourceInfo(SDValue Vec)
4772         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4773           WindowScale(1) {}
4774   };
4775
4776   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4777   // node.
4778   SmallVector<ShuffleSourceInfo, 2> Sources;
4779   for (unsigned i = 0; i < NumElts; ++i) {
4780     SDValue V = Op.getOperand(i);
4781     if (V.getOpcode() == ISD::UNDEF)
4782       continue;
4783     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4784       // A shuffle can only come from building a vector from various
4785       // elements of other vectors.
4786       return SDValue();
4787     }
4788
4789     // Add this element source to the list if it's not already there.
4790     SDValue SourceVec = V.getOperand(0);
4791     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4792     if (Source == Sources.end())
4793       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4794
4795     // Update the minimum and maximum lane number seen.
4796     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4797     Source->MinElt = std::min(Source->MinElt, EltNo);
4798     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4799   }
4800
4801   // Currently only do something sane when at most two source vectors
4802   // are involved.
4803   if (Sources.size() > 2)
4804     return SDValue();
4805
4806   // Find out the smallest element size among result and two sources, and use
4807   // it as element size to build the shuffle_vector.
4808   EVT SmallestEltTy = VT.getVectorElementType();
4809   for (auto &Source : Sources) {
4810     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4811     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4812       SmallestEltTy = SrcEltTy;
4813     }
4814   }
4815   unsigned ResMultiplier =
4816       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4817   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4818   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4819
4820   // If the source vector is too wide or too narrow, we may nevertheless be able
4821   // to construct a compatible shuffle either by concatenating it with UNDEF or
4822   // extracting a suitable range of elements.
4823   for (auto &Src : Sources) {
4824     EVT SrcVT = Src.ShuffleVec.getValueType();
4825
4826     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4827       continue;
4828
4829     // This stage of the search produces a source with the same element type as
4830     // the original, but with a total width matching the BUILD_VECTOR output.
4831     EVT EltVT = SrcVT.getVectorElementType();
4832     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4833     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4834
4835     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4836       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4837       // We can pad out the smaller vector for free, so if it's part of a
4838       // shuffle...
4839       Src.ShuffleVec =
4840           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4841                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4842       continue;
4843     }
4844
4845     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4846
4847     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4848       // Span too large for a VEXT to cope
4849       return SDValue();
4850     }
4851
4852     if (Src.MinElt >= NumSrcElts) {
4853       // The extraction can just take the second half
4854       Src.ShuffleVec =
4855           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4856                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4857       Src.WindowBase = -NumSrcElts;
4858     } else if (Src.MaxElt < NumSrcElts) {
4859       // The extraction can just take the first half
4860       Src.ShuffleVec =
4861           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4862                       DAG.getConstant(0, dl, MVT::i64));
4863     } else {
4864       // An actual VEXT is needed
4865       SDValue VEXTSrc1 =
4866           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4867                       DAG.getConstant(0, dl, MVT::i64));
4868       SDValue VEXTSrc2 =
4869           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4870                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4871       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4872
4873       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4874                                    VEXTSrc2,
4875                                    DAG.getConstant(Imm, dl, MVT::i32));
4876       Src.WindowBase = -Src.MinElt;
4877     }
4878   }
4879
4880   // Another possible incompatibility occurs from the vector element types. We
4881   // can fix this by bitcasting the source vectors to the same type we intend
4882   // for the shuffle.
4883   for (auto &Src : Sources) {
4884     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4885     if (SrcEltTy == SmallestEltTy)
4886       continue;
4887     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4888     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4889     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4890     Src.WindowBase *= Src.WindowScale;
4891   }
4892
4893   // Final sanity check before we try to actually produce a shuffle.
4894   DEBUG(
4895     for (auto Src : Sources)
4896       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4897   );
4898
4899   // The stars all align, our next step is to produce the mask for the shuffle.
4900   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4901   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4902   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4903     SDValue Entry = Op.getOperand(i);
4904     if (Entry.getOpcode() == ISD::UNDEF)
4905       continue;
4906
4907     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4908     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4909
4910     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4911     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4912     // segment.
4913     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4914     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4915                                VT.getVectorElementType().getSizeInBits());
4916     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4917
4918     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4919     // starting at the appropriate offset.
4920     int *LaneMask = &Mask[i * ResMultiplier];
4921
4922     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4923     ExtractBase += NumElts * (Src - Sources.begin());
4924     for (int j = 0; j < LanesDefined; ++j)
4925       LaneMask[j] = ExtractBase + j;
4926   }
4927
4928   // Final check before we try to produce nonsense...
4929   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4930     return SDValue();
4931
4932   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4933   for (unsigned i = 0; i < Sources.size(); ++i)
4934     ShuffleOps[i] = Sources[i].ShuffleVec;
4935
4936   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4937                                          ShuffleOps[1], &Mask[0]);
4938   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4939 }
4940
4941 // check if an EXT instruction can handle the shuffle mask when the
4942 // vector sources of the shuffle are the same.
4943 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4944   unsigned NumElts = VT.getVectorNumElements();
4945
4946   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4947   if (M[0] < 0)
4948     return false;
4949
4950   Imm = M[0];
4951
4952   // If this is a VEXT shuffle, the immediate value is the index of the first
4953   // element.  The other shuffle indices must be the successive elements after
4954   // the first one.
4955   unsigned ExpectedElt = Imm;
4956   for (unsigned i = 1; i < NumElts; ++i) {
4957     // Increment the expected index.  If it wraps around, just follow it
4958     // back to index zero and keep going.
4959     ++ExpectedElt;
4960     if (ExpectedElt == NumElts)
4961       ExpectedElt = 0;
4962
4963     if (M[i] < 0)
4964       continue; // ignore UNDEF indices
4965     if (ExpectedElt != static_cast<unsigned>(M[i]))
4966       return false;
4967   }
4968
4969   return true;
4970 }
4971
4972 // check if an EXT instruction can handle the shuffle mask when the
4973 // vector sources of the shuffle are different.
4974 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4975                       unsigned &Imm) {
4976   // Look for the first non-undef element.
4977   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4978       [](int Elt) {return Elt >= 0;});
4979
4980   // Benefit form APInt to handle overflow when calculating expected element.
4981   unsigned NumElts = VT.getVectorNumElements();
4982   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4983   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4984   // The following shuffle indices must be the successive elements after the
4985   // first real element.
4986   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4987       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4988   if (FirstWrongElt != M.end())
4989     return false;
4990
4991   // The index of an EXT is the first element if it is not UNDEF.
4992   // Watch out for the beginning UNDEFs. The EXT index should be the expected
4993   // value of the first element.  E.g. 
4994   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4995   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4996   // ExpectedElt is the last mask index plus 1.
4997   Imm = ExpectedElt.getZExtValue();
4998
4999   // There are two difference cases requiring to reverse input vectors.
5000   // For example, for vector <4 x i32> we have the following cases,
5001   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5002   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5003   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5004   // to reverse two input vectors.
5005   if (Imm < NumElts)
5006     ReverseEXT = true;
5007   else
5008     Imm -= NumElts;
5009
5010   return true;
5011 }
5012
5013 /// isREVMask - Check if a vector shuffle corresponds to a REV
5014 /// instruction with the specified blocksize.  (The order of the elements
5015 /// within each block of the vector is reversed.)
5016 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5017   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5018          "Only possible block sizes for REV are: 16, 32, 64");
5019
5020   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5021   if (EltSz == 64)
5022     return false;
5023
5024   unsigned NumElts = VT.getVectorNumElements();
5025   unsigned BlockElts = M[0] + 1;
5026   // If the first shuffle index is UNDEF, be optimistic.
5027   if (M[0] < 0)
5028     BlockElts = BlockSize / EltSz;
5029
5030   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5031     return false;
5032
5033   for (unsigned i = 0; i < NumElts; ++i) {
5034     if (M[i] < 0)
5035       continue; // ignore UNDEF indices
5036     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5037       return false;
5038   }
5039
5040   return true;
5041 }
5042
5043 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5044   unsigned NumElts = VT.getVectorNumElements();
5045   WhichResult = (M[0] == 0 ? 0 : 1);
5046   unsigned Idx = WhichResult * NumElts / 2;
5047   for (unsigned i = 0; i != NumElts; i += 2) {
5048     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5049         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5050       return false;
5051     Idx += 1;
5052   }
5053
5054   return true;
5055 }
5056
5057 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5058   unsigned NumElts = VT.getVectorNumElements();
5059   WhichResult = (M[0] == 0 ? 0 : 1);
5060   for (unsigned i = 0; i != NumElts; ++i) {
5061     if (M[i] < 0)
5062       continue; // ignore UNDEF indices
5063     if ((unsigned)M[i] != 2 * i + WhichResult)
5064       return false;
5065   }
5066
5067   return true;
5068 }
5069
5070 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5071   unsigned NumElts = VT.getVectorNumElements();
5072   WhichResult = (M[0] == 0 ? 0 : 1);
5073   for (unsigned i = 0; i < NumElts; i += 2) {
5074     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5075         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5076       return false;
5077   }
5078   return true;
5079 }
5080
5081 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5082 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5083 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5084 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5085   unsigned NumElts = VT.getVectorNumElements();
5086   WhichResult = (M[0] == 0 ? 0 : 1);
5087   unsigned Idx = WhichResult * NumElts / 2;
5088   for (unsigned i = 0; i != NumElts; i += 2) {
5089     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5090         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5091       return false;
5092     Idx += 1;
5093   }
5094
5095   return true;
5096 }
5097
5098 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5099 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5100 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5101 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5102   unsigned Half = VT.getVectorNumElements() / 2;
5103   WhichResult = (M[0] == 0 ? 0 : 1);
5104   for (unsigned j = 0; j != 2; ++j) {
5105     unsigned Idx = WhichResult;
5106     for (unsigned i = 0; i != Half; ++i) {
5107       int MIdx = M[i + j * Half];
5108       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5109         return false;
5110       Idx += 2;
5111     }
5112   }
5113
5114   return true;
5115 }
5116
5117 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5118 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5119 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5120 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5121   unsigned NumElts = VT.getVectorNumElements();
5122   WhichResult = (M[0] == 0 ? 0 : 1);
5123   for (unsigned i = 0; i < NumElts; i += 2) {
5124     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5125         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5126       return false;
5127   }
5128   return true;
5129 }
5130
5131 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5132                       bool &DstIsLeft, int &Anomaly) {
5133   if (M.size() != static_cast<size_t>(NumInputElements))
5134     return false;
5135
5136   int NumLHSMatch = 0, NumRHSMatch = 0;
5137   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5138
5139   for (int i = 0; i < NumInputElements; ++i) {
5140     if (M[i] == -1) {
5141       ++NumLHSMatch;
5142       ++NumRHSMatch;
5143       continue;
5144     }
5145
5146     if (M[i] == i)
5147       ++NumLHSMatch;
5148     else
5149       LastLHSMismatch = i;
5150
5151     if (M[i] == i + NumInputElements)
5152       ++NumRHSMatch;
5153     else
5154       LastRHSMismatch = i;
5155   }
5156
5157   if (NumLHSMatch == NumInputElements - 1) {
5158     DstIsLeft = true;
5159     Anomaly = LastLHSMismatch;
5160     return true;
5161   } else if (NumRHSMatch == NumInputElements - 1) {
5162     DstIsLeft = false;
5163     Anomaly = LastRHSMismatch;
5164     return true;
5165   }
5166
5167   return false;
5168 }
5169
5170 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5171   if (VT.getSizeInBits() != 128)
5172     return false;
5173
5174   unsigned NumElts = VT.getVectorNumElements();
5175
5176   for (int I = 0, E = NumElts / 2; I != E; I++) {
5177     if (Mask[I] != I)
5178       return false;
5179   }
5180
5181   int Offset = NumElts / 2;
5182   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5183     if (Mask[I] != I + SplitLHS * Offset)
5184       return false;
5185   }
5186
5187   return true;
5188 }
5189
5190 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5191   SDLoc DL(Op);
5192   EVT VT = Op.getValueType();
5193   SDValue V0 = Op.getOperand(0);
5194   SDValue V1 = Op.getOperand(1);
5195   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5196
5197   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5198       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5199     return SDValue();
5200
5201   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5202
5203   if (!isConcatMask(Mask, VT, SplitV0))
5204     return SDValue();
5205
5206   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5207                                 VT.getVectorNumElements() / 2);
5208   if (SplitV0) {
5209     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5210                      DAG.getConstant(0, DL, MVT::i64));
5211   }
5212   if (V1.getValueType().getSizeInBits() == 128) {
5213     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5214                      DAG.getConstant(0, DL, MVT::i64));
5215   }
5216   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5217 }
5218
5219 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5220 /// the specified operations to build the shuffle.
5221 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5222                                       SDValue RHS, SelectionDAG &DAG,
5223                                       SDLoc dl) {
5224   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5225   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5226   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5227
5228   enum {
5229     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5230     OP_VREV,
5231     OP_VDUP0,
5232     OP_VDUP1,
5233     OP_VDUP2,
5234     OP_VDUP3,
5235     OP_VEXT1,
5236     OP_VEXT2,
5237     OP_VEXT3,
5238     OP_VUZPL, // VUZP, left result
5239     OP_VUZPR, // VUZP, right result
5240     OP_VZIPL, // VZIP, left result
5241     OP_VZIPR, // VZIP, right result
5242     OP_VTRNL, // VTRN, left result
5243     OP_VTRNR  // VTRN, right result
5244   };
5245
5246   if (OpNum == OP_COPY) {
5247     if (LHSID == (1 * 9 + 2) * 9 + 3)
5248       return LHS;
5249     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5250     return RHS;
5251   }
5252
5253   SDValue OpLHS, OpRHS;
5254   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5255   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5256   EVT VT = OpLHS.getValueType();
5257
5258   switch (OpNum) {
5259   default:
5260     llvm_unreachable("Unknown shuffle opcode!");
5261   case OP_VREV:
5262     // VREV divides the vector in half and swaps within the half.
5263     if (VT.getVectorElementType() == MVT::i32 ||
5264         VT.getVectorElementType() == MVT::f32)
5265       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5266     // vrev <4 x i16> -> REV32
5267     if (VT.getVectorElementType() == MVT::i16 ||
5268         VT.getVectorElementType() == MVT::f16)
5269       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5270     // vrev <4 x i8> -> REV16
5271     assert(VT.getVectorElementType() == MVT::i8);
5272     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5273   case OP_VDUP0:
5274   case OP_VDUP1:
5275   case OP_VDUP2:
5276   case OP_VDUP3: {
5277     EVT EltTy = VT.getVectorElementType();
5278     unsigned Opcode;
5279     if (EltTy == MVT::i8)
5280       Opcode = AArch64ISD::DUPLANE8;
5281     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5282       Opcode = AArch64ISD::DUPLANE16;
5283     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5284       Opcode = AArch64ISD::DUPLANE32;
5285     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5286       Opcode = AArch64ISD::DUPLANE64;
5287     else
5288       llvm_unreachable("Invalid vector element type?");
5289
5290     if (VT.getSizeInBits() == 64)
5291       OpLHS = WidenVector(OpLHS, DAG);
5292     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5293     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5294   }
5295   case OP_VEXT1:
5296   case OP_VEXT2:
5297   case OP_VEXT3: {
5298     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5299     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5300                        DAG.getConstant(Imm, dl, MVT::i32));
5301   }
5302   case OP_VUZPL:
5303     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5304                        OpRHS);
5305   case OP_VUZPR:
5306     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5307                        OpRHS);
5308   case OP_VZIPL:
5309     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5310                        OpRHS);
5311   case OP_VZIPR:
5312     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5313                        OpRHS);
5314   case OP_VTRNL:
5315     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5316                        OpRHS);
5317   case OP_VTRNR:
5318     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5319                        OpRHS);
5320   }
5321 }
5322
5323 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5324                            SelectionDAG &DAG) {
5325   // Check to see if we can use the TBL instruction.
5326   SDValue V1 = Op.getOperand(0);
5327   SDValue V2 = Op.getOperand(1);
5328   SDLoc DL(Op);
5329
5330   EVT EltVT = Op.getValueType().getVectorElementType();
5331   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5332
5333   SmallVector<SDValue, 8> TBLMask;
5334   for (int Val : ShuffleMask) {
5335     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5336       unsigned Offset = Byte + Val * BytesPerElt;
5337       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5338     }
5339   }
5340
5341   MVT IndexVT = MVT::v8i8;
5342   unsigned IndexLen = 8;
5343   if (Op.getValueType().getSizeInBits() == 128) {
5344     IndexVT = MVT::v16i8;
5345     IndexLen = 16;
5346   }
5347
5348   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5349   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5350
5351   SDValue Shuffle;
5352   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5353     if (IndexLen == 8)
5354       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5355     Shuffle = DAG.getNode(
5356         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5357         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5358         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5359                     makeArrayRef(TBLMask.data(), IndexLen)));
5360   } else {
5361     if (IndexLen == 8) {
5362       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5363       Shuffle = DAG.getNode(
5364           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5365           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5366           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5367                       makeArrayRef(TBLMask.data(), IndexLen)));
5368     } else {
5369       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5370       // cannot currently represent the register constraints on the input
5371       // table registers.
5372       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5373       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5374       //                               &TBLMask[0], IndexLen));
5375       Shuffle = DAG.getNode(
5376           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5377           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5378           V1Cst, V2Cst,
5379           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5380                       makeArrayRef(TBLMask.data(), IndexLen)));
5381     }
5382   }
5383   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5384 }
5385
5386 static unsigned getDUPLANEOp(EVT EltType) {
5387   if (EltType == MVT::i8)
5388     return AArch64ISD::DUPLANE8;
5389   if (EltType == MVT::i16 || EltType == MVT::f16)
5390     return AArch64ISD::DUPLANE16;
5391   if (EltType == MVT::i32 || EltType == MVT::f32)
5392     return AArch64ISD::DUPLANE32;
5393   if (EltType == MVT::i64 || EltType == MVT::f64)
5394     return AArch64ISD::DUPLANE64;
5395
5396   llvm_unreachable("Invalid vector element type?");
5397 }
5398
5399 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5400                                                    SelectionDAG &DAG) const {
5401   SDLoc dl(Op);
5402   EVT VT = Op.getValueType();
5403
5404   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5405
5406   // Convert shuffles that are directly supported on NEON to target-specific
5407   // DAG nodes, instead of keeping them as shuffles and matching them again
5408   // during code selection.  This is more efficient and avoids the possibility
5409   // of inconsistencies between legalization and selection.
5410   ArrayRef<int> ShuffleMask = SVN->getMask();
5411
5412   SDValue V1 = Op.getOperand(0);
5413   SDValue V2 = Op.getOperand(1);
5414
5415   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5416                                        V1.getValueType().getSimpleVT())) {
5417     int Lane = SVN->getSplatIndex();
5418     // If this is undef splat, generate it via "just" vdup, if possible.
5419     if (Lane == -1)
5420       Lane = 0;
5421
5422     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5423       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5424                          V1.getOperand(0));
5425     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5426     // constant. If so, we can just reference the lane's definition directly.
5427     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5428         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5429       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5430
5431     // Otherwise, duplicate from the lane of the input vector.
5432     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5433
5434     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5435     // to make a vector of the same size as this SHUFFLE. We can ignore the
5436     // extract entirely, and canonicalise the concat using WidenVector.
5437     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5438       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5439       V1 = V1.getOperand(0);
5440     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5441       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5442       Lane -= Idx * VT.getVectorNumElements() / 2;
5443       V1 = WidenVector(V1.getOperand(Idx), DAG);
5444     } else if (VT.getSizeInBits() == 64)
5445       V1 = WidenVector(V1, DAG);
5446
5447     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5448   }
5449
5450   if (isREVMask(ShuffleMask, VT, 64))
5451     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5452   if (isREVMask(ShuffleMask, VT, 32))
5453     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5454   if (isREVMask(ShuffleMask, VT, 16))
5455     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5456
5457   bool ReverseEXT = false;
5458   unsigned Imm;
5459   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5460     if (ReverseEXT)
5461       std::swap(V1, V2);
5462     Imm *= getExtFactor(V1);
5463     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5464                        DAG.getConstant(Imm, dl, MVT::i32));
5465   } else if (V2->getOpcode() == ISD::UNDEF &&
5466              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5467     Imm *= getExtFactor(V1);
5468     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5469                        DAG.getConstant(Imm, dl, MVT::i32));
5470   }
5471
5472   unsigned WhichResult;
5473   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5474     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5475     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5476   }
5477   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5478     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5479     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5480   }
5481   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5482     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5483     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5484   }
5485
5486   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5487     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5488     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5489   }
5490   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5491     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5492     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5493   }
5494   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5495     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5496     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5497   }
5498
5499   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5500   if (Concat.getNode())
5501     return Concat;
5502
5503   bool DstIsLeft;
5504   int Anomaly;
5505   int NumInputElements = V1.getValueType().getVectorNumElements();
5506   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5507     SDValue DstVec = DstIsLeft ? V1 : V2;
5508     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5509
5510     SDValue SrcVec = V1;
5511     int SrcLane = ShuffleMask[Anomaly];
5512     if (SrcLane >= NumInputElements) {
5513       SrcVec = V2;
5514       SrcLane -= VT.getVectorNumElements();
5515     }
5516     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5517
5518     EVT ScalarVT = VT.getVectorElementType();
5519
5520     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5521       ScalarVT = MVT::i32;
5522
5523     return DAG.getNode(
5524         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5525         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5526         DstLaneV);
5527   }
5528
5529   // If the shuffle is not directly supported and it has 4 elements, use
5530   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5531   unsigned NumElts = VT.getVectorNumElements();
5532   if (NumElts == 4) {
5533     unsigned PFIndexes[4];
5534     for (unsigned i = 0; i != 4; ++i) {
5535       if (ShuffleMask[i] < 0)
5536         PFIndexes[i] = 8;
5537       else
5538         PFIndexes[i] = ShuffleMask[i];
5539     }
5540
5541     // Compute the index in the perfect shuffle table.
5542     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5543                             PFIndexes[2] * 9 + PFIndexes[3];
5544     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5545     unsigned Cost = (PFEntry >> 30);
5546
5547     if (Cost <= 4)
5548       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5549   }
5550
5551   return GenerateTBL(Op, ShuffleMask, DAG);
5552 }
5553
5554 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5555                                APInt &UndefBits) {
5556   EVT VT = BVN->getValueType(0);
5557   APInt SplatBits, SplatUndef;
5558   unsigned SplatBitSize;
5559   bool HasAnyUndefs;
5560   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5561     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5562
5563     for (unsigned i = 0; i < NumSplats; ++i) {
5564       CnstBits <<= SplatBitSize;
5565       UndefBits <<= SplatBitSize;
5566       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5567       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5568     }
5569
5570     return true;
5571   }
5572
5573   return false;
5574 }
5575
5576 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5577                                               SelectionDAG &DAG) const {
5578   BuildVectorSDNode *BVN =
5579       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5580   SDValue LHS = Op.getOperand(0);
5581   SDLoc dl(Op);
5582   EVT VT = Op.getValueType();
5583
5584   if (!BVN)
5585     return Op;
5586
5587   APInt CnstBits(VT.getSizeInBits(), 0);
5588   APInt UndefBits(VT.getSizeInBits(), 0);
5589   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5590     // We only have BIC vector immediate instruction, which is and-not.
5591     CnstBits = ~CnstBits;
5592
5593     // We make use of a little bit of goto ickiness in order to avoid having to
5594     // duplicate the immediate matching logic for the undef toggled case.
5595     bool SecondTry = false;
5596   AttemptModImm:
5597
5598     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5599       CnstBits = CnstBits.zextOrTrunc(64);
5600       uint64_t CnstVal = CnstBits.getZExtValue();
5601
5602       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5603         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5604         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5605         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5606                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5607                                   DAG.getConstant(0, dl, MVT::i32));
5608         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5609       }
5610
5611       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5612         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5613         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5614         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5615                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5616                                   DAG.getConstant(8, dl, MVT::i32));
5617         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5618       }
5619
5620       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5621         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5622         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5623         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5624                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5625                                   DAG.getConstant(16, dl, MVT::i32));
5626         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5627       }
5628
5629       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5630         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5631         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5632         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5633                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5634                                   DAG.getConstant(24, dl, MVT::i32));
5635         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5636       }
5637
5638       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5639         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5640         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5641         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5642                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5643                                   DAG.getConstant(0, dl, MVT::i32));
5644         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5645       }
5646
5647       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5648         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5649         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5650         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5651                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5652                                   DAG.getConstant(8, dl, MVT::i32));
5653         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5654       }
5655     }
5656
5657     if (SecondTry)
5658       goto FailedModImm;
5659     SecondTry = true;
5660     CnstBits = ~UndefBits;
5661     goto AttemptModImm;
5662   }
5663
5664 // We can always fall back to a non-immediate AND.
5665 FailedModImm:
5666   return Op;
5667 }
5668
5669 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5670 // consists of only the same constant int value, returned in reference arg
5671 // ConstVal
5672 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5673                                      uint64_t &ConstVal) {
5674   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5675   if (!Bvec)
5676     return false;
5677   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5678   if (!FirstElt)
5679     return false;
5680   EVT VT = Bvec->getValueType(0);
5681   unsigned NumElts = VT.getVectorNumElements();
5682   for (unsigned i = 1; i < NumElts; ++i)
5683     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5684       return false;
5685   ConstVal = FirstElt->getZExtValue();
5686   return true;
5687 }
5688
5689 static unsigned getIntrinsicID(const SDNode *N) {
5690   unsigned Opcode = N->getOpcode();
5691   switch (Opcode) {
5692   default:
5693     return Intrinsic::not_intrinsic;
5694   case ISD::INTRINSIC_WO_CHAIN: {
5695     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5696     if (IID < Intrinsic::num_intrinsics)
5697       return IID;
5698     return Intrinsic::not_intrinsic;
5699   }
5700   }
5701 }
5702
5703 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5704 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5705 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5706 // Also, logical shift right -> sri, with the same structure.
5707 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5708   EVT VT = N->getValueType(0);
5709
5710   if (!VT.isVector())
5711     return SDValue();
5712
5713   SDLoc DL(N);
5714
5715   // Is the first op an AND?
5716   const SDValue And = N->getOperand(0);
5717   if (And.getOpcode() != ISD::AND)
5718     return SDValue();
5719
5720   // Is the second op an shl or lshr?
5721   SDValue Shift = N->getOperand(1);
5722   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5723   // or AArch64ISD::VLSHR vector, #shift
5724   unsigned ShiftOpc = Shift.getOpcode();
5725   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5726     return SDValue();
5727   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5728
5729   // Is the shift amount constant?
5730   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5731   if (!C2node)
5732     return SDValue();
5733
5734   // Is the and mask vector all constant?
5735   uint64_t C1;
5736   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5737     return SDValue();
5738
5739   // Is C1 == ~C2, taking into account how much one can shift elements of a
5740   // particular size?
5741   uint64_t C2 = C2node->getZExtValue();
5742   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5743   if (C2 > ElemSizeInBits)
5744     return SDValue();
5745   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5746   if ((C1 & ElemMask) != (~C2 & ElemMask))
5747     return SDValue();
5748
5749   SDValue X = And.getOperand(0);
5750   SDValue Y = Shift.getOperand(0);
5751
5752   unsigned Intrin =
5753       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5754   SDValue ResultSLI =
5755       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5756                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5757                   Shift.getOperand(1));
5758
5759   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5760   DEBUG(N->dump(&DAG));
5761   DEBUG(dbgs() << "into: \n");
5762   DEBUG(ResultSLI->dump(&DAG));
5763
5764   ++NumShiftInserts;
5765   return ResultSLI;
5766 }
5767
5768 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5769                                              SelectionDAG &DAG) const {
5770   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5771   if (EnableAArch64SlrGeneration) {
5772     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5773     if (Res.getNode())
5774       return Res;
5775   }
5776
5777   BuildVectorSDNode *BVN =
5778       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5779   SDValue LHS = Op.getOperand(1);
5780   SDLoc dl(Op);
5781   EVT VT = Op.getValueType();
5782
5783   // OR commutes, so try swapping the operands.
5784   if (!BVN) {
5785     LHS = Op.getOperand(0);
5786     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5787   }
5788   if (!BVN)
5789     return Op;
5790
5791   APInt CnstBits(VT.getSizeInBits(), 0);
5792   APInt UndefBits(VT.getSizeInBits(), 0);
5793   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5794     // We make use of a little bit of goto ickiness in order to avoid having to
5795     // duplicate the immediate matching logic for the undef toggled case.
5796     bool SecondTry = false;
5797   AttemptModImm:
5798
5799     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5800       CnstBits = CnstBits.zextOrTrunc(64);
5801       uint64_t CnstVal = CnstBits.getZExtValue();
5802
5803       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5804         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5805         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5806         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5807                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5808                                   DAG.getConstant(0, dl, MVT::i32));
5809         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5810       }
5811
5812       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5813         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5814         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5815         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5816                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5817                                   DAG.getConstant(8, dl, MVT::i32));
5818         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5819       }
5820
5821       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5822         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5823         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5824         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5825                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5826                                   DAG.getConstant(16, dl, MVT::i32));
5827         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5828       }
5829
5830       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5831         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5832         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5833         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5834                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5835                                   DAG.getConstant(24, dl, MVT::i32));
5836         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5837       }
5838
5839       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5840         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5841         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5842         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5843                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5844                                   DAG.getConstant(0, dl, MVT::i32));
5845         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5846       }
5847
5848       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5849         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5850         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5851         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5852                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5853                                   DAG.getConstant(8, dl, MVT::i32));
5854         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5855       }
5856     }
5857
5858     if (SecondTry)
5859       goto FailedModImm;
5860     SecondTry = true;
5861     CnstBits = UndefBits;
5862     goto AttemptModImm;
5863   }
5864
5865 // We can always fall back to a non-immediate OR.
5866 FailedModImm:
5867   return Op;
5868 }
5869
5870 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5871 // be truncated to fit element width.
5872 static SDValue NormalizeBuildVector(SDValue Op,
5873                                     SelectionDAG &DAG) {
5874   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5875   SDLoc dl(Op);
5876   EVT VT = Op.getValueType();
5877   EVT EltTy= VT.getVectorElementType();
5878
5879   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5880     return Op;
5881
5882   SmallVector<SDValue, 16> Ops;
5883   for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5884     SDValue Lane = Op.getOperand(I);
5885     if (Lane.getOpcode() == ISD::Constant) {
5886       APInt LowBits(EltTy.getSizeInBits(),
5887                     cast<ConstantSDNode>(Lane)->getZExtValue());
5888       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5889     }
5890     Ops.push_back(Lane);
5891   }
5892   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5893 }
5894
5895 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5896                                                  SelectionDAG &DAG) const {
5897   SDLoc dl(Op);
5898   EVT VT = Op.getValueType();
5899   Op = NormalizeBuildVector(Op, DAG);
5900   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5901
5902   APInt CnstBits(VT.getSizeInBits(), 0);
5903   APInt UndefBits(VT.getSizeInBits(), 0);
5904   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5905     // We make use of a little bit of goto ickiness in order to avoid having to
5906     // duplicate the immediate matching logic for the undef toggled case.
5907     bool SecondTry = false;
5908   AttemptModImm:
5909
5910     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5911       CnstBits = CnstBits.zextOrTrunc(64);
5912       uint64_t CnstVal = CnstBits.getZExtValue();
5913
5914       // Certain magic vector constants (used to express things like NOT
5915       // and NEG) are passed through unmodified.  This allows codegen patterns
5916       // for these operations to match.  Special-purpose patterns will lower
5917       // these immediates to MOVIs if it proves necessary.
5918       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5919         return Op;
5920
5921       // The many faces of MOVI...
5922       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5923         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5924         if (VT.getSizeInBits() == 128) {
5925           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5926                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5927           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5928         }
5929
5930         // Support the V64 version via subregister insertion.
5931         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5932                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5933         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5934       }
5935
5936       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5937         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5938         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5939         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5940                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5941                                   DAG.getConstant(0, dl, MVT::i32));
5942         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5943       }
5944
5945       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5946         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5947         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5948         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5949                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5950                                   DAG.getConstant(8, dl, MVT::i32));
5951         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5952       }
5953
5954       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5955         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5956         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5957         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5958                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5959                                   DAG.getConstant(16, dl, MVT::i32));
5960         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5961       }
5962
5963       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5964         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5965         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5966         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5967                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5968                                   DAG.getConstant(24, dl, MVT::i32));
5969         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5970       }
5971
5972       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5973         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5974         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5975         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5976                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5977                                   DAG.getConstant(0, dl, MVT::i32));
5978         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5979       }
5980
5981       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5982         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5983         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5984         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5985                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5986                                   DAG.getConstant(8, dl, MVT::i32));
5987         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5988       }
5989
5990       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5991         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5992         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5993         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5994                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5995                                   DAG.getConstant(264, dl, MVT::i32));
5996         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5997       }
5998
5999       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6000         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6001         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6002         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6003                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6004                                   DAG.getConstant(272, dl, MVT::i32));
6005         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6006       }
6007
6008       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6009         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6010         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6011         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6012                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6013         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6014       }
6015
6016       // The few faces of FMOV...
6017       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6018         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6019         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6020         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6021                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6022         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6023       }
6024
6025       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6026           VT.getSizeInBits() == 128) {
6027         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6028         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6029                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6030         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6031       }
6032
6033       // The many faces of MVNI...
6034       CnstVal = ~CnstVal;
6035       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6036         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6037         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6038         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6039                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6040                                   DAG.getConstant(0, dl, MVT::i32));
6041         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6042       }
6043
6044       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6045         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6046         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6047         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6048                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6049                                   DAG.getConstant(8, dl, MVT::i32));
6050         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6051       }
6052
6053       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6054         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6055         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6056         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6057                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6058                                   DAG.getConstant(16, dl, MVT::i32));
6059         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6060       }
6061
6062       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6063         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6064         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6065         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6066                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6067                                   DAG.getConstant(24, dl, MVT::i32));
6068         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6069       }
6070
6071       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6072         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6073         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6074         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6075                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6076                                   DAG.getConstant(0, dl, MVT::i32));
6077         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6078       }
6079
6080       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6081         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6082         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6083         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6084                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6085                                   DAG.getConstant(8, dl, MVT::i32));
6086         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6087       }
6088
6089       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6090         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6091         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6092         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6093                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6094                                   DAG.getConstant(264, dl, MVT::i32));
6095         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6096       }
6097
6098       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6099         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6100         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6101         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6102                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6103                                   DAG.getConstant(272, dl, MVT::i32));
6104         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6105       }
6106     }
6107
6108     if (SecondTry)
6109       goto FailedModImm;
6110     SecondTry = true;
6111     CnstBits = UndefBits;
6112     goto AttemptModImm;
6113   }
6114 FailedModImm:
6115
6116   // Scan through the operands to find some interesting properties we can
6117   // exploit:
6118   //   1) If only one value is used, we can use a DUP, or
6119   //   2) if only the low element is not undef, we can just insert that, or
6120   //   3) if only one constant value is used (w/ some non-constant lanes),
6121   //      we can splat the constant value into the whole vector then fill
6122   //      in the non-constant lanes.
6123   //   4) FIXME: If different constant values are used, but we can intelligently
6124   //             select the values we'll be overwriting for the non-constant
6125   //             lanes such that we can directly materialize the vector
6126   //             some other way (MOVI, e.g.), we can be sneaky.
6127   unsigned NumElts = VT.getVectorNumElements();
6128   bool isOnlyLowElement = true;
6129   bool usesOnlyOneValue = true;
6130   bool usesOnlyOneConstantValue = true;
6131   bool isConstant = true;
6132   unsigned NumConstantLanes = 0;
6133   SDValue Value;
6134   SDValue ConstantValue;
6135   for (unsigned i = 0; i < NumElts; ++i) {
6136     SDValue V = Op.getOperand(i);
6137     if (V.getOpcode() == ISD::UNDEF)
6138       continue;
6139     if (i > 0)
6140       isOnlyLowElement = false;
6141     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6142       isConstant = false;
6143
6144     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6145       ++NumConstantLanes;
6146       if (!ConstantValue.getNode())
6147         ConstantValue = V;
6148       else if (ConstantValue != V)
6149         usesOnlyOneConstantValue = false;
6150     }
6151
6152     if (!Value.getNode())
6153       Value = V;
6154     else if (V != Value)
6155       usesOnlyOneValue = false;
6156   }
6157
6158   if (!Value.getNode())
6159     return DAG.getUNDEF(VT);
6160
6161   if (isOnlyLowElement)
6162     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6163
6164   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6165   // i32 and try again.
6166   if (usesOnlyOneValue) {
6167     if (!isConstant) {
6168       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6169           Value.getValueType() != VT)
6170         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6171
6172       // This is actually a DUPLANExx operation, which keeps everything vectory.
6173
6174       // DUPLANE works on 128-bit vectors, widen it if necessary.
6175       SDValue Lane = Value.getOperand(1);
6176       Value = Value.getOperand(0);
6177       if (Value.getValueType().getSizeInBits() == 64)
6178         Value = WidenVector(Value, DAG);
6179
6180       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6181       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6182     }
6183
6184     if (VT.getVectorElementType().isFloatingPoint()) {
6185       SmallVector<SDValue, 8> Ops;
6186       EVT EltTy = VT.getVectorElementType();
6187       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6188               "Unsupported floating-point vector type");
6189       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6190       for (unsigned i = 0; i < NumElts; ++i)
6191         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6192       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6193       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6194       Val = LowerBUILD_VECTOR(Val, DAG);
6195       if (Val.getNode())
6196         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6197     }
6198   }
6199
6200   // If there was only one constant value used and for more than one lane,
6201   // start by splatting that value, then replace the non-constant lanes. This
6202   // is better than the default, which will perform a separate initialization
6203   // for each lane.
6204   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6205     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6206     // Now insert the non-constant lanes.
6207     for (unsigned i = 0; i < NumElts; ++i) {
6208       SDValue V = Op.getOperand(i);
6209       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6210       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6211         // Note that type legalization likely mucked about with the VT of the
6212         // source operand, so we may have to convert it here before inserting.
6213         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6214       }
6215     }
6216     return Val;
6217   }
6218
6219   // If all elements are constants and the case above didn't get hit, fall back
6220   // to the default expansion, which will generate a load from the constant
6221   // pool.
6222   if (isConstant)
6223     return SDValue();
6224
6225   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6226   if (NumElts >= 4) {
6227     SDValue shuffle = ReconstructShuffle(Op, DAG);
6228     if (shuffle != SDValue())
6229       return shuffle;
6230   }
6231
6232   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6233   // know the default expansion would otherwise fall back on something even
6234   // worse. For a vector with one or two non-undef values, that's
6235   // scalar_to_vector for the elements followed by a shuffle (provided the
6236   // shuffle is valid for the target) and materialization element by element
6237   // on the stack followed by a load for everything else.
6238   if (!isConstant && !usesOnlyOneValue) {
6239     SDValue Vec = DAG.getUNDEF(VT);
6240     SDValue Op0 = Op.getOperand(0);
6241     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6242     unsigned i = 0;
6243     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6244     // a) Avoid a RMW dependency on the full vector register, and
6245     // b) Allow the register coalescer to fold away the copy if the
6246     //    value is already in an S or D register.
6247     if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6248       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6249       MachineSDNode *N =
6250           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6251                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6252       Vec = SDValue(N, 0);
6253       ++i;
6254     }
6255     for (; i < NumElts; ++i) {
6256       SDValue V = Op.getOperand(i);
6257       if (V.getOpcode() == ISD::UNDEF)
6258         continue;
6259       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6260       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6261     }
6262     return Vec;
6263   }
6264
6265   // Just use the default expansion. We failed to find a better alternative.
6266   return SDValue();
6267 }
6268
6269 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6270                                                       SelectionDAG &DAG) const {
6271   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6272
6273   // Check for non-constant or out of range lane.
6274   EVT VT = Op.getOperand(0).getValueType();
6275   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6276   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6277     return SDValue();
6278
6279
6280   // Insertion/extraction are legal for V128 types.
6281   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6282       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6283       VT == MVT::v8f16)
6284     return Op;
6285
6286   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6287       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6288     return SDValue();
6289
6290   // For V64 types, we perform insertion by expanding the value
6291   // to a V128 type and perform the insertion on that.
6292   SDLoc DL(Op);
6293   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6294   EVT WideTy = WideVec.getValueType();
6295
6296   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6297                              Op.getOperand(1), Op.getOperand(2));
6298   // Re-narrow the resultant vector.
6299   return NarrowVector(Node, DAG);
6300 }
6301
6302 SDValue
6303 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6304                                                SelectionDAG &DAG) const {
6305   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6306
6307   // Check for non-constant or out of range lane.
6308   EVT VT = Op.getOperand(0).getValueType();
6309   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6310   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6311     return SDValue();
6312
6313
6314   // Insertion/extraction are legal for V128 types.
6315   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6316       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6317       VT == MVT::v8f16)
6318     return Op;
6319
6320   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6321       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6322     return SDValue();
6323
6324   // For V64 types, we perform extraction by expanding the value
6325   // to a V128 type and perform the extraction on that.
6326   SDLoc DL(Op);
6327   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6328   EVT WideTy = WideVec.getValueType();
6329
6330   EVT ExtrTy = WideTy.getVectorElementType();
6331   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6332     ExtrTy = MVT::i32;
6333
6334   // For extractions, we just return the result directly.
6335   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6336                      Op.getOperand(1));
6337 }
6338
6339 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6340                                                       SelectionDAG &DAG) const {
6341   EVT VT = Op.getOperand(0).getValueType();
6342   SDLoc dl(Op);
6343   // Just in case...
6344   if (!VT.isVector())
6345     return SDValue();
6346
6347   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6348   if (!Cst)
6349     return SDValue();
6350   unsigned Val = Cst->getZExtValue();
6351
6352   unsigned Size = Op.getValueType().getSizeInBits();
6353   if (Val == 0) {
6354     switch (Size) {
6355     case 8:
6356       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6357                                         Op.getOperand(0));
6358     case 16:
6359       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6360                                         Op.getOperand(0));
6361     case 32:
6362       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6363                                         Op.getOperand(0));
6364     case 64:
6365       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6366                                         Op.getOperand(0));
6367     default:
6368       llvm_unreachable("Unexpected vector type in extract_subvector!");
6369     }
6370   }
6371   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6372   // that directly.
6373   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6374     return Op;
6375
6376   return SDValue();
6377 }
6378
6379 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6380                                                EVT VT) const {
6381   if (VT.getVectorNumElements() == 4 &&
6382       (VT.is128BitVector() || VT.is64BitVector())) {
6383     unsigned PFIndexes[4];
6384     for (unsigned i = 0; i != 4; ++i) {
6385       if (M[i] < 0)
6386         PFIndexes[i] = 8;
6387       else
6388         PFIndexes[i] = M[i];
6389     }
6390
6391     // Compute the index in the perfect shuffle table.
6392     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6393                             PFIndexes[2] * 9 + PFIndexes[3];
6394     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6395     unsigned Cost = (PFEntry >> 30);
6396
6397     if (Cost <= 4)
6398       return true;
6399   }
6400
6401   bool DummyBool;
6402   int DummyInt;
6403   unsigned DummyUnsigned;
6404
6405   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6406           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6407           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6408           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6409           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6410           isZIPMask(M, VT, DummyUnsigned) ||
6411           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6412           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6413           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6414           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6415           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6416 }
6417
6418 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6419 /// operand of a vector shift operation, where all the elements of the
6420 /// build_vector must have the same constant integer value.
6421 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6422   // Ignore bit_converts.
6423   while (Op.getOpcode() == ISD::BITCAST)
6424     Op = Op.getOperand(0);
6425   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6426   APInt SplatBits, SplatUndef;
6427   unsigned SplatBitSize;
6428   bool HasAnyUndefs;
6429   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6430                                     HasAnyUndefs, ElementBits) ||
6431       SplatBitSize > ElementBits)
6432     return false;
6433   Cnt = SplatBits.getSExtValue();
6434   return true;
6435 }
6436
6437 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6438 /// operand of a vector shift left operation.  That value must be in the range:
6439 ///   0 <= Value < ElementBits for a left shift; or
6440 ///   0 <= Value <= ElementBits for a long left shift.
6441 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6442   assert(VT.isVector() && "vector shift count is not a vector type");
6443   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6444   if (!getVShiftImm(Op, ElementBits, Cnt))
6445     return false;
6446   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6447 }
6448
6449 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6450 /// operand of a vector shift right operation.  For a shift opcode, the value
6451 /// is positive, but for an intrinsic the value count must be negative. The
6452 /// absolute value must be in the range:
6453 ///   1 <= |Value| <= ElementBits for a right shift; or
6454 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6455 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6456                          int64_t &Cnt) {
6457   assert(VT.isVector() && "vector shift count is not a vector type");
6458   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6459   if (!getVShiftImm(Op, ElementBits, Cnt))
6460     return false;
6461   if (isIntrinsic)
6462     Cnt = -Cnt;
6463   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6464 }
6465
6466 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6467                                                       SelectionDAG &DAG) const {
6468   EVT VT = Op.getValueType();
6469   SDLoc DL(Op);
6470   int64_t Cnt;
6471
6472   if (!Op.getOperand(1).getValueType().isVector())
6473     return Op;
6474   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6475
6476   switch (Op.getOpcode()) {
6477   default:
6478     llvm_unreachable("unexpected shift opcode");
6479
6480   case ISD::SHL:
6481     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6482       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6483                          DAG.getConstant(Cnt, DL, MVT::i32));
6484     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6485                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6486                                        MVT::i32),
6487                        Op.getOperand(0), Op.getOperand(1));
6488   case ISD::SRA:
6489   case ISD::SRL:
6490     // Right shift immediate
6491     if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6492         Cnt < EltSize) {
6493       unsigned Opc =
6494           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6495       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6496                          DAG.getConstant(Cnt, DL, MVT::i32));
6497     }
6498
6499     // Right shift register.  Note, there is not a shift right register
6500     // instruction, but the shift left register instruction takes a signed
6501     // value, where negative numbers specify a right shift.
6502     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6503                                                 : Intrinsic::aarch64_neon_ushl;
6504     // negate the shift amount
6505     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6506     SDValue NegShiftLeft =
6507         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6508                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6509                     NegShift);
6510     return NegShiftLeft;
6511   }
6512
6513   return SDValue();
6514 }
6515
6516 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6517                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6518                                     SDLoc dl, SelectionDAG &DAG) {
6519   EVT SrcVT = LHS.getValueType();
6520   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6521          "function only supposed to emit natural comparisons");
6522
6523   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6524   APInt CnstBits(VT.getSizeInBits(), 0);
6525   APInt UndefBits(VT.getSizeInBits(), 0);
6526   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6527   bool IsZero = IsCnst && (CnstBits == 0);
6528
6529   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6530     switch (CC) {
6531     default:
6532       return SDValue();
6533     case AArch64CC::NE: {
6534       SDValue Fcmeq;
6535       if (IsZero)
6536         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6537       else
6538         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6539       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6540     }
6541     case AArch64CC::EQ:
6542       if (IsZero)
6543         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6544       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6545     case AArch64CC::GE:
6546       if (IsZero)
6547         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6548       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6549     case AArch64CC::GT:
6550       if (IsZero)
6551         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6552       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6553     case AArch64CC::LS:
6554       if (IsZero)
6555         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6556       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6557     case AArch64CC::LT:
6558       if (!NoNans)
6559         return SDValue();
6560     // If we ignore NaNs then we can use to the MI implementation.
6561     // Fallthrough.
6562     case AArch64CC::MI:
6563       if (IsZero)
6564         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6565       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6566     }
6567   }
6568
6569   switch (CC) {
6570   default:
6571     return SDValue();
6572   case AArch64CC::NE: {
6573     SDValue Cmeq;
6574     if (IsZero)
6575       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6576     else
6577       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6578     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6579   }
6580   case AArch64CC::EQ:
6581     if (IsZero)
6582       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6583     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6584   case AArch64CC::GE:
6585     if (IsZero)
6586       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6587     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6588   case AArch64CC::GT:
6589     if (IsZero)
6590       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6591     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6592   case AArch64CC::LE:
6593     if (IsZero)
6594       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6595     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6596   case AArch64CC::LS:
6597     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6598   case AArch64CC::LO:
6599     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6600   case AArch64CC::LT:
6601     if (IsZero)
6602       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6603     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6604   case AArch64CC::HI:
6605     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6606   case AArch64CC::HS:
6607     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6608   }
6609 }
6610
6611 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6612                                            SelectionDAG &DAG) const {
6613   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6614   SDValue LHS = Op.getOperand(0);
6615   SDValue RHS = Op.getOperand(1);
6616   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6617   SDLoc dl(Op);
6618
6619   if (LHS.getValueType().getVectorElementType().isInteger()) {
6620     assert(LHS.getValueType() == RHS.getValueType());
6621     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6622     SDValue Cmp =
6623         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6624     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6625   }
6626
6627   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6628          LHS.getValueType().getVectorElementType() == MVT::f64);
6629
6630   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6631   // clean.  Some of them require two branches to implement.
6632   AArch64CC::CondCode CC1, CC2;
6633   bool ShouldInvert;
6634   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6635
6636   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6637   SDValue Cmp =
6638       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6639   if (!Cmp.getNode())
6640     return SDValue();
6641
6642   if (CC2 != AArch64CC::AL) {
6643     SDValue Cmp2 =
6644         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6645     if (!Cmp2.getNode())
6646       return SDValue();
6647
6648     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6649   }
6650
6651   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6652
6653   if (ShouldInvert)
6654     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6655
6656   return Cmp;
6657 }
6658
6659 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6660 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6661 /// specified in the intrinsic calls.
6662 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6663                                                const CallInst &I,
6664                                                unsigned Intrinsic) const {
6665   auto &DL = I.getModule()->getDataLayout();
6666   switch (Intrinsic) {
6667   case Intrinsic::aarch64_neon_ld2:
6668   case Intrinsic::aarch64_neon_ld3:
6669   case Intrinsic::aarch64_neon_ld4:
6670   case Intrinsic::aarch64_neon_ld1x2:
6671   case Intrinsic::aarch64_neon_ld1x3:
6672   case Intrinsic::aarch64_neon_ld1x4:
6673   case Intrinsic::aarch64_neon_ld2lane:
6674   case Intrinsic::aarch64_neon_ld3lane:
6675   case Intrinsic::aarch64_neon_ld4lane:
6676   case Intrinsic::aarch64_neon_ld2r:
6677   case Intrinsic::aarch64_neon_ld3r:
6678   case Intrinsic::aarch64_neon_ld4r: {
6679     Info.opc = ISD::INTRINSIC_W_CHAIN;
6680     // Conservatively set memVT to the entire set of vectors loaded.
6681     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6682     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6683     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6684     Info.offset = 0;
6685     Info.align = 0;
6686     Info.vol = false; // volatile loads with NEON intrinsics not supported
6687     Info.readMem = true;
6688     Info.writeMem = false;
6689     return true;
6690   }
6691   case Intrinsic::aarch64_neon_st2:
6692   case Intrinsic::aarch64_neon_st3:
6693   case Intrinsic::aarch64_neon_st4:
6694   case Intrinsic::aarch64_neon_st1x2:
6695   case Intrinsic::aarch64_neon_st1x3:
6696   case Intrinsic::aarch64_neon_st1x4:
6697   case Intrinsic::aarch64_neon_st2lane:
6698   case Intrinsic::aarch64_neon_st3lane:
6699   case Intrinsic::aarch64_neon_st4lane: {
6700     Info.opc = ISD::INTRINSIC_VOID;
6701     // Conservatively set memVT to the entire set of vectors stored.
6702     unsigned NumElts = 0;
6703     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6704       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6705       if (!ArgTy->isVectorTy())
6706         break;
6707       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6708     }
6709     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6710     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6711     Info.offset = 0;
6712     Info.align = 0;
6713     Info.vol = false; // volatile stores with NEON intrinsics not supported
6714     Info.readMem = false;
6715     Info.writeMem = true;
6716     return true;
6717   }
6718   case Intrinsic::aarch64_ldaxr:
6719   case Intrinsic::aarch64_ldxr: {
6720     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6721     Info.opc = ISD::INTRINSIC_W_CHAIN;
6722     Info.memVT = MVT::getVT(PtrTy->getElementType());
6723     Info.ptrVal = I.getArgOperand(0);
6724     Info.offset = 0;
6725     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6726     Info.vol = true;
6727     Info.readMem = true;
6728     Info.writeMem = false;
6729     return true;
6730   }
6731   case Intrinsic::aarch64_stlxr:
6732   case Intrinsic::aarch64_stxr: {
6733     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6734     Info.opc = ISD::INTRINSIC_W_CHAIN;
6735     Info.memVT = MVT::getVT(PtrTy->getElementType());
6736     Info.ptrVal = I.getArgOperand(1);
6737     Info.offset = 0;
6738     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6739     Info.vol = true;
6740     Info.readMem = false;
6741     Info.writeMem = true;
6742     return true;
6743   }
6744   case Intrinsic::aarch64_ldaxp:
6745   case Intrinsic::aarch64_ldxp: {
6746     Info.opc = ISD::INTRINSIC_W_CHAIN;
6747     Info.memVT = MVT::i128;
6748     Info.ptrVal = I.getArgOperand(0);
6749     Info.offset = 0;
6750     Info.align = 16;
6751     Info.vol = true;
6752     Info.readMem = true;
6753     Info.writeMem = false;
6754     return true;
6755   }
6756   case Intrinsic::aarch64_stlxp:
6757   case Intrinsic::aarch64_stxp: {
6758     Info.opc = ISD::INTRINSIC_W_CHAIN;
6759     Info.memVT = MVT::i128;
6760     Info.ptrVal = I.getArgOperand(2);
6761     Info.offset = 0;
6762     Info.align = 16;
6763     Info.vol = true;
6764     Info.readMem = false;
6765     Info.writeMem = true;
6766     return true;
6767   }
6768   default:
6769     break;
6770   }
6771
6772   return false;
6773 }
6774
6775 // Truncations from 64-bit GPR to 32-bit GPR is free.
6776 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6777   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6778     return false;
6779   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6780   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6781   return NumBits1 > NumBits2;
6782 }
6783 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6784   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6785     return false;
6786   unsigned NumBits1 = VT1.getSizeInBits();
6787   unsigned NumBits2 = VT2.getSizeInBits();
6788   return NumBits1 > NumBits2;
6789 }
6790
6791 /// Check if it is profitable to hoist instruction in then/else to if.
6792 /// Not profitable if I and it's user can form a FMA instruction
6793 /// because we prefer FMSUB/FMADD.
6794 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6795   if (I->getOpcode() != Instruction::FMul)
6796     return true;
6797
6798   if (I->getNumUses() != 1)
6799     return true;
6800
6801   Instruction *User = I->user_back();
6802
6803   if (User &&
6804       !(User->getOpcode() == Instruction::FSub ||
6805         User->getOpcode() == Instruction::FAdd))
6806     return true;
6807
6808   const TargetOptions &Options = getTargetMachine().Options;
6809   const DataLayout &DL = I->getModule()->getDataLayout();
6810   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6811
6812   if (isFMAFasterThanFMulAndFAdd(VT) &&
6813       isOperationLegalOrCustom(ISD::FMA, VT) &&
6814       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6815     return false;
6816
6817   return true;
6818 }
6819
6820 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6821 // 64-bit GPR.
6822 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6823   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6824     return false;
6825   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6826   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6827   return NumBits1 == 32 && NumBits2 == 64;
6828 }
6829 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6830   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6831     return false;
6832   unsigned NumBits1 = VT1.getSizeInBits();
6833   unsigned NumBits2 = VT2.getSizeInBits();
6834   return NumBits1 == 32 && NumBits2 == 64;
6835 }
6836
6837 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6838   EVT VT1 = Val.getValueType();
6839   if (isZExtFree(VT1, VT2)) {
6840     return true;
6841   }
6842
6843   if (Val.getOpcode() != ISD::LOAD)
6844     return false;
6845
6846   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6847   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6848           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6849           VT1.getSizeInBits() <= 32);
6850 }
6851
6852 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6853   if (isa<FPExtInst>(Ext))
6854     return false;
6855
6856   // Vector types are next free.
6857   if (Ext->getType()->isVectorTy())
6858     return false;
6859
6860   for (const Use &U : Ext->uses()) {
6861     // The extension is free if we can fold it with a left shift in an
6862     // addressing mode or an arithmetic operation: add, sub, and cmp.
6863
6864     // Is there a shift?
6865     const Instruction *Instr = cast<Instruction>(U.getUser());
6866
6867     // Is this a constant shift?
6868     switch (Instr->getOpcode()) {
6869     case Instruction::Shl:
6870       if (!isa<ConstantInt>(Instr->getOperand(1)))
6871         return false;
6872       break;
6873     case Instruction::GetElementPtr: {
6874       gep_type_iterator GTI = gep_type_begin(Instr);
6875       auto &DL = Ext->getModule()->getDataLayout();
6876       std::advance(GTI, U.getOperandNo());
6877       Type *IdxTy = *GTI;
6878       // This extension will end up with a shift because of the scaling factor.
6879       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6880       // Get the shift amount based on the scaling factor:
6881       // log2(sizeof(IdxTy)) - log2(8).
6882       uint64_t ShiftAmt =
6883           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6884       // Is the constant foldable in the shift of the addressing mode?
6885       // I.e., shift amount is between 1 and 4 inclusive.
6886       if (ShiftAmt == 0 || ShiftAmt > 4)
6887         return false;
6888       break;
6889     }
6890     case Instruction::Trunc:
6891       // Check if this is a noop.
6892       // trunc(sext ty1 to ty2) to ty1.
6893       if (Instr->getType() == Ext->getOperand(0)->getType())
6894         continue;
6895     // FALL THROUGH.
6896     default:
6897       return false;
6898     }
6899
6900     // At this point we can use the bfm family, so this extension is free
6901     // for that use.
6902   }
6903   return true;
6904 }
6905
6906 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6907                                           unsigned &RequiredAligment) const {
6908   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6909     return false;
6910   // Cyclone supports unaligned accesses.
6911   RequiredAligment = 0;
6912   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6913   return NumBits == 32 || NumBits == 64;
6914 }
6915
6916 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6917                                           unsigned &RequiredAligment) const {
6918   if (!LoadedType.isSimple() ||
6919       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6920     return false;
6921   // Cyclone supports unaligned accesses.
6922   RequiredAligment = 0;
6923   unsigned NumBits = LoadedType.getSizeInBits();
6924   return NumBits == 32 || NumBits == 64;
6925 }
6926
6927 /// \brief Lower an interleaved load into a ldN intrinsic.
6928 ///
6929 /// E.g. Lower an interleaved load (Factor = 2):
6930 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6931 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6932 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6933 ///
6934 ///      Into:
6935 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6936 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6937 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6938 bool AArch64TargetLowering::lowerInterleavedLoad(
6939     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6940     ArrayRef<unsigned> Indices, unsigned Factor) const {
6941   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6942          "Invalid interleave factor");
6943   assert(!Shuffles.empty() && "Empty shufflevector input");
6944   assert(Shuffles.size() == Indices.size() &&
6945          "Unmatched number of shufflevectors and indices");
6946
6947   const DataLayout &DL = LI->getModule()->getDataLayout();
6948
6949   VectorType *VecTy = Shuffles[0]->getType();
6950   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6951
6952   // Skip illegal vector types.
6953   if (VecSize != 64 && VecSize != 128)
6954     return false;
6955
6956   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6957   // load integer vectors first and then convert to pointer vectors.
6958   Type *EltTy = VecTy->getVectorElementType();
6959   if (EltTy->isPointerTy())
6960     VecTy =
6961         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6962
6963   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6964   Type *Tys[2] = {VecTy, PtrTy};
6965   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6966                                             Intrinsic::aarch64_neon_ld3,
6967                                             Intrinsic::aarch64_neon_ld4};
6968   Function *LdNFunc =
6969       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6970
6971   IRBuilder<> Builder(LI);
6972   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6973
6974   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6975
6976   // Replace uses of each shufflevector with the corresponding vector loaded
6977   // by ldN.
6978   for (unsigned i = 0; i < Shuffles.size(); i++) {
6979     ShuffleVectorInst *SVI = Shuffles[i];
6980     unsigned Index = Indices[i];
6981
6982     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
6983
6984     // Convert the integer vector to pointer vector if the element is pointer.
6985     if (EltTy->isPointerTy())
6986       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
6987
6988     SVI->replaceAllUsesWith(SubVec);
6989   }
6990
6991   return true;
6992 }
6993
6994 /// \brief Get a mask consisting of sequential integers starting from \p Start.
6995 ///
6996 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
6997 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
6998                                    unsigned NumElts) {
6999   SmallVector<Constant *, 16> Mask;
7000   for (unsigned i = 0; i < NumElts; i++)
7001     Mask.push_back(Builder.getInt32(Start + i));
7002
7003   return ConstantVector::get(Mask);
7004 }
7005
7006 /// \brief Lower an interleaved store into a stN intrinsic.
7007 ///
7008 /// E.g. Lower an interleaved store (Factor = 3):
7009 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7010 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7011 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7012 ///
7013 ///      Into:
7014 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7015 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7016 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7017 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7018 ///
7019 /// Note that the new shufflevectors will be removed and we'll only generate one
7020 /// st3 instruction in CodeGen.
7021 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7022                                                   ShuffleVectorInst *SVI,
7023                                                   unsigned Factor) const {
7024   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7025          "Invalid interleave factor");
7026
7027   VectorType *VecTy = SVI->getType();
7028   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7029          "Invalid interleaved store");
7030
7031   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7032   Type *EltTy = VecTy->getVectorElementType();
7033   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7034
7035   const DataLayout &DL = SI->getModule()->getDataLayout();
7036   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7037
7038   // Skip illegal vector types.
7039   if (SubVecSize != 64 && SubVecSize != 128)
7040     return false;
7041
7042   Value *Op0 = SVI->getOperand(0);
7043   Value *Op1 = SVI->getOperand(1);
7044   IRBuilder<> Builder(SI);
7045
7046   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7047   // vectors to integer vectors.
7048   if (EltTy->isPointerTy()) {
7049     Type *IntTy = DL.getIntPtrType(EltTy);
7050     unsigned NumOpElts =
7051         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7052
7053     // Convert to the corresponding integer vector.
7054     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7055     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7056     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7057
7058     SubVecTy = VectorType::get(IntTy, NumSubElts);
7059   }
7060
7061   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7062   Type *Tys[2] = {SubVecTy, PtrTy};
7063   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7064                                              Intrinsic::aarch64_neon_st3,
7065                                              Intrinsic::aarch64_neon_st4};
7066   Function *StNFunc =
7067       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7068
7069   SmallVector<Value *, 5> Ops;
7070
7071   // Split the shufflevector operands into sub vectors for the new stN call.
7072   for (unsigned i = 0; i < Factor; i++)
7073     Ops.push_back(Builder.CreateShuffleVector(
7074         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7075
7076   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7077   Builder.CreateCall(StNFunc, Ops);
7078   return true;
7079 }
7080
7081 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7082                        unsigned AlignCheck) {
7083   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7084           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7085 }
7086
7087 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7088                                                unsigned SrcAlign, bool IsMemset,
7089                                                bool ZeroMemset,
7090                                                bool MemcpyStrSrc,
7091                                                MachineFunction &MF) const {
7092   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7093   // instruction to materialize the v2i64 zero and one store (with restrictive
7094   // addressing mode). Just do two i64 store of zero-registers.
7095   bool Fast;
7096   const Function *F = MF.getFunction();
7097   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7098       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7099       (memOpAlign(SrcAlign, DstAlign, 16) ||
7100        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7101     return MVT::f128;
7102
7103   if (Size >= 8 &&
7104       (memOpAlign(SrcAlign, DstAlign, 8) ||
7105        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7106     return MVT::i64;
7107
7108   if (Size >= 4 &&
7109       (memOpAlign(SrcAlign, DstAlign, 4) ||
7110        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7111     return MVT::i32;
7112
7113   return MVT::Other;
7114 }
7115
7116 // 12-bit optionally shifted immediates are legal for adds.
7117 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7118   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7119     return true;
7120   return false;
7121 }
7122
7123 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7124 // immediates is the same as for an add or a sub.
7125 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7126   if (Immed < 0)
7127     Immed *= -1;
7128   return isLegalAddImmediate(Immed);
7129 }
7130
7131 /// isLegalAddressingMode - Return true if the addressing mode represented
7132 /// by AM is legal for this target, for a load/store of the specified type.
7133 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7134                                                   const AddrMode &AM, Type *Ty,
7135                                                   unsigned AS) const {
7136   // AArch64 has five basic addressing modes:
7137   //  reg
7138   //  reg + 9-bit signed offset
7139   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7140   //  reg1 + reg2
7141   //  reg + SIZE_IN_BYTES * reg
7142
7143   // No global is ever allowed as a base.
7144   if (AM.BaseGV)
7145     return false;
7146
7147   // No reg+reg+imm addressing.
7148   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7149     return false;
7150
7151   // check reg + imm case:
7152   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7153   uint64_t NumBytes = 0;
7154   if (Ty->isSized()) {
7155     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7156     NumBytes = NumBits / 8;
7157     if (!isPowerOf2_64(NumBits))
7158       NumBytes = 0;
7159   }
7160
7161   if (!AM.Scale) {
7162     int64_t Offset = AM.BaseOffs;
7163
7164     // 9-bit signed offset
7165     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7166       return true;
7167
7168     // 12-bit unsigned offset
7169     unsigned shift = Log2_64(NumBytes);
7170     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7171         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7172         (Offset >> shift) << shift == Offset)
7173       return true;
7174     return false;
7175   }
7176
7177   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7178
7179   if (!AM.Scale || AM.Scale == 1 ||
7180       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7181     return true;
7182   return false;
7183 }
7184
7185 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7186                                                 const AddrMode &AM, Type *Ty,
7187                                                 unsigned AS) const {
7188   // Scaling factors are not free at all.
7189   // Operands                     | Rt Latency
7190   // -------------------------------------------
7191   // Rt, [Xn, Xm]                 | 4
7192   // -------------------------------------------
7193   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7194   // Rt, [Xn, Wm, <extend> #imm]  |
7195   if (isLegalAddressingMode(DL, AM, Ty, AS))
7196     // Scale represents reg2 * scale, thus account for 1 if
7197     // it is not equal to 0 or 1.
7198     return AM.Scale != 0 && AM.Scale != 1;
7199   return -1;
7200 }
7201
7202 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7203   VT = VT.getScalarType();
7204
7205   if (!VT.isSimple())
7206     return false;
7207
7208   switch (VT.getSimpleVT().SimpleTy) {
7209   case MVT::f32:
7210   case MVT::f64:
7211     return true;
7212   default:
7213     break;
7214   }
7215
7216   return false;
7217 }
7218
7219 const MCPhysReg *
7220 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7221   // LR is a callee-save register, but we must treat it as clobbered by any call
7222   // site. Hence we include LR in the scratch registers, which are in turn added
7223   // as implicit-defs for stackmaps and patchpoints.
7224   static const MCPhysReg ScratchRegs[] = {
7225     AArch64::X16, AArch64::X17, AArch64::LR, 0
7226   };
7227   return ScratchRegs;
7228 }
7229
7230 bool
7231 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7232   EVT VT = N->getValueType(0);
7233     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7234     // it with shift to let it be lowered to UBFX.
7235   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7236       isa<ConstantSDNode>(N->getOperand(1))) {
7237     uint64_t TruncMask = N->getConstantOperandVal(1);
7238     if (isMask_64(TruncMask) &&
7239       N->getOperand(0).getOpcode() == ISD::SRL &&
7240       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7241       return false;
7242   }
7243   return true;
7244 }
7245
7246 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7247                                                               Type *Ty) const {
7248   assert(Ty->isIntegerTy());
7249
7250   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7251   if (BitSize == 0)
7252     return false;
7253
7254   int64_t Val = Imm.getSExtValue();
7255   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7256     return true;
7257
7258   if ((int64_t)Val < 0)
7259     Val = ~Val;
7260   if (BitSize == 32)
7261     Val &= (1LL << 32) - 1;
7262
7263   unsigned LZ = countLeadingZeros((uint64_t)Val);
7264   unsigned Shift = (63 - LZ) / 16;
7265   // MOVZ is free so return true for one or fewer MOVK.
7266   return Shift < 3;
7267 }
7268
7269 // Generate SUBS and CSEL for integer abs.
7270 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7271   EVT VT = N->getValueType(0);
7272
7273   SDValue N0 = N->getOperand(0);
7274   SDValue N1 = N->getOperand(1);
7275   SDLoc DL(N);
7276
7277   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7278   // and change it to SUB and CSEL.
7279   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7280       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7281       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7282     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7283       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7284         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7285                                   N0.getOperand(0));
7286         // Generate SUBS & CSEL.
7287         SDValue Cmp =
7288             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7289                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7290         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7291                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7292                            SDValue(Cmp.getNode(), 1));
7293       }
7294   return SDValue();
7295 }
7296
7297 // performXorCombine - Attempts to handle integer ABS.
7298 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7299                                  TargetLowering::DAGCombinerInfo &DCI,
7300                                  const AArch64Subtarget *Subtarget) {
7301   if (DCI.isBeforeLegalizeOps())
7302     return SDValue();
7303
7304   return performIntegerAbsCombine(N, DAG);
7305 }
7306
7307 SDValue
7308 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7309                                      SelectionDAG &DAG,
7310                                      std::vector<SDNode *> *Created) const {
7311   // fold (sdiv X, pow2)
7312   EVT VT = N->getValueType(0);
7313   if ((VT != MVT::i32 && VT != MVT::i64) ||
7314       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7315     return SDValue();
7316
7317   SDLoc DL(N);
7318   SDValue N0 = N->getOperand(0);
7319   unsigned Lg2 = Divisor.countTrailingZeros();
7320   SDValue Zero = DAG.getConstant(0, DL, VT);
7321   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7322
7323   // Add (N0 < 0) ? Pow2 - 1 : 0;
7324   SDValue CCVal;
7325   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7326   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7327   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7328
7329   if (Created) {
7330     Created->push_back(Cmp.getNode());
7331     Created->push_back(Add.getNode());
7332     Created->push_back(CSel.getNode());
7333   }
7334
7335   // Divide by pow2.
7336   SDValue SRA =
7337       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7338
7339   // If we're dividing by a positive value, we're done.  Otherwise, we must
7340   // negate the result.
7341   if (Divisor.isNonNegative())
7342     return SRA;
7343
7344   if (Created)
7345     Created->push_back(SRA.getNode());
7346   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7347 }
7348
7349 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7350                                  TargetLowering::DAGCombinerInfo &DCI,
7351                                  const AArch64Subtarget *Subtarget) {
7352   if (DCI.isBeforeLegalizeOps())
7353     return SDValue();
7354
7355   // Multiplication of a power of two plus/minus one can be done more
7356   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7357   // future CPUs have a cheaper MADD instruction, this may need to be
7358   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7359   // 64-bit is 5 cycles, so this is always a win.
7360   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7361     APInt Value = C->getAPIntValue();
7362     EVT VT = N->getValueType(0);
7363     SDLoc DL(N);
7364     if (Value.isNonNegative()) {
7365       // (mul x, 2^N + 1) => (add (shl x, N), x)
7366       APInt VM1 = Value - 1;
7367       if (VM1.isPowerOf2()) {
7368         SDValue ShiftedVal =
7369             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7370                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7371         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7372                            N->getOperand(0));
7373       }
7374       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7375       APInt VP1 = Value + 1;
7376       if (VP1.isPowerOf2()) {
7377         SDValue ShiftedVal =
7378             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7379                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7380         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7381                            N->getOperand(0));
7382       }
7383     } else {
7384       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7385       APInt VNP1 = -Value + 1;
7386       if (VNP1.isPowerOf2()) {
7387         SDValue ShiftedVal =
7388             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7389                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7390         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7391                            ShiftedVal);
7392       }
7393       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7394       APInt VNM1 = -Value - 1;
7395       if (VNM1.isPowerOf2()) {
7396         SDValue ShiftedVal =
7397             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7398                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7399         SDValue Add =
7400             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7401         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7402       }
7403     }
7404   }
7405   return SDValue();
7406 }
7407
7408 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7409                                                          SelectionDAG &DAG) {
7410   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7411   // optimize away operation when it's from a constant.
7412   //
7413   // The general transformation is:
7414   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7415   //       AND(VECTOR_CMP(x,y), constant2)
7416   //    constant2 = UNARYOP(constant)
7417
7418   // Early exit if this isn't a vector operation, the operand of the
7419   // unary operation isn't a bitwise AND, or if the sizes of the operations
7420   // aren't the same.
7421   EVT VT = N->getValueType(0);
7422   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7423       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7424       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7425     return SDValue();
7426
7427   // Now check that the other operand of the AND is a constant. We could
7428   // make the transformation for non-constant splats as well, but it's unclear
7429   // that would be a benefit as it would not eliminate any operations, just
7430   // perform one more step in scalar code before moving to the vector unit.
7431   if (BuildVectorSDNode *BV =
7432           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7433     // Bail out if the vector isn't a constant.
7434     if (!BV->isConstant())
7435       return SDValue();
7436
7437     // Everything checks out. Build up the new and improved node.
7438     SDLoc DL(N);
7439     EVT IntVT = BV->getValueType(0);
7440     // Create a new constant of the appropriate type for the transformed
7441     // DAG.
7442     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7443     // The AND node needs bitcasts to/from an integer vector type around it.
7444     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7445     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7446                                  N->getOperand(0)->getOperand(0), MaskConst);
7447     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7448     return Res;
7449   }
7450
7451   return SDValue();
7452 }
7453
7454 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7455                                      const AArch64Subtarget *Subtarget) {
7456   // First try to optimize away the conversion when it's conditionally from
7457   // a constant. Vectors only.
7458   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
7459   if (Res != SDValue())
7460     return Res;
7461
7462   EVT VT = N->getValueType(0);
7463   if (VT != MVT::f32 && VT != MVT::f64)
7464     return SDValue();
7465
7466   // Only optimize when the source and destination types have the same width.
7467   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7468     return SDValue();
7469
7470   // If the result of an integer load is only used by an integer-to-float
7471   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7472   // This eliminates an "integer-to-vector-move UOP and improve throughput.
7473   SDValue N0 = N->getOperand(0);
7474   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7475       // Do not change the width of a volatile load.
7476       !cast<LoadSDNode>(N0)->isVolatile()) {
7477     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7478     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7479                                LN0->getPointerInfo(), LN0->isVolatile(),
7480                                LN0->isNonTemporal(), LN0->isInvariant(),
7481                                LN0->getAlignment());
7482
7483     // Make sure successors of the original load stay after it by updating them
7484     // to use the new Chain.
7485     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7486
7487     unsigned Opcode =
7488         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7489     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7490   }
7491
7492   return SDValue();
7493 }
7494
7495 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7496 /// searches for and classifies those shifts.
7497 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7498                          bool &FromHi) {
7499   if (N.getOpcode() == ISD::SHL)
7500     FromHi = false;
7501   else if (N.getOpcode() == ISD::SRL)
7502     FromHi = true;
7503   else
7504     return false;
7505
7506   if (!isa<ConstantSDNode>(N.getOperand(1)))
7507     return false;
7508
7509   ShiftAmount = N->getConstantOperandVal(1);
7510   Src = N->getOperand(0);
7511   return true;
7512 }
7513
7514 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7515 /// registers viewed as a high/low pair. This function looks for the pattern:
7516 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7517 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7518 /// independent.
7519 static SDValue tryCombineToEXTR(SDNode *N,
7520                                 TargetLowering::DAGCombinerInfo &DCI) {
7521   SelectionDAG &DAG = DCI.DAG;
7522   SDLoc DL(N);
7523   EVT VT = N->getValueType(0);
7524
7525   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7526
7527   if (VT != MVT::i32 && VT != MVT::i64)
7528     return SDValue();
7529
7530   SDValue LHS;
7531   uint32_t ShiftLHS = 0;
7532   bool LHSFromHi = 0;
7533   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7534     return SDValue();
7535
7536   SDValue RHS;
7537   uint32_t ShiftRHS = 0;
7538   bool RHSFromHi = 0;
7539   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7540     return SDValue();
7541
7542   // If they're both trying to come from the high part of the register, they're
7543   // not really an EXTR.
7544   if (LHSFromHi == RHSFromHi)
7545     return SDValue();
7546
7547   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7548     return SDValue();
7549
7550   if (LHSFromHi) {
7551     std::swap(LHS, RHS);
7552     std::swap(ShiftLHS, ShiftRHS);
7553   }
7554
7555   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7556                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7557 }
7558
7559 static SDValue tryCombineToBSL(SDNode *N,
7560                                 TargetLowering::DAGCombinerInfo &DCI) {
7561   EVT VT = N->getValueType(0);
7562   SelectionDAG &DAG = DCI.DAG;
7563   SDLoc DL(N);
7564
7565   if (!VT.isVector())
7566     return SDValue();
7567
7568   SDValue N0 = N->getOperand(0);
7569   if (N0.getOpcode() != ISD::AND)
7570     return SDValue();
7571
7572   SDValue N1 = N->getOperand(1);
7573   if (N1.getOpcode() != ISD::AND)
7574     return SDValue();
7575
7576   // We only have to look for constant vectors here since the general, variable
7577   // case can be handled in TableGen.
7578   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7579   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7580   for (int i = 1; i >= 0; --i)
7581     for (int j = 1; j >= 0; --j) {
7582       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7583       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7584       if (!BVN0 || !BVN1)
7585         continue;
7586
7587       bool FoundMatch = true;
7588       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7589         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7590         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7591         if (!CN0 || !CN1 ||
7592             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7593           FoundMatch = false;
7594           break;
7595         }
7596       }
7597
7598       if (FoundMatch)
7599         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7600                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7601     }
7602
7603   return SDValue();
7604 }
7605
7606 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7607                                 const AArch64Subtarget *Subtarget) {
7608   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7609   if (!EnableAArch64ExtrGeneration)
7610     return SDValue();
7611   SelectionDAG &DAG = DCI.DAG;
7612   EVT VT = N->getValueType(0);
7613
7614   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7615     return SDValue();
7616
7617   SDValue Res = tryCombineToEXTR(N, DCI);
7618   if (Res.getNode())
7619     return Res;
7620
7621   Res = tryCombineToBSL(N, DCI);
7622   if (Res.getNode())
7623     return Res;
7624
7625   return SDValue();
7626 }
7627
7628 static SDValue performBitcastCombine(SDNode *N,
7629                                      TargetLowering::DAGCombinerInfo &DCI,
7630                                      SelectionDAG &DAG) {
7631   // Wait 'til after everything is legalized to try this. That way we have
7632   // legal vector types and such.
7633   if (DCI.isBeforeLegalizeOps())
7634     return SDValue();
7635
7636   // Remove extraneous bitcasts around an extract_subvector.
7637   // For example,
7638   //    (v4i16 (bitconvert
7639   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7640   //  becomes
7641   //    (extract_subvector ((v8i16 ...), (i64 4)))
7642
7643   // Only interested in 64-bit vectors as the ultimate result.
7644   EVT VT = N->getValueType(0);
7645   if (!VT.isVector())
7646     return SDValue();
7647   if (VT.getSimpleVT().getSizeInBits() != 64)
7648     return SDValue();
7649   // Is the operand an extract_subvector starting at the beginning or halfway
7650   // point of the vector? A low half may also come through as an
7651   // EXTRACT_SUBREG, so look for that, too.
7652   SDValue Op0 = N->getOperand(0);
7653   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7654       !(Op0->isMachineOpcode() &&
7655         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7656     return SDValue();
7657   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7658   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7659     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7660       return SDValue();
7661   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7662     if (idx != AArch64::dsub)
7663       return SDValue();
7664     // The dsub reference is equivalent to a lane zero subvector reference.
7665     idx = 0;
7666   }
7667   // Look through the bitcast of the input to the extract.
7668   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7669     return SDValue();
7670   SDValue Source = Op0->getOperand(0)->getOperand(0);
7671   // If the source type has twice the number of elements as our destination
7672   // type, we know this is an extract of the high or low half of the vector.
7673   EVT SVT = Source->getValueType(0);
7674   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7675     return SDValue();
7676
7677   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7678
7679   // Create the simplified form to just extract the low or high half of the
7680   // vector directly rather than bothering with the bitcasts.
7681   SDLoc dl(N);
7682   unsigned NumElements = VT.getVectorNumElements();
7683   if (idx) {
7684     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7685     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7686   } else {
7687     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7688     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7689                                       Source, SubReg),
7690                    0);
7691   }
7692 }
7693
7694 static SDValue performConcatVectorsCombine(SDNode *N,
7695                                            TargetLowering::DAGCombinerInfo &DCI,
7696                                            SelectionDAG &DAG) {
7697   SDLoc dl(N);
7698   EVT VT = N->getValueType(0);
7699   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7700
7701   // Optimize concat_vectors of truncated vectors, where the intermediate
7702   // type is illegal, to avoid said illegality,  e.g.,
7703   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7704   //                          (v2i16 (truncate (v2i64)))))
7705   // ->
7706   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7707   //                                    (v4i32 (bitcast (v2i64))),
7708   //                                    <0, 2, 4, 6>)))
7709   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7710   // on both input and result type, so we might generate worse code.
7711   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7712   if (N->getNumOperands() == 2 &&
7713       N0->getOpcode() == ISD::TRUNCATE &&
7714       N1->getOpcode() == ISD::TRUNCATE) {
7715     SDValue N00 = N0->getOperand(0);
7716     SDValue N10 = N1->getOperand(0);
7717     EVT N00VT = N00.getValueType();
7718
7719     if (N00VT == N10.getValueType() &&
7720         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7721         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7722       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7723       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7724       for (size_t i = 0; i < Mask.size(); ++i)
7725         Mask[i] = i * 2;
7726       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7727                          DAG.getVectorShuffle(
7728                              MidVT, dl,
7729                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7730                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7731     }
7732   }
7733
7734   // Wait 'til after everything is legalized to try this. That way we have
7735   // legal vector types and such.
7736   if (DCI.isBeforeLegalizeOps())
7737     return SDValue();
7738
7739   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7740   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7741   // canonicalise to that.
7742   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7743     assert(VT.getVectorElementType().getSizeInBits() == 64);
7744     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7745                        DAG.getConstant(0, dl, MVT::i64));
7746   }
7747
7748   // Canonicalise concat_vectors so that the right-hand vector has as few
7749   // bit-casts as possible before its real operation. The primary matching
7750   // destination for these operations will be the narrowing "2" instructions,
7751   // which depend on the operation being performed on this right-hand vector.
7752   // For example,
7753   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7754   // becomes
7755   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7756
7757   if (N1->getOpcode() != ISD::BITCAST)
7758     return SDValue();
7759   SDValue RHS = N1->getOperand(0);
7760   MVT RHSTy = RHS.getValueType().getSimpleVT();
7761   // If the RHS is not a vector, this is not the pattern we're looking for.
7762   if (!RHSTy.isVector())
7763     return SDValue();
7764
7765   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7766
7767   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7768                                   RHSTy.getVectorNumElements() * 2);
7769   return DAG.getNode(ISD::BITCAST, dl, VT,
7770                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7771                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7772                                  RHS));
7773 }
7774
7775 static SDValue tryCombineFixedPointConvert(SDNode *N,
7776                                            TargetLowering::DAGCombinerInfo &DCI,
7777                                            SelectionDAG &DAG) {
7778   // Wait 'til after everything is legalized to try this. That way we have
7779   // legal vector types and such.
7780   if (DCI.isBeforeLegalizeOps())
7781     return SDValue();
7782   // Transform a scalar conversion of a value from a lane extract into a
7783   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7784   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7785   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7786   //
7787   // The second form interacts better with instruction selection and the
7788   // register allocator to avoid cross-class register copies that aren't
7789   // coalescable due to a lane reference.
7790
7791   // Check the operand and see if it originates from a lane extract.
7792   SDValue Op1 = N->getOperand(1);
7793   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7794     // Yep, no additional predication needed. Perform the transform.
7795     SDValue IID = N->getOperand(0);
7796     SDValue Shift = N->getOperand(2);
7797     SDValue Vec = Op1.getOperand(0);
7798     SDValue Lane = Op1.getOperand(1);
7799     EVT ResTy = N->getValueType(0);
7800     EVT VecResTy;
7801     SDLoc DL(N);
7802
7803     // The vector width should be 128 bits by the time we get here, even
7804     // if it started as 64 bits (the extract_vector handling will have
7805     // done so).
7806     assert(Vec.getValueType().getSizeInBits() == 128 &&
7807            "unexpected vector size on extract_vector_elt!");
7808     if (Vec.getValueType() == MVT::v4i32)
7809       VecResTy = MVT::v4f32;
7810     else if (Vec.getValueType() == MVT::v2i64)
7811       VecResTy = MVT::v2f64;
7812     else
7813       llvm_unreachable("unexpected vector type!");
7814
7815     SDValue Convert =
7816         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7817     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7818   }
7819   return SDValue();
7820 }
7821
7822 // AArch64 high-vector "long" operations are formed by performing the non-high
7823 // version on an extract_subvector of each operand which gets the high half:
7824 //
7825 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7826 //
7827 // However, there are cases which don't have an extract_high explicitly, but
7828 // have another operation that can be made compatible with one for free. For
7829 // example:
7830 //
7831 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7832 //
7833 // This routine does the actual conversion of such DUPs, once outer routines
7834 // have determined that everything else is in order.
7835 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7836 // similarly here.
7837 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7838   switch (N.getOpcode()) {
7839   case AArch64ISD::DUP:
7840   case AArch64ISD::DUPLANE8:
7841   case AArch64ISD::DUPLANE16:
7842   case AArch64ISD::DUPLANE32:
7843   case AArch64ISD::DUPLANE64:
7844   case AArch64ISD::MOVI:
7845   case AArch64ISD::MOVIshift:
7846   case AArch64ISD::MOVIedit:
7847   case AArch64ISD::MOVImsl:
7848   case AArch64ISD::MVNIshift:
7849   case AArch64ISD::MVNImsl:
7850     break;
7851   default:
7852     // FMOV could be supported, but isn't very useful, as it would only occur
7853     // if you passed a bitcast' floating point immediate to an eligible long
7854     // integer op (addl, smull, ...).
7855     return SDValue();
7856   }
7857
7858   MVT NarrowTy = N.getSimpleValueType();
7859   if (!NarrowTy.is64BitVector())
7860     return SDValue();
7861
7862   MVT ElementTy = NarrowTy.getVectorElementType();
7863   unsigned NumElems = NarrowTy.getVectorNumElements();
7864   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7865
7866   SDLoc dl(N);
7867   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7868                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
7869                      DAG.getConstant(NumElems, dl, MVT::i64));
7870 }
7871
7872 static bool isEssentiallyExtractSubvector(SDValue N) {
7873   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7874     return true;
7875
7876   return N.getOpcode() == ISD::BITCAST &&
7877          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7878 }
7879
7880 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7881 struct GenericSetCCInfo {
7882   const SDValue *Opnd0;
7883   const SDValue *Opnd1;
7884   ISD::CondCode CC;
7885 };
7886
7887 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7888 struct AArch64SetCCInfo {
7889   const SDValue *Cmp;
7890   AArch64CC::CondCode CC;
7891 };
7892
7893 /// \brief Helper structure to keep track of SetCC information.
7894 union SetCCInfo {
7895   GenericSetCCInfo Generic;
7896   AArch64SetCCInfo AArch64;
7897 };
7898
7899 /// \brief Helper structure to be able to read SetCC information.  If set to
7900 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7901 /// GenericSetCCInfo.
7902 struct SetCCInfoAndKind {
7903   SetCCInfo Info;
7904   bool IsAArch64;
7905 };
7906
7907 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7908 /// an
7909 /// AArch64 lowered one.
7910 /// \p SetCCInfo is filled accordingly.
7911 /// \post SetCCInfo is meanginfull only when this function returns true.
7912 /// \return True when Op is a kind of SET_CC operation.
7913 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7914   // If this is a setcc, this is straight forward.
7915   if (Op.getOpcode() == ISD::SETCC) {
7916     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7917     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7918     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7919     SetCCInfo.IsAArch64 = false;
7920     return true;
7921   }
7922   // Otherwise, check if this is a matching csel instruction.
7923   // In other words:
7924   // - csel 1, 0, cc
7925   // - csel 0, 1, !cc
7926   if (Op.getOpcode() != AArch64ISD::CSEL)
7927     return false;
7928   // Set the information about the operands.
7929   // TODO: we want the operands of the Cmp not the csel
7930   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7931   SetCCInfo.IsAArch64 = true;
7932   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7933       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7934
7935   // Check that the operands matches the constraints:
7936   // (1) Both operands must be constants.
7937   // (2) One must be 1 and the other must be 0.
7938   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7939   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7940
7941   // Check (1).
7942   if (!TValue || !FValue)
7943     return false;
7944
7945   // Check (2).
7946   if (!TValue->isOne()) {
7947     // Update the comparison when we are interested in !cc.
7948     std::swap(TValue, FValue);
7949     SetCCInfo.Info.AArch64.CC =
7950         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7951   }
7952   return TValue->isOne() && FValue->isNullValue();
7953 }
7954
7955 // Returns true if Op is setcc or zext of setcc.
7956 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7957   if (isSetCC(Op, Info))
7958     return true;
7959   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7960     isSetCC(Op->getOperand(0), Info));
7961 }
7962
7963 // The folding we want to perform is:
7964 // (add x, [zext] (setcc cc ...) )
7965 //   -->
7966 // (csel x, (add x, 1), !cc ...)
7967 //
7968 // The latter will get matched to a CSINC instruction.
7969 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7970   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7971   SDValue LHS = Op->getOperand(0);
7972   SDValue RHS = Op->getOperand(1);
7973   SetCCInfoAndKind InfoAndKind;
7974
7975   // If neither operand is a SET_CC, give up.
7976   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7977     std::swap(LHS, RHS);
7978     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7979       return SDValue();
7980   }
7981
7982   // FIXME: This could be generatized to work for FP comparisons.
7983   EVT CmpVT = InfoAndKind.IsAArch64
7984                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7985                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
7986   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7987     return SDValue();
7988
7989   SDValue CCVal;
7990   SDValue Cmp;
7991   SDLoc dl(Op);
7992   if (InfoAndKind.IsAArch64) {
7993     CCVal = DAG.getConstant(
7994         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7995         MVT::i32);
7996     Cmp = *InfoAndKind.Info.AArch64.Cmp;
7997   } else
7998     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7999                       *InfoAndKind.Info.Generic.Opnd1,
8000                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8001                       CCVal, DAG, dl);
8002
8003   EVT VT = Op->getValueType(0);
8004   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8005   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8006 }
8007
8008 // The basic add/sub long vector instructions have variants with "2" on the end
8009 // which act on the high-half of their inputs. They are normally matched by
8010 // patterns like:
8011 //
8012 // (add (zeroext (extract_high LHS)),
8013 //      (zeroext (extract_high RHS)))
8014 // -> uaddl2 vD, vN, vM
8015 //
8016 // However, if one of the extracts is something like a duplicate, this
8017 // instruction can still be used profitably. This function puts the DAG into a
8018 // more appropriate form for those patterns to trigger.
8019 static SDValue performAddSubLongCombine(SDNode *N,
8020                                         TargetLowering::DAGCombinerInfo &DCI,
8021                                         SelectionDAG &DAG) {
8022   if (DCI.isBeforeLegalizeOps())
8023     return SDValue();
8024
8025   MVT VT = N->getSimpleValueType(0);
8026   if (!VT.is128BitVector()) {
8027     if (N->getOpcode() == ISD::ADD)
8028       return performSetccAddFolding(N, DAG);
8029     return SDValue();
8030   }
8031
8032   // Make sure both branches are extended in the same way.
8033   SDValue LHS = N->getOperand(0);
8034   SDValue RHS = N->getOperand(1);
8035   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8036        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8037       LHS.getOpcode() != RHS.getOpcode())
8038     return SDValue();
8039
8040   unsigned ExtType = LHS.getOpcode();
8041
8042   // It's not worth doing if at least one of the inputs isn't already an
8043   // extract, but we don't know which it'll be so we have to try both.
8044   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8045     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8046     if (!RHS.getNode())
8047       return SDValue();
8048
8049     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8050   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8051     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8052     if (!LHS.getNode())
8053       return SDValue();
8054
8055     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8056   }
8057
8058   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8059 }
8060
8061 // Massage DAGs which we can use the high-half "long" operations on into
8062 // something isel will recognize better. E.g.
8063 //
8064 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8065 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8066 //                     (extract_high (v2i64 (dup128 scalar)))))
8067 //
8068 static SDValue tryCombineLongOpWithDup(SDNode *N,
8069                                        TargetLowering::DAGCombinerInfo &DCI,
8070                                        SelectionDAG &DAG) {
8071   if (DCI.isBeforeLegalizeOps())
8072     return SDValue();
8073
8074   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8075   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8076   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8077   assert(LHS.getValueType().is64BitVector() &&
8078          RHS.getValueType().is64BitVector() &&
8079          "unexpected shape for long operation");
8080
8081   // Either node could be a DUP, but it's not worth doing both of them (you'd
8082   // just as well use the non-high version) so look for a corresponding extract
8083   // operation on the other "wing".
8084   if (isEssentiallyExtractSubvector(LHS)) {
8085     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8086     if (!RHS.getNode())
8087       return SDValue();
8088   } else if (isEssentiallyExtractSubvector(RHS)) {
8089     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8090     if (!LHS.getNode())
8091       return SDValue();
8092   }
8093
8094   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8095   if (IsIntrinsic)
8096     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8097                        N->getOperand(0), LHS, RHS);
8098   else
8099     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8100                        LHS, RHS);
8101 }
8102
8103 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8104   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8105   unsigned ElemBits = ElemTy.getSizeInBits();
8106
8107   int64_t ShiftAmount;
8108   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8109     APInt SplatValue, SplatUndef;
8110     unsigned SplatBitSize;
8111     bool HasAnyUndefs;
8112     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8113                               HasAnyUndefs, ElemBits) ||
8114         SplatBitSize != ElemBits)
8115       return SDValue();
8116
8117     ShiftAmount = SplatValue.getSExtValue();
8118   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8119     ShiftAmount = CVN->getSExtValue();
8120   } else
8121     return SDValue();
8122
8123   unsigned Opcode;
8124   bool IsRightShift;
8125   switch (IID) {
8126   default:
8127     llvm_unreachable("Unknown shift intrinsic");
8128   case Intrinsic::aarch64_neon_sqshl:
8129     Opcode = AArch64ISD::SQSHL_I;
8130     IsRightShift = false;
8131     break;
8132   case Intrinsic::aarch64_neon_uqshl:
8133     Opcode = AArch64ISD::UQSHL_I;
8134     IsRightShift = false;
8135     break;
8136   case Intrinsic::aarch64_neon_srshl:
8137     Opcode = AArch64ISD::SRSHR_I;
8138     IsRightShift = true;
8139     break;
8140   case Intrinsic::aarch64_neon_urshl:
8141     Opcode = AArch64ISD::URSHR_I;
8142     IsRightShift = true;
8143     break;
8144   case Intrinsic::aarch64_neon_sqshlu:
8145     Opcode = AArch64ISD::SQSHLU_I;
8146     IsRightShift = false;
8147     break;
8148   }
8149
8150   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8151     SDLoc dl(N);
8152     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8153                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8154   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8155     SDLoc dl(N);
8156     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8157                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8158   }
8159
8160   return SDValue();
8161 }
8162
8163 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8164 // the intrinsics must be legal and take an i32, this means there's almost
8165 // certainly going to be a zext in the DAG which we can eliminate.
8166 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8167   SDValue AndN = N->getOperand(2);
8168   if (AndN.getOpcode() != ISD::AND)
8169     return SDValue();
8170
8171   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8172   if (!CMask || CMask->getZExtValue() != Mask)
8173     return SDValue();
8174
8175   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8176                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8177 }
8178
8179 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8180                                            SelectionDAG &DAG) {
8181   SDLoc dl(N);
8182   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8183                      DAG.getNode(Opc, dl,
8184                                  N->getOperand(1).getSimpleValueType(),
8185                                  N->getOperand(1)),
8186                      DAG.getConstant(0, dl, MVT::i64));
8187 }
8188
8189 static SDValue performIntrinsicCombine(SDNode *N,
8190                                        TargetLowering::DAGCombinerInfo &DCI,
8191                                        const AArch64Subtarget *Subtarget) {
8192   SelectionDAG &DAG = DCI.DAG;
8193   unsigned IID = getIntrinsicID(N);
8194   switch (IID) {
8195   default:
8196     break;
8197   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8198   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8199     return tryCombineFixedPointConvert(N, DCI, DAG);
8200     break;
8201   case Intrinsic::aarch64_neon_saddv:
8202     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8203   case Intrinsic::aarch64_neon_uaddv:
8204     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8205   case Intrinsic::aarch64_neon_sminv:
8206     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8207   case Intrinsic::aarch64_neon_uminv:
8208     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8209   case Intrinsic::aarch64_neon_smaxv:
8210     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8211   case Intrinsic::aarch64_neon_umaxv:
8212     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8213   case Intrinsic::aarch64_neon_fmax:
8214     return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
8215                        N->getOperand(1), N->getOperand(2));
8216   case Intrinsic::aarch64_neon_fmin:
8217     return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
8218                        N->getOperand(1), N->getOperand(2));
8219   case Intrinsic::aarch64_neon_sabd:
8220     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8221                        N->getOperand(1), N->getOperand(2));
8222   case Intrinsic::aarch64_neon_uabd:
8223     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8224                        N->getOperand(1), N->getOperand(2));
8225   case Intrinsic::aarch64_neon_smull:
8226   case Intrinsic::aarch64_neon_umull:
8227   case Intrinsic::aarch64_neon_pmull:
8228   case Intrinsic::aarch64_neon_sqdmull:
8229     return tryCombineLongOpWithDup(N, DCI, DAG);
8230   case Intrinsic::aarch64_neon_sqshl:
8231   case Intrinsic::aarch64_neon_uqshl:
8232   case Intrinsic::aarch64_neon_sqshlu:
8233   case Intrinsic::aarch64_neon_srshl:
8234   case Intrinsic::aarch64_neon_urshl:
8235     return tryCombineShiftImm(IID, N, DAG);
8236   case Intrinsic::aarch64_crc32b:
8237   case Intrinsic::aarch64_crc32cb:
8238     return tryCombineCRC32(0xff, N, DAG);
8239   case Intrinsic::aarch64_crc32h:
8240   case Intrinsic::aarch64_crc32ch:
8241     return tryCombineCRC32(0xffff, N, DAG);
8242   }
8243   return SDValue();
8244 }
8245
8246 static SDValue performExtendCombine(SDNode *N,
8247                                     TargetLowering::DAGCombinerInfo &DCI,
8248                                     SelectionDAG &DAG) {
8249   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8250   // we can convert that DUP into another extract_high (of a bigger DUP), which
8251   // helps the backend to decide that an sabdl2 would be useful, saving a real
8252   // extract_high operation.
8253   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8254       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8255        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8256     SDNode *ABDNode = N->getOperand(0).getNode();
8257     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8258     if (!NewABD.getNode())
8259       return SDValue();
8260
8261     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8262                        NewABD);
8263   }
8264
8265   // This is effectively a custom type legalization for AArch64.
8266   //
8267   // Type legalization will split an extend of a small, legal, type to a larger
8268   // illegal type by first splitting the destination type, often creating
8269   // illegal source types, which then get legalized in isel-confusing ways,
8270   // leading to really terrible codegen. E.g.,
8271   //   %result = v8i32 sext v8i8 %value
8272   // becomes
8273   //   %losrc = extract_subreg %value, ...
8274   //   %hisrc = extract_subreg %value, ...
8275   //   %lo = v4i32 sext v4i8 %losrc
8276   //   %hi = v4i32 sext v4i8 %hisrc
8277   // Things go rapidly downhill from there.
8278   //
8279   // For AArch64, the [sz]ext vector instructions can only go up one element
8280   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8281   // take two instructions.
8282   //
8283   // This implies that the most efficient way to do the extend from v8i8
8284   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8285   // the normal splitting to happen for the v8i16->v8i32.
8286
8287   // This is pre-legalization to catch some cases where the default
8288   // type legalization will create ill-tempered code.
8289   if (!DCI.isBeforeLegalizeOps())
8290     return SDValue();
8291
8292   // We're only interested in cleaning things up for non-legal vector types
8293   // here. If both the source and destination are legal, things will just
8294   // work naturally without any fiddling.
8295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8296   EVT ResVT = N->getValueType(0);
8297   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8298     return SDValue();
8299   // If the vector type isn't a simple VT, it's beyond the scope of what
8300   // we're  worried about here. Let legalization do its thing and hope for
8301   // the best.
8302   SDValue Src = N->getOperand(0);
8303   EVT SrcVT = Src->getValueType(0);
8304   if (!ResVT.isSimple() || !SrcVT.isSimple())
8305     return SDValue();
8306
8307   // If the source VT is a 64-bit vector, we can play games and get the
8308   // better results we want.
8309   if (SrcVT.getSizeInBits() != 64)
8310     return SDValue();
8311
8312   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8313   unsigned ElementCount = SrcVT.getVectorNumElements();
8314   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8315   SDLoc DL(N);
8316   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8317
8318   // Now split the rest of the operation into two halves, each with a 64
8319   // bit source.
8320   EVT LoVT, HiVT;
8321   SDValue Lo, Hi;
8322   unsigned NumElements = ResVT.getVectorNumElements();
8323   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8324   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8325                                  ResVT.getVectorElementType(), NumElements / 2);
8326
8327   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8328                                LoVT.getVectorNumElements());
8329   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8330                    DAG.getConstant(0, DL, MVT::i64));
8331   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8332                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8333   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8334   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8335
8336   // Now combine the parts back together so we still have a single result
8337   // like the combiner expects.
8338   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8339 }
8340
8341 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8342 /// value. The load store optimizer pass will merge them to store pair stores.
8343 /// This has better performance than a splat of the scalar followed by a split
8344 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8345 /// followed by an ext.b and two stores.
8346 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8347   SDValue StVal = St->getValue();
8348   EVT VT = StVal.getValueType();
8349
8350   // Don't replace floating point stores, they possibly won't be transformed to
8351   // stp because of the store pair suppress pass.
8352   if (VT.isFloatingPoint())
8353     return SDValue();
8354
8355   // Check for insert vector elements.
8356   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8357     return SDValue();
8358
8359   // We can express a splat as store pair(s) for 2 or 4 elements.
8360   unsigned NumVecElts = VT.getVectorNumElements();
8361   if (NumVecElts != 4 && NumVecElts != 2)
8362     return SDValue();
8363   SDValue SplatVal = StVal.getOperand(1);
8364   unsigned RemainInsertElts = NumVecElts - 1;
8365
8366   // Check that this is a splat.
8367   while (--RemainInsertElts) {
8368     SDValue NextInsertElt = StVal.getOperand(0);
8369     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8370       return SDValue();
8371     if (NextInsertElt.getOperand(1) != SplatVal)
8372       return SDValue();
8373     StVal = NextInsertElt;
8374   }
8375   unsigned OrigAlignment = St->getAlignment();
8376   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8377   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8378
8379   // Create scalar stores. This is at least as good as the code sequence for a
8380   // split unaligned store wich is a dup.s, ext.b, and two stores.
8381   // Most of the time the three stores should be replaced by store pair
8382   // instructions (stp).
8383   SDLoc DL(St);
8384   SDValue BasePtr = St->getBasePtr();
8385   SDValue NewST1 =
8386       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8387                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8388
8389   unsigned Offset = EltOffset;
8390   while (--NumVecElts) {
8391     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8392                                     DAG.getConstant(Offset, DL, MVT::i64));
8393     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8394                           St->getPointerInfo(), St->isVolatile(),
8395                           St->isNonTemporal(), Alignment);
8396     Offset += EltOffset;
8397   }
8398   return NewST1;
8399 }
8400
8401 static SDValue performSTORECombine(SDNode *N,
8402                                    TargetLowering::DAGCombinerInfo &DCI,
8403                                    SelectionDAG &DAG,
8404                                    const AArch64Subtarget *Subtarget) {
8405   if (!DCI.isBeforeLegalize())
8406     return SDValue();
8407
8408   StoreSDNode *S = cast<StoreSDNode>(N);
8409   if (S->isVolatile())
8410     return SDValue();
8411
8412   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8413   // page boundaries. We want to split such stores.
8414   if (!Subtarget->isCyclone())
8415     return SDValue();
8416
8417   // Don't split at Oz.
8418   MachineFunction &MF = DAG.getMachineFunction();
8419   bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
8420   if (IsMinSize)
8421     return SDValue();
8422
8423   SDValue StVal = S->getValue();
8424   EVT VT = StVal.getValueType();
8425
8426   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8427   // those up regresses performance on micro-benchmarks and olden/bh.
8428   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8429     return SDValue();
8430
8431   // Split unaligned 16B stores. They are terrible for performance.
8432   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8433   // extensions can use this to mark that it does not want splitting to happen
8434   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8435   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8436   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8437       S->getAlignment() <= 2)
8438     return SDValue();
8439
8440   // If we get a splat of a scalar convert this vector store to a store of
8441   // scalars. They will be merged into store pairs thereby removing two
8442   // instructions.
8443   SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
8444   if (ReplacedSplat != SDValue())
8445     return ReplacedSplat;
8446
8447   SDLoc DL(S);
8448   unsigned NumElts = VT.getVectorNumElements() / 2;
8449   // Split VT into two.
8450   EVT HalfVT =
8451       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8452   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8453                                    DAG.getConstant(0, DL, MVT::i64));
8454   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8455                                    DAG.getConstant(NumElts, DL, MVT::i64));
8456   SDValue BasePtr = S->getBasePtr();
8457   SDValue NewST1 =
8458       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8459                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8460   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8461                                   DAG.getConstant(8, DL, MVT::i64));
8462   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8463                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8464                       S->getAlignment());
8465 }
8466
8467 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8468 /// post-increment LD1R.
8469 static SDValue performPostLD1Combine(SDNode *N,
8470                                      TargetLowering::DAGCombinerInfo &DCI,
8471                                      bool IsLaneOp) {
8472   if (DCI.isBeforeLegalizeOps())
8473     return SDValue();
8474
8475   SelectionDAG &DAG = DCI.DAG;
8476   EVT VT = N->getValueType(0);
8477
8478   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8479   SDNode *LD = N->getOperand(LoadIdx).getNode();
8480   // If it is not LOAD, can not do such combine.
8481   if (LD->getOpcode() != ISD::LOAD)
8482     return SDValue();
8483
8484   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8485   EVT MemVT = LoadSDN->getMemoryVT();
8486   // Check if memory operand is the same type as the vector element.
8487   if (MemVT != VT.getVectorElementType())
8488     return SDValue();
8489
8490   // Check if there are other uses. If so, do not combine as it will introduce
8491   // an extra load.
8492   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8493        ++UI) {
8494     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8495       continue;
8496     if (*UI != N)
8497       return SDValue();
8498   }
8499
8500   SDValue Addr = LD->getOperand(1);
8501   SDValue Vector = N->getOperand(0);
8502   // Search for a use of the address operand that is an increment.
8503   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8504        Addr.getNode()->use_end(); UI != UE; ++UI) {
8505     SDNode *User = *UI;
8506     if (User->getOpcode() != ISD::ADD
8507         || UI.getUse().getResNo() != Addr.getResNo())
8508       continue;
8509
8510     // Check that the add is independent of the load.  Otherwise, folding it
8511     // would create a cycle.
8512     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8513       continue;
8514     // Also check that add is not used in the vector operand.  This would also
8515     // create a cycle.
8516     if (User->isPredecessorOf(Vector.getNode()))
8517       continue;
8518
8519     // If the increment is a constant, it must match the memory ref size.
8520     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8521     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8522       uint32_t IncVal = CInc->getZExtValue();
8523       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8524       if (IncVal != NumBytes)
8525         continue;
8526       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8527     }
8528
8529     // Finally, check that the vector doesn't depend on the load.
8530     // Again, this would create a cycle.
8531     // The load depending on the vector is fine, as that's the case for the
8532     // LD1*post we'll eventually generate anyway.
8533     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8534       continue;
8535
8536     SmallVector<SDValue, 8> Ops;
8537     Ops.push_back(LD->getOperand(0));  // Chain
8538     if (IsLaneOp) {
8539       Ops.push_back(Vector);           // The vector to be inserted
8540       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8541     }
8542     Ops.push_back(Addr);
8543     Ops.push_back(Inc);
8544
8545     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8546     SDVTList SDTys = DAG.getVTList(Tys);
8547     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8548     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8549                                            MemVT,
8550                                            LoadSDN->getMemOperand());
8551
8552     // Update the uses.
8553     SmallVector<SDValue, 2> NewResults;
8554     NewResults.push_back(SDValue(LD, 0));             // The result of load
8555     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8556     DCI.CombineTo(LD, NewResults);
8557     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8558     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8559
8560     break;
8561   }
8562   return SDValue();
8563 }
8564
8565 /// Target-specific DAG combine function for NEON load/store intrinsics
8566 /// to merge base address updates.
8567 static SDValue performNEONPostLDSTCombine(SDNode *N,
8568                                           TargetLowering::DAGCombinerInfo &DCI,
8569                                           SelectionDAG &DAG) {
8570   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8571     return SDValue();
8572
8573   unsigned AddrOpIdx = N->getNumOperands() - 1;
8574   SDValue Addr = N->getOperand(AddrOpIdx);
8575
8576   // Search for a use of the address operand that is an increment.
8577   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8578        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8579     SDNode *User = *UI;
8580     if (User->getOpcode() != ISD::ADD ||
8581         UI.getUse().getResNo() != Addr.getResNo())
8582       continue;
8583
8584     // Check that the add is independent of the load/store.  Otherwise, folding
8585     // it would create a cycle.
8586     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8587       continue;
8588
8589     // Find the new opcode for the updating load/store.
8590     bool IsStore = false;
8591     bool IsLaneOp = false;
8592     bool IsDupOp = false;
8593     unsigned NewOpc = 0;
8594     unsigned NumVecs = 0;
8595     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8596     switch (IntNo) {
8597     default: llvm_unreachable("unexpected intrinsic for Neon base update");
8598     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
8599       NumVecs = 2; break;
8600     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
8601       NumVecs = 3; break;
8602     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
8603       NumVecs = 4; break;
8604     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
8605       NumVecs = 2; IsStore = true; break;
8606     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
8607       NumVecs = 3; IsStore = true; break;
8608     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
8609       NumVecs = 4; IsStore = true; break;
8610     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
8611       NumVecs = 2; break;
8612     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
8613       NumVecs = 3; break;
8614     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
8615       NumVecs = 4; break;
8616     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
8617       NumVecs = 2; IsStore = true; break;
8618     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
8619       NumVecs = 3; IsStore = true; break;
8620     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
8621       NumVecs = 4; IsStore = true; break;
8622     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
8623       NumVecs = 2; IsDupOp = true; break;
8624     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
8625       NumVecs = 3; IsDupOp = true; break;
8626     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
8627       NumVecs = 4; IsDupOp = true; break;
8628     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
8629       NumVecs = 2; IsLaneOp = true; break;
8630     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
8631       NumVecs = 3; IsLaneOp = true; break;
8632     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
8633       NumVecs = 4; IsLaneOp = true; break;
8634     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
8635       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8636     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
8637       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8638     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
8639       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8640     }
8641
8642     EVT VecTy;
8643     if (IsStore)
8644       VecTy = N->getOperand(2).getValueType();
8645     else
8646       VecTy = N->getValueType(0);
8647
8648     // If the increment is a constant, it must match the memory ref size.
8649     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8650     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8651       uint32_t IncVal = CInc->getZExtValue();
8652       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8653       if (IsLaneOp || IsDupOp)
8654         NumBytes /= VecTy.getVectorNumElements();
8655       if (IncVal != NumBytes)
8656         continue;
8657       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8658     }
8659     SmallVector<SDValue, 8> Ops;
8660     Ops.push_back(N->getOperand(0)); // Incoming chain
8661     // Load lane and store have vector list as input.
8662     if (IsLaneOp || IsStore)
8663       for (unsigned i = 2; i < AddrOpIdx; ++i)
8664         Ops.push_back(N->getOperand(i));
8665     Ops.push_back(Addr); // Base register
8666     Ops.push_back(Inc);
8667
8668     // Return Types.
8669     EVT Tys[6];
8670     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8671     unsigned n;
8672     for (n = 0; n < NumResultVecs; ++n)
8673       Tys[n] = VecTy;
8674     Tys[n++] = MVT::i64;  // Type of write back register
8675     Tys[n] = MVT::Other;  // Type of the chain
8676     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8677
8678     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8679     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8680                                            MemInt->getMemoryVT(),
8681                                            MemInt->getMemOperand());
8682
8683     // Update the uses.
8684     std::vector<SDValue> NewResults;
8685     for (unsigned i = 0; i < NumResultVecs; ++i) {
8686       NewResults.push_back(SDValue(UpdN.getNode(), i));
8687     }
8688     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8689     DCI.CombineTo(N, NewResults);
8690     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8691
8692     break;
8693   }
8694   return SDValue();
8695 }
8696
8697 // Checks to see if the value is the prescribed width and returns information
8698 // about its extension mode.
8699 static
8700 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8701   ExtType = ISD::NON_EXTLOAD;
8702   switch(V.getNode()->getOpcode()) {
8703   default:
8704     return false;
8705   case ISD::LOAD: {
8706     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8707     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8708        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8709       ExtType = LoadNode->getExtensionType();
8710       return true;
8711     }
8712     return false;
8713   }
8714   case ISD::AssertSext: {
8715     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8716     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8717        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8718       ExtType = ISD::SEXTLOAD;
8719       return true;
8720     }
8721     return false;
8722   }
8723   case ISD::AssertZext: {
8724     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8725     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8726        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8727       ExtType = ISD::ZEXTLOAD;
8728       return true;
8729     }
8730     return false;
8731   }
8732   case ISD::Constant:
8733   case ISD::TargetConstant: {
8734     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8735         1LL << (width - 1))
8736       return true;
8737     return false;
8738   }
8739   }
8740
8741   return true;
8742 }
8743
8744 // This function does a whole lot of voodoo to determine if the tests are
8745 // equivalent without and with a mask. Essentially what happens is that given a
8746 // DAG resembling:
8747 //
8748 //  +-------------+ +-------------+ +-------------+ +-------------+
8749 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
8750 //  +-------------+ +-------------+ +-------------+ +-------------+
8751 //           |           |           |               |
8752 //           V           V           |    +----------+
8753 //          +-------------+  +----+  |    |
8754 //          |     ADD     |  |0xff|  |    |
8755 //          +-------------+  +----+  |    |
8756 //                  |           |    |    |
8757 //                  V           V    |    |
8758 //                 +-------------+   |    |
8759 //                 |     AND     |   |    |
8760 //                 +-------------+   |    |
8761 //                      |            |    |
8762 //                      +-----+      |    |
8763 //                            |      |    |
8764 //                            V      V    V
8765 //                           +-------------+
8766 //                           |     CMP     |
8767 //                           +-------------+
8768 //
8769 // The AND node may be safely removed for some combinations of inputs. In
8770 // particular we need to take into account the extension type of the Input,
8771 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8772 // width of the input (this can work for any width inputs, the above graph is
8773 // specific to 8 bits.
8774 //
8775 // The specific equations were worked out by generating output tables for each
8776 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8777 // problem was simplified by working with 4 bit inputs, which means we only
8778 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8779 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8780 // patterns present in both extensions (0,7). For every distinct set of
8781 // AddConstant and CompConstants bit patterns we can consider the masked and
8782 // unmasked versions to be equivalent if the result of this function is true for
8783 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8784 //
8785 //   sub      w8, w0, w1
8786 //   and      w10, w8, #0x0f
8787 //   cmp      w8, w2
8788 //   cset     w9, AArch64CC
8789 //   cmp      w10, w2
8790 //   cset     w11, AArch64CC
8791 //   cmp      w9, w11
8792 //   cset     w0, eq
8793 //   ret
8794 //
8795 // Since the above function shows when the outputs are equivalent it defines
8796 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8797 // would be expensive to run during compiles. The equations below were written
8798 // in a test harness that confirmed they gave equivalent outputs to the above
8799 // for all inputs function, so they can be used determine if the removal is
8800 // legal instead.
8801 //
8802 // isEquivalentMaskless() is the code for testing if the AND can be removed
8803 // factored out of the DAG recognition as the DAG can take several forms.
8804
8805 static
8806 bool isEquivalentMaskless(unsigned CC, unsigned width,
8807                           ISD::LoadExtType ExtType, signed AddConstant,
8808                           signed CompConstant) {
8809   // By being careful about our equations and only writing the in term
8810   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8811   // make them generally applicable to all bit widths.
8812   signed MaxUInt = (1 << width);
8813
8814   // For the purposes of these comparisons sign extending the type is
8815   // equivalent to zero extending the add and displacing it by half the integer
8816   // width. Provided we are careful and make sure our equations are valid over
8817   // the whole range we can just adjust the input and avoid writing equations
8818   // for sign extended inputs.
8819   if (ExtType == ISD::SEXTLOAD)
8820     AddConstant -= (1 << (width-1));
8821
8822   switch(CC) {
8823   case AArch64CC::LE:
8824   case AArch64CC::GT: {
8825     if ((AddConstant == 0) ||
8826         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8827         (AddConstant >= 0 && CompConstant < 0) ||
8828         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8829       return true;
8830   } break;
8831   case AArch64CC::LT:
8832   case AArch64CC::GE: {
8833     if ((AddConstant == 0) ||
8834         (AddConstant >= 0 && CompConstant <= 0) ||
8835         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8836       return true;
8837   } break;
8838   case AArch64CC::HI:
8839   case AArch64CC::LS: {
8840     if ((AddConstant >= 0 && CompConstant < 0) ||
8841        (AddConstant <= 0 && CompConstant >= -1 &&
8842         CompConstant < AddConstant + MaxUInt))
8843       return true;
8844   } break;
8845   case AArch64CC::PL:
8846   case AArch64CC::MI: {
8847     if ((AddConstant == 0) ||
8848         (AddConstant > 0 && CompConstant <= 0) ||
8849         (AddConstant < 0 && CompConstant <= AddConstant))
8850       return true;
8851   } break;
8852   case AArch64CC::LO:
8853   case AArch64CC::HS: {
8854     if ((AddConstant >= 0 && CompConstant <= 0) ||
8855         (AddConstant <= 0 && CompConstant >= 0 &&
8856          CompConstant <= AddConstant + MaxUInt))
8857       return true;
8858   } break;
8859   case AArch64CC::EQ:
8860   case AArch64CC::NE: {
8861     if ((AddConstant > 0 && CompConstant < 0) ||
8862         (AddConstant < 0 && CompConstant >= 0 &&
8863          CompConstant < AddConstant + MaxUInt) ||
8864         (AddConstant >= 0 && CompConstant >= 0 &&
8865          CompConstant >= AddConstant) ||
8866         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8867
8868       return true;
8869   } break;
8870   case AArch64CC::VS:
8871   case AArch64CC::VC:
8872   case AArch64CC::AL:
8873   case AArch64CC::NV:
8874     return true;
8875   case AArch64CC::Invalid:
8876     break;
8877   }
8878
8879   return false;
8880 }
8881
8882 static
8883 SDValue performCONDCombine(SDNode *N,
8884                            TargetLowering::DAGCombinerInfo &DCI,
8885                            SelectionDAG &DAG, unsigned CCIndex,
8886                            unsigned CmpIndex) {
8887   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8888   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8889   unsigned CondOpcode = SubsNode->getOpcode();
8890
8891   if (CondOpcode != AArch64ISD::SUBS)
8892     return SDValue();
8893
8894   // There is a SUBS feeding this condition. Is it fed by a mask we can
8895   // use?
8896
8897   SDNode *AndNode = SubsNode->getOperand(0).getNode();
8898   unsigned MaskBits = 0;
8899
8900   if (AndNode->getOpcode() != ISD::AND)
8901     return SDValue();
8902
8903   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8904     uint32_t CNV = CN->getZExtValue();
8905     if (CNV == 255)
8906       MaskBits = 8;
8907     else if (CNV == 65535)
8908       MaskBits = 16;
8909   }
8910
8911   if (!MaskBits)
8912     return SDValue();
8913
8914   SDValue AddValue = AndNode->getOperand(0);
8915
8916   if (AddValue.getOpcode() != ISD::ADD)
8917     return SDValue();
8918
8919   // The basic dag structure is correct, grab the inputs and validate them.
8920
8921   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8922   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8923   SDValue SubsInputValue = SubsNode->getOperand(1);
8924
8925   // The mask is present and the provenance of all the values is a smaller type,
8926   // lets see if the mask is superfluous.
8927
8928   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8929       !isa<ConstantSDNode>(SubsInputValue.getNode()))
8930     return SDValue();
8931
8932   ISD::LoadExtType ExtType;
8933
8934   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8935       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8936       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8937     return SDValue();
8938
8939   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8940                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8941                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8942     return SDValue();
8943
8944   // The AND is not necessary, remove it.
8945
8946   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8947                                SubsNode->getValueType(1));
8948   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8949
8950   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8951   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8952
8953   return SDValue(N, 0);
8954 }
8955
8956 // Optimize compare with zero and branch.
8957 static SDValue performBRCONDCombine(SDNode *N,
8958                                     TargetLowering::DAGCombinerInfo &DCI,
8959                                     SelectionDAG &DAG) {
8960   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8961   if (NV.getNode())
8962     N = NV.getNode();
8963   SDValue Chain = N->getOperand(0);
8964   SDValue Dest = N->getOperand(1);
8965   SDValue CCVal = N->getOperand(2);
8966   SDValue Cmp = N->getOperand(3);
8967
8968   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8969   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8970   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8971     return SDValue();
8972
8973   unsigned CmpOpc = Cmp.getOpcode();
8974   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8975     return SDValue();
8976
8977   // Only attempt folding if there is only one use of the flag and no use of the
8978   // value.
8979   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8980     return SDValue();
8981
8982   SDValue LHS = Cmp.getOperand(0);
8983   SDValue RHS = Cmp.getOperand(1);
8984
8985   assert(LHS.getValueType() == RHS.getValueType() &&
8986          "Expected the value type to be the same for both operands!");
8987   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8988     return SDValue();
8989
8990   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8991     std::swap(LHS, RHS);
8992
8993   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8994     return SDValue();
8995
8996   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8997       LHS.getOpcode() == ISD::SRL)
8998     return SDValue();
8999
9000   // Fold the compare into the branch instruction.
9001   SDValue BR;
9002   if (CC == AArch64CC::EQ)
9003     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9004   else
9005     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9006
9007   // Do not add new nodes to DAG combiner worklist.
9008   DCI.CombineTo(N, BR, false);
9009
9010   return SDValue();
9011 }
9012
9013 // vselect (v1i1 setcc) ->
9014 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9015 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9016 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9017 // such VSELECT.
9018 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9019   SDValue N0 = N->getOperand(0);
9020   EVT CCVT = N0.getValueType();
9021
9022   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9023       CCVT.getVectorElementType() != MVT::i1)
9024     return SDValue();
9025
9026   EVT ResVT = N->getValueType(0);
9027   EVT CmpVT = N0.getOperand(0).getValueType();
9028   // Only combine when the result type is of the same size as the compared
9029   // operands.
9030   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9031     return SDValue();
9032
9033   SDValue IfTrue = N->getOperand(1);
9034   SDValue IfFalse = N->getOperand(2);
9035   SDValue SetCC =
9036       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9037                    N0.getOperand(0), N0.getOperand(1),
9038                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9039   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9040                      IfTrue, IfFalse);
9041 }
9042
9043 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9044 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9045 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9046 /// with a vector one followed by a DUP shuffle on the result.
9047 static SDValue performSelectCombine(SDNode *N,
9048                                     TargetLowering::DAGCombinerInfo &DCI) {
9049   SelectionDAG &DAG = DCI.DAG;
9050   SDValue N0 = N->getOperand(0);
9051   EVT ResVT = N->getValueType(0);
9052
9053   if (N0.getOpcode() != ISD::SETCC)
9054     return SDValue();
9055
9056   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9057   // scalar SetCCResultType. We also don't expect vectors, because we assume
9058   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9059   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9060          "Scalar-SETCC feeding SELECT has unexpected result type!");
9061
9062   // If NumMaskElts == 0, the comparison is larger than select result. The
9063   // largest real NEON comparison is 64-bits per lane, which means the result is
9064   // at most 32-bits and an illegal vector. Just bail out for now.
9065   EVT SrcVT = N0.getOperand(0).getValueType();
9066
9067   // Don't try to do this optimization when the setcc itself has i1 operands.
9068   // There are no legal vectors of i1, so this would be pointless.
9069   if (SrcVT == MVT::i1)
9070     return SDValue();
9071
9072   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9073   if (!ResVT.isVector() || NumMaskElts == 0)
9074     return SDValue();
9075
9076   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9077   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9078
9079   // Also bail out if the vector CCVT isn't the same size as ResVT.
9080   // This can happen if the SETCC operand size doesn't divide the ResVT size
9081   // (e.g., f64 vs v3f32).
9082   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9083     return SDValue();
9084
9085   // Make sure we didn't create illegal types, if we're not supposed to.
9086   assert(DCI.isBeforeLegalize() ||
9087          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9088
9089   // First perform a vector comparison, where lane 0 is the one we're interested
9090   // in.
9091   SDLoc DL(N0);
9092   SDValue LHS =
9093       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9094   SDValue RHS =
9095       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9096   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9097
9098   // Now duplicate the comparison mask we want across all other lanes.
9099   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9100   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9101   Mask = DAG.getNode(ISD::BITCAST, DL,
9102                      ResVT.changeVectorElementTypeToInteger(), Mask);
9103
9104   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9105 }
9106
9107 /// performSelectCCCombine - Target-specific DAG combining for ISD::SELECT_CC
9108 /// to match FMIN/FMAX patterns.
9109 static SDValue performSelectCCCombine(SDNode *N, SelectionDAG &DAG) {
9110   // Try to use FMIN/FMAX instructions for FP selects like "x < y ? x : y".
9111   // Unless the NoNaNsFPMath option is set, be careful about NaNs:
9112   // vmax/vmin return NaN if either operand is a NaN;
9113   // only do the transformation when it matches that behavior.
9114
9115   SDValue CondLHS = N->getOperand(0);
9116   SDValue CondRHS = N->getOperand(1);
9117   SDValue LHS = N->getOperand(2);
9118   SDValue RHS = N->getOperand(3);
9119   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9120
9121   unsigned Opcode;
9122   bool IsReversed;
9123   if (selectCCOpsAreFMaxCompatible(CondLHS, LHS) &&
9124       selectCCOpsAreFMaxCompatible(CondRHS, RHS)) {
9125     IsReversed = false; // x CC y ? x : y
9126   } else if (selectCCOpsAreFMaxCompatible(CondRHS, LHS) &&
9127              selectCCOpsAreFMaxCompatible(CondLHS, RHS)) {
9128     IsReversed = true ; // x CC y ? y : x
9129   } else {
9130     return SDValue();
9131   }
9132
9133   bool IsUnordered = false, IsOrEqual;
9134   switch (CC) {
9135   default:
9136     return SDValue();
9137   case ISD::SETULT:
9138   case ISD::SETULE:
9139     IsUnordered = true;
9140   case ISD::SETOLT:
9141   case ISD::SETOLE:
9142   case ISD::SETLT:
9143   case ISD::SETLE:
9144     IsOrEqual = (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE);
9145     Opcode = IsReversed ? AArch64ISD::FMAX : AArch64ISD::FMIN;
9146     break;
9147
9148   case ISD::SETUGT:
9149   case ISD::SETUGE:
9150     IsUnordered = true;
9151   case ISD::SETOGT:
9152   case ISD::SETOGE:
9153   case ISD::SETGT:
9154   case ISD::SETGE:
9155     IsOrEqual = (CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE);
9156     Opcode = IsReversed ? AArch64ISD::FMIN : AArch64ISD::FMAX;
9157     break;
9158   }
9159
9160   // If LHS is NaN, an ordered comparison will be false and the result will be
9161   // the RHS, but FMIN(NaN, RHS) = FMAX(NaN, RHS) = NaN. Avoid this by checking
9162   // that LHS != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9163   if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9164     return SDValue();
9165
9166   // For xxx-or-equal comparisons, "+0 <= -0" and "-0 >= +0" will both be true,
9167   // but FMIN will return -0, and FMAX will return +0. So FMIN/FMAX can only be
9168   // used for unsafe math or if one of the operands is known to be nonzero.
9169   if (IsOrEqual && !DAG.getTarget().Options.UnsafeFPMath &&
9170       !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9171     return SDValue();
9172
9173   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9174 }
9175
9176 /// Get rid of unnecessary NVCASTs (that don't change the type).
9177 static SDValue performNVCASTCombine(SDNode *N) {
9178   if (N->getValueType(0) == N->getOperand(0).getValueType())
9179     return N->getOperand(0);
9180
9181   return SDValue();
9182 }
9183
9184 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9185                                                  DAGCombinerInfo &DCI) const {
9186   SelectionDAG &DAG = DCI.DAG;
9187   switch (N->getOpcode()) {
9188   default:
9189     break;
9190   case ISD::ADD:
9191   case ISD::SUB:
9192     return performAddSubLongCombine(N, DCI, DAG);
9193   case ISD::XOR:
9194     return performXorCombine(N, DAG, DCI, Subtarget);
9195   case ISD::MUL:
9196     return performMulCombine(N, DAG, DCI, Subtarget);
9197   case ISD::SINT_TO_FP:
9198   case ISD::UINT_TO_FP:
9199     return performIntToFpCombine(N, DAG, Subtarget);
9200   case ISD::OR:
9201     return performORCombine(N, DCI, Subtarget);
9202   case ISD::INTRINSIC_WO_CHAIN:
9203     return performIntrinsicCombine(N, DCI, Subtarget);
9204   case ISD::ANY_EXTEND:
9205   case ISD::ZERO_EXTEND:
9206   case ISD::SIGN_EXTEND:
9207     return performExtendCombine(N, DCI, DAG);
9208   case ISD::BITCAST:
9209     return performBitcastCombine(N, DCI, DAG);
9210   case ISD::CONCAT_VECTORS:
9211     return performConcatVectorsCombine(N, DCI, DAG);
9212   case ISD::SELECT:
9213     return performSelectCombine(N, DCI);
9214   case ISD::VSELECT:
9215     return performVSelectCombine(N, DCI.DAG);
9216   case ISD::SELECT_CC:
9217     return performSelectCCCombine(N, DCI.DAG);
9218   case ISD::STORE:
9219     return performSTORECombine(N, DCI, DAG, Subtarget);
9220   case AArch64ISD::BRCOND:
9221     return performBRCONDCombine(N, DCI, DAG);
9222   case AArch64ISD::CSEL:
9223     return performCONDCombine(N, DCI, DAG, 2, 3);
9224   case AArch64ISD::DUP:
9225     return performPostLD1Combine(N, DCI, false);
9226   case AArch64ISD::NVCAST:
9227     return performNVCASTCombine(N);
9228   case ISD::INSERT_VECTOR_ELT:
9229     return performPostLD1Combine(N, DCI, true);
9230   case ISD::INTRINSIC_VOID:
9231   case ISD::INTRINSIC_W_CHAIN:
9232     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9233     case Intrinsic::aarch64_neon_ld2:
9234     case Intrinsic::aarch64_neon_ld3:
9235     case Intrinsic::aarch64_neon_ld4:
9236     case Intrinsic::aarch64_neon_ld1x2:
9237     case Intrinsic::aarch64_neon_ld1x3:
9238     case Intrinsic::aarch64_neon_ld1x4:
9239     case Intrinsic::aarch64_neon_ld2lane:
9240     case Intrinsic::aarch64_neon_ld3lane:
9241     case Intrinsic::aarch64_neon_ld4lane:
9242     case Intrinsic::aarch64_neon_ld2r:
9243     case Intrinsic::aarch64_neon_ld3r:
9244     case Intrinsic::aarch64_neon_ld4r:
9245     case Intrinsic::aarch64_neon_st2:
9246     case Intrinsic::aarch64_neon_st3:
9247     case Intrinsic::aarch64_neon_st4:
9248     case Intrinsic::aarch64_neon_st1x2:
9249     case Intrinsic::aarch64_neon_st1x3:
9250     case Intrinsic::aarch64_neon_st1x4:
9251     case Intrinsic::aarch64_neon_st2lane:
9252     case Intrinsic::aarch64_neon_st3lane:
9253     case Intrinsic::aarch64_neon_st4lane:
9254       return performNEONPostLDSTCombine(N, DCI, DAG);
9255     default:
9256       break;
9257     }
9258   }
9259   return SDValue();
9260 }
9261
9262 // Check if the return value is used as only a return value, as otherwise
9263 // we can't perform a tail-call. In particular, we need to check for
9264 // target ISD nodes that are returns and any other "odd" constructs
9265 // that the generic analysis code won't necessarily catch.
9266 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9267                                                SDValue &Chain) const {
9268   if (N->getNumValues() != 1)
9269     return false;
9270   if (!N->hasNUsesOfValue(1, 0))
9271     return false;
9272
9273   SDValue TCChain = Chain;
9274   SDNode *Copy = *N->use_begin();
9275   if (Copy->getOpcode() == ISD::CopyToReg) {
9276     // If the copy has a glue operand, we conservatively assume it isn't safe to
9277     // perform a tail call.
9278     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9279         MVT::Glue)
9280       return false;
9281     TCChain = Copy->getOperand(0);
9282   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9283     return false;
9284
9285   bool HasRet = false;
9286   for (SDNode *Node : Copy->uses()) {
9287     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9288       return false;
9289     HasRet = true;
9290   }
9291
9292   if (!HasRet)
9293     return false;
9294
9295   Chain = TCChain;
9296   return true;
9297 }
9298
9299 // Return whether the an instruction can potentially be optimized to a tail
9300 // call. This will cause the optimizers to attempt to move, or duplicate,
9301 // return instructions to help enable tail call optimizations for this
9302 // instruction.
9303 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9304   if (!CI->isTailCall())
9305     return false;
9306
9307   return true;
9308 }
9309
9310 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9311                                                    SDValue &Offset,
9312                                                    ISD::MemIndexedMode &AM,
9313                                                    bool &IsInc,
9314                                                    SelectionDAG &DAG) const {
9315   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9316     return false;
9317
9318   Base = Op->getOperand(0);
9319   // All of the indexed addressing mode instructions take a signed
9320   // 9 bit immediate offset.
9321   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9322     int64_t RHSC = (int64_t)RHS->getZExtValue();
9323     if (RHSC >= 256 || RHSC <= -256)
9324       return false;
9325     IsInc = (Op->getOpcode() == ISD::ADD);
9326     Offset = Op->getOperand(1);
9327     return true;
9328   }
9329   return false;
9330 }
9331
9332 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9333                                                       SDValue &Offset,
9334                                                       ISD::MemIndexedMode &AM,
9335                                                       SelectionDAG &DAG) const {
9336   EVT VT;
9337   SDValue Ptr;
9338   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9339     VT = LD->getMemoryVT();
9340     Ptr = LD->getBasePtr();
9341   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9342     VT = ST->getMemoryVT();
9343     Ptr = ST->getBasePtr();
9344   } else
9345     return false;
9346
9347   bool IsInc;
9348   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9349     return false;
9350   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9351   return true;
9352 }
9353
9354 bool AArch64TargetLowering::getPostIndexedAddressParts(
9355     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9356     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9357   EVT VT;
9358   SDValue Ptr;
9359   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9360     VT = LD->getMemoryVT();
9361     Ptr = LD->getBasePtr();
9362   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9363     VT = ST->getMemoryVT();
9364     Ptr = ST->getBasePtr();
9365   } else
9366     return false;
9367
9368   bool IsInc;
9369   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9370     return false;
9371   // Post-indexing updates the base, so it's not a valid transform
9372   // if that's not the same as the load's pointer.
9373   if (Ptr != Base)
9374     return false;
9375   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9376   return true;
9377 }
9378
9379 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9380                                   SelectionDAG &DAG) {
9381   SDLoc DL(N);
9382   SDValue Op = N->getOperand(0);
9383
9384   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9385     return;
9386
9387   Op = SDValue(
9388       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9389                          DAG.getUNDEF(MVT::i32), Op,
9390                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9391       0);
9392   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9393   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9394 }
9395
9396 void AArch64TargetLowering::ReplaceNodeResults(
9397     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9398   switch (N->getOpcode()) {
9399   default:
9400     llvm_unreachable("Don't know how to custom expand this");
9401   case ISD::BITCAST:
9402     ReplaceBITCASTResults(N, Results, DAG);
9403     return;
9404   case ISD::FP_TO_UINT:
9405   case ISD::FP_TO_SINT:
9406     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9407     // Let normal code take care of it by not adding anything to Results.
9408     return;
9409   }
9410 }
9411
9412 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9413   return true;
9414 }
9415
9416 bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
9417   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9418   // reciprocal if there are three or more FDIVs.
9419   return NumUsers > 2;
9420 }
9421
9422 TargetLoweringBase::LegalizeTypeAction
9423 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9424   MVT SVT = VT.getSimpleVT();
9425   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9426   // v4i16, v2i32 instead of to promote.
9427   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9428       || SVT == MVT::v1f32)
9429     return TypeWidenVector;
9430
9431   return TargetLoweringBase::getPreferredVectorAction(VT);
9432 }
9433
9434 // Loads and stores less than 128-bits are already atomic; ones above that
9435 // are doomed anyway, so defer to the default libcall and blame the OS when
9436 // things go wrong.
9437 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9438   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9439   return Size == 128;
9440 }
9441
9442 // Loads and stores less than 128-bits are already atomic; ones above that
9443 // are doomed anyway, so defer to the default libcall and blame the OS when
9444 // things go wrong.
9445 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9446   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9447   return Size == 128;
9448 }
9449
9450 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9451 TargetLoweringBase::AtomicRMWExpansionKind
9452 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9453   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9454   return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9455                      : AtomicRMWExpansionKind::None;
9456 }
9457
9458 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9459   return true;
9460 }
9461
9462 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9463                                              AtomicOrdering Ord) const {
9464   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9465   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9466   bool IsAcquire = isAtLeastAcquire(Ord);
9467
9468   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9469   // intrinsic must return {i64, i64} and we have to recombine them into a
9470   // single i128 here.
9471   if (ValTy->getPrimitiveSizeInBits() == 128) {
9472     Intrinsic::ID Int =
9473         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9474     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9475
9476     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9477     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9478
9479     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9480     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9481     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9482     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9483     return Builder.CreateOr(
9484         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9485   }
9486
9487   Type *Tys[] = { Addr->getType() };
9488   Intrinsic::ID Int =
9489       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9490   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9491
9492   return Builder.CreateTruncOrBitCast(
9493       Builder.CreateCall(Ldxr, Addr),
9494       cast<PointerType>(Addr->getType())->getElementType());
9495 }
9496
9497 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9498                                                    Value *Val, Value *Addr,
9499                                                    AtomicOrdering Ord) const {
9500   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9501   bool IsRelease = isAtLeastRelease(Ord);
9502
9503   // Since the intrinsics must have legal type, the i128 intrinsics take two
9504   // parameters: "i64, i64". We must marshal Val into the appropriate form
9505   // before the call.
9506   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9507     Intrinsic::ID Int =
9508         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9509     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9510     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9511
9512     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9513     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9514     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9515     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9516   }
9517
9518   Intrinsic::ID Int =
9519       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9520   Type *Tys[] = { Addr->getType() };
9521   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9522
9523   return Builder.CreateCall(Stxr,
9524                             {Builder.CreateZExtOrBitCast(
9525                                  Val, Stxr->getFunctionType()->getParamType(0)),
9526                              Addr});
9527 }
9528
9529 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9530     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9531   return Ty->isArrayTy();
9532 }
9533
9534 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9535                                                             EVT) const {
9536   return false;
9537 }