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