[AArch64] Custom lower concat_vector patterns with v4i16, v4i32, v8i8, v8i16, v16i8...
[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 defines the interfaces that AArch64 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "aarch64-isel"
16 #include "AArch64.h"
17 #include "AArch64ISelLowering.h"
18 #include "AArch64MachineFunctionInfo.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/CodeGen/Analysis.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/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29
30 using namespace llvm;
31
32 static TargetLoweringObjectFile *createTLOF(AArch64TargetMachine &TM) {
33   assert (TM.getSubtarget<AArch64Subtarget>().isTargetELF() &&
34           "unknown subtarget type");
35   return new AArch64ElfTargetObjectFile();
36 }
37
38 AArch64TargetLowering::AArch64TargetLowering(AArch64TargetMachine &TM)
39   : TargetLowering(TM, createTLOF(TM)), Itins(TM.getInstrItineraryData()) {
40
41   const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
42
43   // SIMD compares set the entire lane's bits to 1
44   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
45
46   // Scalar register <-> type mapping
47   addRegisterClass(MVT::i32, &AArch64::GPR32RegClass);
48   addRegisterClass(MVT::i64, &AArch64::GPR64RegClass);
49
50   if (Subtarget->hasFPARMv8()) {
51     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
52     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
53     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
54     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
55   }
56
57   if (Subtarget->hasNEON()) {
58     // And the vectors
59     addRegisterClass(MVT::v1i8,  &AArch64::FPR8RegClass);
60     addRegisterClass(MVT::v1i16, &AArch64::FPR16RegClass);
61     addRegisterClass(MVT::v1i32, &AArch64::FPR32RegClass);
62     addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
63     addRegisterClass(MVT::v1f64, &AArch64::FPR64RegClass);
64     addRegisterClass(MVT::v8i8,  &AArch64::FPR64RegClass);
65     addRegisterClass(MVT::v4i16, &AArch64::FPR64RegClass);
66     addRegisterClass(MVT::v2i32, &AArch64::FPR64RegClass);
67     addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
68     addRegisterClass(MVT::v2f32, &AArch64::FPR64RegClass);
69     addRegisterClass(MVT::v16i8, &AArch64::FPR128RegClass);
70     addRegisterClass(MVT::v8i16, &AArch64::FPR128RegClass);
71     addRegisterClass(MVT::v4i32, &AArch64::FPR128RegClass);
72     addRegisterClass(MVT::v2i64, &AArch64::FPR128RegClass);
73     addRegisterClass(MVT::v4f32, &AArch64::FPR128RegClass);
74     addRegisterClass(MVT::v2f64, &AArch64::FPR128RegClass);
75   }
76
77   computeRegisterProperties();
78
79   // We combine OR nodes for bitfield and NEON BSL operations.
80   setTargetDAGCombine(ISD::OR);
81
82   setTargetDAGCombine(ISD::AND);
83   setTargetDAGCombine(ISD::SRA);
84   setTargetDAGCombine(ISD::SRL);
85   setTargetDAGCombine(ISD::SHL);
86
87   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
88   setTargetDAGCombine(ISD::INTRINSIC_VOID);
89   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
90
91   // AArch64 does not have i1 loads, or much of anything for i1 really.
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
94   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
95
96   setStackPointerRegisterToSaveRestore(AArch64::XSP);
97   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
98   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
99   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
100
101   // We'll lower globals to wrappers for selection.
102   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
104
105   // A64 instructions have the comparison predicate attached to the user of the
106   // result, but having a separate comparison is valuable for matching.
107   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
108   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
109   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
110   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
111
112   setOperationAction(ISD::SELECT, MVT::i32, Custom);
113   setOperationAction(ISD::SELECT, MVT::i64, Custom);
114   setOperationAction(ISD::SELECT, MVT::f32, Custom);
115   setOperationAction(ISD::SELECT, MVT::f64, Custom);
116
117   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
118   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
119   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
120   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
121
122   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
123
124   setOperationAction(ISD::SETCC, MVT::i32, Custom);
125   setOperationAction(ISD::SETCC, MVT::i64, Custom);
126   setOperationAction(ISD::SETCC, MVT::f32, Custom);
127   setOperationAction(ISD::SETCC, MVT::f64, Custom);
128
129   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
130   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
132
133   setOperationAction(ISD::VASTART, MVT::Other, Custom);
134   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
135   setOperationAction(ISD::VAEND, MVT::Other, Expand);
136   setOperationAction(ISD::VAARG, MVT::Other, Expand);
137
138   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
139   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
140
141   setOperationAction(ISD::ROTL, MVT::i32, Expand);
142   setOperationAction(ISD::ROTL, MVT::i64, Expand);
143
144   setOperationAction(ISD::UREM, MVT::i32, Expand);
145   setOperationAction(ISD::UREM, MVT::i64, Expand);
146   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
147   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
148
149   setOperationAction(ISD::SREM, MVT::i32, Expand);
150   setOperationAction(ISD::SREM, MVT::i64, Expand);
151   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
152   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
153
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
157   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
158
159   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
160   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
161
162   // Legal floating-point operations.
163   setOperationAction(ISD::FABS, MVT::f32, Legal);
164   setOperationAction(ISD::FABS, MVT::f64, Legal);
165
166   setOperationAction(ISD::FCEIL, MVT::f32, Legal);
167   setOperationAction(ISD::FCEIL, MVT::f64, Legal);
168
169   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
170   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
171
172   setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
173   setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
174
175   setOperationAction(ISD::FNEG, MVT::f32, Legal);
176   setOperationAction(ISD::FNEG, MVT::f64, Legal);
177
178   setOperationAction(ISD::FRINT, MVT::f32, Legal);
179   setOperationAction(ISD::FRINT, MVT::f64, Legal);
180
181   setOperationAction(ISD::FSQRT, MVT::f32, Legal);
182   setOperationAction(ISD::FSQRT, MVT::f64, Legal);
183
184   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
185   setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
186
187   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
188   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
189   setOperationAction(ISD::ConstantFP, MVT::f128, Legal);
190
191   // Illegal floating-point operations.
192   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
193   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194
195   setOperationAction(ISD::FCOS, MVT::f32, Expand);
196   setOperationAction(ISD::FCOS, MVT::f64, Expand);
197
198   setOperationAction(ISD::FEXP, MVT::f32, Expand);
199   setOperationAction(ISD::FEXP, MVT::f64, Expand);
200
201   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
202   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
203
204   setOperationAction(ISD::FLOG, MVT::f32, Expand);
205   setOperationAction(ISD::FLOG, MVT::f64, Expand);
206
207   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
208   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
209
210   setOperationAction(ISD::FLOG10, MVT::f32, Expand);
211   setOperationAction(ISD::FLOG10, MVT::f64, Expand);
212
213   setOperationAction(ISD::FPOW, MVT::f32, Expand);
214   setOperationAction(ISD::FPOW, MVT::f64, Expand);
215
216   setOperationAction(ISD::FPOWI, MVT::f32, Expand);
217   setOperationAction(ISD::FPOWI, MVT::f64, Expand);
218
219   setOperationAction(ISD::FREM, MVT::f32, Expand);
220   setOperationAction(ISD::FREM, MVT::f64, Expand);
221
222   setOperationAction(ISD::FSIN, MVT::f32, Expand);
223   setOperationAction(ISD::FSIN, MVT::f64, Expand);
224
225   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
226   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227
228   // Virtually no operation on f128 is legal, but LLVM can't expand them when
229   // there's a valid register class, so we need custom operations in most cases.
230   setOperationAction(ISD::FABS,       MVT::f128, Expand);
231   setOperationAction(ISD::FADD,       MVT::f128, Custom);
232   setOperationAction(ISD::FCOPYSIGN,  MVT::f128, Expand);
233   setOperationAction(ISD::FCOS,       MVT::f128, Expand);
234   setOperationAction(ISD::FDIV,       MVT::f128, Custom);
235   setOperationAction(ISD::FMA,        MVT::f128, Expand);
236   setOperationAction(ISD::FMUL,       MVT::f128, Custom);
237   setOperationAction(ISD::FNEG,       MVT::f128, Expand);
238   setOperationAction(ISD::FP_EXTEND,  MVT::f128, Expand);
239   setOperationAction(ISD::FP_ROUND,   MVT::f128, Expand);
240   setOperationAction(ISD::FPOW,       MVT::f128, Expand);
241   setOperationAction(ISD::FREM,       MVT::f128, Expand);
242   setOperationAction(ISD::FRINT,      MVT::f128, Expand);
243   setOperationAction(ISD::FSIN,       MVT::f128, Expand);
244   setOperationAction(ISD::FSINCOS,    MVT::f128, Expand);
245   setOperationAction(ISD::FSQRT,      MVT::f128, Expand);
246   setOperationAction(ISD::FSUB,       MVT::f128, Custom);
247   setOperationAction(ISD::FTRUNC,     MVT::f128, Expand);
248   setOperationAction(ISD::SETCC,      MVT::f128, Custom);
249   setOperationAction(ISD::BR_CC,      MVT::f128, Custom);
250   setOperationAction(ISD::SELECT,     MVT::f128, Expand);
251   setOperationAction(ISD::SELECT_CC,  MVT::f128, Custom);
252   setOperationAction(ISD::FP_EXTEND,  MVT::f128, Custom);
253
254   // Lowering for many of the conversions is actually specified by the non-f128
255   // type. The LowerXXX function will be trivial when f128 isn't involved.
256   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
257   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
258   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
259   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
260   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
261   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
262   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
263   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
264   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
265   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
266   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
267   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
268   setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
269   setOperationAction(ISD::FP_ROUND,  MVT::f64, Custom);
270
271   // This prevents LLVM trying to compress double constants into a floating
272   // constant-pool entry and trying to load from there. It's of doubtful benefit
273   // for A64: we'd need LDR followed by FCVT, I believe.
274   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
275   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
276   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
277
278   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
279   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
280   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
281   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
282   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
283   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
284
285   setExceptionPointerRegister(AArch64::X0);
286   setExceptionSelectorRegister(AArch64::X1);
287
288   if (Subtarget->hasNEON()) {
289     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Expand);
290     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Expand);
291     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Expand);
292     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v1i64, Expand);
293     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v16i8, Expand);
294     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Expand);
295     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Expand);
296     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Expand);
297
298     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i8, Custom);
299     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
300     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
301     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i16, Custom);
302     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
303     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
304     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i32, Custom);
305     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
306     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
307     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
308     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
309     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
310     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
311     setOperationAction(ISD::BUILD_VECTOR, MVT::v1f64, Custom);
312     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
313
314     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
315     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
316     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
317     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
318     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
319     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
320     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
321     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
322     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
323     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
324     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
325     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
326
327     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i32, Legal);
328     setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Legal);
329     setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
330     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
331     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
332     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
333     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
334
335     setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i8, Custom);
336     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i16, Custom);
337     setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
338     setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
339     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
340
341     setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
342     setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
343     setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
344     setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
345     setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
346     setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
347     setOperationAction(ISD::SETCC, MVT::v1i64, Custom);
348     setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
349     setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
350     setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
351     setOperationAction(ISD::SETCC, MVT::v1f64, Custom);
352     setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
353
354     setOperationAction(ISD::FFLOOR, MVT::v2f32, Legal);
355     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
356     setOperationAction(ISD::FFLOOR, MVT::v1f64, Legal);
357     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
358
359     setOperationAction(ISD::FCEIL, MVT::v2f32, Legal);
360     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
361     setOperationAction(ISD::FCEIL, MVT::v1f64, Legal);
362     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
363
364     setOperationAction(ISD::FTRUNC, MVT::v2f32, Legal);
365     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
366     setOperationAction(ISD::FTRUNC, MVT::v1f64, Legal);
367     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
368
369     setOperationAction(ISD::FRINT, MVT::v2f32, Legal);
370     setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
371     setOperationAction(ISD::FRINT, MVT::v1f64, Legal);
372     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
373
374     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Legal);
375     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
376     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Legal);
377     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
378
379     setOperationAction(ISD::FROUND, MVT::v2f32, Legal);
380     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
381     setOperationAction(ISD::FROUND, MVT::v1f64, Legal);
382     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
383
384     setOperationAction(ISD::SINT_TO_FP, MVT::v1i8, Custom);
385     setOperationAction(ISD::SINT_TO_FP, MVT::v1i16, Custom);
386     setOperationAction(ISD::SINT_TO_FP, MVT::v1i32, Custom);
387     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
388     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
389     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
390
391     setOperationAction(ISD::UINT_TO_FP, MVT::v1i8, Custom);
392     setOperationAction(ISD::UINT_TO_FP, MVT::v1i16, Custom);
393     setOperationAction(ISD::UINT_TO_FP, MVT::v1i32, Custom);
394     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
395     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
396     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
397
398     setOperationAction(ISD::FP_TO_SINT, MVT::v1i8, Custom);
399     setOperationAction(ISD::FP_TO_SINT, MVT::v1i16, Custom);
400     setOperationAction(ISD::FP_TO_SINT, MVT::v1i32, Custom);
401     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
402     setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
403     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Custom);
404
405     setOperationAction(ISD::FP_TO_UINT, MVT::v1i8, Custom);
406     setOperationAction(ISD::FP_TO_UINT, MVT::v1i16, Custom);
407     setOperationAction(ISD::FP_TO_UINT, MVT::v1i32, Custom);
408     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
409     setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
410     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Custom);
411
412     // Neon does not support vector divide/remainder operations except
413     // floating-point divide.
414     setOperationAction(ISD::SDIV, MVT::v1i8, Expand);
415     setOperationAction(ISD::SDIV, MVT::v8i8, Expand);
416     setOperationAction(ISD::SDIV, MVT::v16i8, Expand);
417     setOperationAction(ISD::SDIV, MVT::v1i16, Expand);
418     setOperationAction(ISD::SDIV, MVT::v4i16, Expand);
419     setOperationAction(ISD::SDIV, MVT::v8i16, Expand);
420     setOperationAction(ISD::SDIV, MVT::v1i32, Expand);
421     setOperationAction(ISD::SDIV, MVT::v2i32, Expand);
422     setOperationAction(ISD::SDIV, MVT::v4i32, Expand);
423     setOperationAction(ISD::SDIV, MVT::v1i64, Expand);
424     setOperationAction(ISD::SDIV, MVT::v2i64, Expand);
425
426     setOperationAction(ISD::UDIV, MVT::v1i8, Expand);
427     setOperationAction(ISD::UDIV, MVT::v8i8, Expand);
428     setOperationAction(ISD::UDIV, MVT::v16i8, Expand);
429     setOperationAction(ISD::UDIV, MVT::v1i16, Expand);
430     setOperationAction(ISD::UDIV, MVT::v4i16, Expand);
431     setOperationAction(ISD::UDIV, MVT::v8i16, Expand);
432     setOperationAction(ISD::UDIV, MVT::v1i32, Expand);
433     setOperationAction(ISD::UDIV, MVT::v2i32, Expand);
434     setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
435     setOperationAction(ISD::UDIV, MVT::v1i64, Expand);
436     setOperationAction(ISD::UDIV, MVT::v2i64, Expand);
437
438     setOperationAction(ISD::SREM, MVT::v1i8, Expand);
439     setOperationAction(ISD::SREM, MVT::v8i8, Expand);
440     setOperationAction(ISD::SREM, MVT::v16i8, Expand);
441     setOperationAction(ISD::SREM, MVT::v1i16, Expand);
442     setOperationAction(ISD::SREM, MVT::v4i16, Expand);
443     setOperationAction(ISD::SREM, MVT::v8i16, Expand);
444     setOperationAction(ISD::SREM, MVT::v1i32, Expand);
445     setOperationAction(ISD::SREM, MVT::v2i32, Expand);
446     setOperationAction(ISD::SREM, MVT::v4i32, Expand);
447     setOperationAction(ISD::SREM, MVT::v1i64, Expand);
448     setOperationAction(ISD::SREM, MVT::v2i64, Expand);
449
450     setOperationAction(ISD::UREM, MVT::v1i8, Expand);
451     setOperationAction(ISD::UREM, MVT::v8i8, Expand);
452     setOperationAction(ISD::UREM, MVT::v16i8, Expand);
453     setOperationAction(ISD::UREM, MVT::v1i16, Expand);
454     setOperationAction(ISD::UREM, MVT::v4i16, Expand);
455     setOperationAction(ISD::UREM, MVT::v8i16, Expand);
456     setOperationAction(ISD::UREM, MVT::v1i32, Expand);
457     setOperationAction(ISD::UREM, MVT::v2i32, Expand);
458     setOperationAction(ISD::UREM, MVT::v4i32, Expand);
459     setOperationAction(ISD::UREM, MVT::v1i64, Expand);
460     setOperationAction(ISD::UREM, MVT::v2i64, Expand);
461
462     setOperationAction(ISD::FREM, MVT::v2f32, Expand);
463     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
464     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
465     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
466
467     setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
468     setOperationAction(ISD::SELECT, MVT::v16i8, Expand);
469     setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
470     setOperationAction(ISD::SELECT, MVT::v8i16, Expand);
471     setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
472     setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
473     setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
474     setOperationAction(ISD::SELECT, MVT::v2i64, Expand);
475     setOperationAction(ISD::SELECT, MVT::v2f32, Expand);
476     setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
477     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
478     setOperationAction(ISD::SELECT, MVT::v2f64, Expand);
479
480     setOperationAction(ISD::SELECT_CC, MVT::v8i8, Custom);
481     setOperationAction(ISD::SELECT_CC, MVT::v16i8, Custom);
482     setOperationAction(ISD::SELECT_CC, MVT::v4i16, Custom);
483     setOperationAction(ISD::SELECT_CC, MVT::v8i16, Custom);
484     setOperationAction(ISD::SELECT_CC, MVT::v2i32, Custom);
485     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Custom);
486     setOperationAction(ISD::SELECT_CC, MVT::v1i64, Custom);
487     setOperationAction(ISD::SELECT_CC, MVT::v2i64, Custom);
488     setOperationAction(ISD::SELECT_CC, MVT::v2f32, Custom);
489     setOperationAction(ISD::SELECT_CC, MVT::v4f32, Custom);
490     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Custom);
491     setOperationAction(ISD::SELECT_CC, MVT::v2f64, Custom);
492
493     // Vector ExtLoad and TruncStore are expanded.
494     for (unsigned I = MVT::FIRST_VECTOR_VALUETYPE;
495          I <= MVT::LAST_VECTOR_VALUETYPE; ++I) {
496       MVT VT = (MVT::SimpleValueType) I;
497       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
498       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
499       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
500       for (unsigned II = MVT::FIRST_VECTOR_VALUETYPE;
501            II <= MVT::LAST_VECTOR_VALUETYPE; ++II) {
502         MVT VT1 = (MVT::SimpleValueType) II;
503         // A TruncStore has two vector types of the same number of elements
504         // and different element sizes.
505         if (VT.getVectorNumElements() == VT1.getVectorNumElements() &&
506             VT.getVectorElementType().getSizeInBits()
507                 > VT1.getVectorElementType().getSizeInBits())
508           setTruncStoreAction(VT, VT1, Expand);
509       }
510     }
511
512     // There is no v1i64/v2i64 multiply, expand v1i64/v2i64 to GPR i64 multiply.
513     // FIXME: For a v2i64 multiply, we copy VPR to GPR and do 2 i64 multiplies,
514     // and then copy back to VPR. This solution may be optimized by Following 3
515     // NEON instructions:
516     //        pmull  v2.1q, v0.1d, v1.1d
517     //        pmull2 v3.1q, v0.2d, v1.2d
518     //        ins    v2.d[1], v3.d[0]
519     // As currently we can't verify the correctness of such assumption, we can
520     // do such optimization in the future.
521     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
522     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
523   }
524 }
525
526 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
527   // It's reasonably important that this value matches the "natural" legal
528   // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
529   // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
530   if (!VT.isVector()) return MVT::i32;
531   return VT.changeVectorElementTypeToInteger();
532 }
533
534 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
535                                   unsigned &LdrOpc,
536                                   unsigned &StrOpc) {
537   static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
538                                        AArch64::LDXR_word, AArch64::LDXR_dword};
539   static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
540                                      AArch64::LDAXR_word, AArch64::LDAXR_dword};
541   static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
542                                        AArch64::STXR_word, AArch64::STXR_dword};
543   static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
544                                      AArch64::STLXR_word, AArch64::STLXR_dword};
545
546   const unsigned *LoadOps, *StoreOps;
547   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
548     LoadOps = LoadAcqs;
549   else
550     LoadOps = LoadBares;
551
552   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
553     StoreOps = StoreRels;
554   else
555     StoreOps = StoreBares;
556
557   assert(isPowerOf2_32(Size) && Size <= 8 &&
558          "unsupported size for atomic binary op!");
559
560   LdrOpc = LoadOps[Log2_32(Size)];
561   StrOpc = StoreOps[Log2_32(Size)];
562 }
563
564 // FIXME: AArch64::DTripleRegClass and AArch64::QTripleRegClass don't really
565 // have value type mapped, and they are both being defined as MVT::untyped.
566 // Without knowing the MVT type, MachineLICM::getRegisterClassIDAndCost
567 // would fail to figure out the register pressure correctly.
568 std::pair<const TargetRegisterClass*, uint8_t>
569 AArch64TargetLowering::findRepresentativeClass(MVT VT) const{
570   const TargetRegisterClass *RRC = 0;
571   uint8_t Cost = 1;
572   switch (VT.SimpleTy) {
573   default:
574     return TargetLowering::findRepresentativeClass(VT);
575   case MVT::v4i64:
576     RRC = &AArch64::QPairRegClass;
577     Cost = 2;
578     break;
579   case MVT::v8i64:
580     RRC = &AArch64::QQuadRegClass;
581     Cost = 4;
582     break;
583   }
584   return std::make_pair(RRC, Cost);
585 }
586
587 MachineBasicBlock *
588 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
589                                         unsigned Size,
590                                         unsigned BinOpcode) const {
591   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
592   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
593
594   const BasicBlock *LLVM_BB = BB->getBasicBlock();
595   MachineFunction *MF = BB->getParent();
596   MachineFunction::iterator It = BB;
597   ++It;
598
599   unsigned dest = MI->getOperand(0).getReg();
600   unsigned ptr = MI->getOperand(1).getReg();
601   unsigned incr = MI->getOperand(2).getReg();
602   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
603   DebugLoc dl = MI->getDebugLoc();
604
605   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
606
607   unsigned ldrOpc, strOpc;
608   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
609
610   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
611   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
612   MF->insert(It, loopMBB);
613   MF->insert(It, exitMBB);
614
615   // Transfer the remainder of BB and its successor edges to exitMBB.
616   exitMBB->splice(exitMBB->begin(), BB,
617                   llvm::next(MachineBasicBlock::iterator(MI)),
618                   BB->end());
619   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
620
621   const TargetRegisterClass *TRC
622     = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
623   unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
624
625   //  thisMBB:
626   //   ...
627   //   fallthrough --> loopMBB
628   BB->addSuccessor(loopMBB);
629
630   //  loopMBB:
631   //   ldxr dest, ptr
632   //   <binop> scratch, dest, incr
633   //   stxr stxr_status, scratch, ptr
634   //   cbnz stxr_status, loopMBB
635   //   fallthrough --> exitMBB
636   BB = loopMBB;
637   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
638   if (BinOpcode) {
639     // All arithmetic operations we'll be creating are designed to take an extra
640     // shift or extend operand, which we can conveniently set to zero.
641
642     // Operand order needs to go the other way for NAND.
643     if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
644       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
645         .addReg(incr).addReg(dest).addImm(0);
646     else
647       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
648         .addReg(dest).addReg(incr).addImm(0);
649   }
650
651   // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
652   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
653   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
654
655   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
656   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
657     .addReg(stxr_status).addMBB(loopMBB);
658
659   BB->addSuccessor(loopMBB);
660   BB->addSuccessor(exitMBB);
661
662   //  exitMBB:
663   //   ...
664   BB = exitMBB;
665
666   MI->eraseFromParent();   // The instruction is gone now.
667
668   return BB;
669 }
670
671 MachineBasicBlock *
672 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
673                                               MachineBasicBlock *BB,
674                                               unsigned Size,
675                                               unsigned CmpOp,
676                                               A64CC::CondCodes Cond) const {
677   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
678
679   const BasicBlock *LLVM_BB = BB->getBasicBlock();
680   MachineFunction *MF = BB->getParent();
681   MachineFunction::iterator It = BB;
682   ++It;
683
684   unsigned dest = MI->getOperand(0).getReg();
685   unsigned ptr = MI->getOperand(1).getReg();
686   unsigned incr = MI->getOperand(2).getReg();
687   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
688
689   unsigned oldval = dest;
690   DebugLoc dl = MI->getDebugLoc();
691
692   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
693   const TargetRegisterClass *TRC, *TRCsp;
694   if (Size == 8) {
695     TRC = &AArch64::GPR64RegClass;
696     TRCsp = &AArch64::GPR64xspRegClass;
697   } else {
698     TRC = &AArch64::GPR32RegClass;
699     TRCsp = &AArch64::GPR32wspRegClass;
700   }
701
702   unsigned ldrOpc, strOpc;
703   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
704
705   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
706   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
707   MF->insert(It, loopMBB);
708   MF->insert(It, exitMBB);
709
710   // Transfer the remainder of BB and its successor edges to exitMBB.
711   exitMBB->splice(exitMBB->begin(), BB,
712                   llvm::next(MachineBasicBlock::iterator(MI)),
713                   BB->end());
714   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
715
716   unsigned scratch = MRI.createVirtualRegister(TRC);
717   MRI.constrainRegClass(scratch, TRCsp);
718
719   //  thisMBB:
720   //   ...
721   //   fallthrough --> loopMBB
722   BB->addSuccessor(loopMBB);
723
724   //  loopMBB:
725   //   ldxr dest, ptr
726   //   cmp incr, dest (, sign extend if necessary)
727   //   csel scratch, dest, incr, cond
728   //   stxr stxr_status, scratch, ptr
729   //   cbnz stxr_status, loopMBB
730   //   fallthrough --> exitMBB
731   BB = loopMBB;
732   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
733
734   // Build compare and cmov instructions.
735   MRI.constrainRegClass(incr, TRCsp);
736   BuildMI(BB, dl, TII->get(CmpOp))
737     .addReg(incr).addReg(oldval).addImm(0);
738
739   BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
740           scratch)
741     .addReg(oldval).addReg(incr).addImm(Cond);
742
743   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
744   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
745
746   BuildMI(BB, dl, TII->get(strOpc), stxr_status)
747     .addReg(scratch).addReg(ptr);
748   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
749     .addReg(stxr_status).addMBB(loopMBB);
750
751   BB->addSuccessor(loopMBB);
752   BB->addSuccessor(exitMBB);
753
754   //  exitMBB:
755   //   ...
756   BB = exitMBB;
757
758   MI->eraseFromParent();   // The instruction is gone now.
759
760   return BB;
761 }
762
763 MachineBasicBlock *
764 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
765                                          MachineBasicBlock *BB,
766                                          unsigned Size) const {
767   unsigned dest    = MI->getOperand(0).getReg();
768   unsigned ptr     = MI->getOperand(1).getReg();
769   unsigned oldval  = MI->getOperand(2).getReg();
770   unsigned newval  = MI->getOperand(3).getReg();
771   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
772   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
773   DebugLoc dl = MI->getDebugLoc();
774
775   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
776   const TargetRegisterClass *TRCsp;
777   TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
778
779   unsigned ldrOpc, strOpc;
780   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
781
782   MachineFunction *MF = BB->getParent();
783   const BasicBlock *LLVM_BB = BB->getBasicBlock();
784   MachineFunction::iterator It = BB;
785   ++It; // insert the new blocks after the current block
786
787   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
788   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
789   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
790   MF->insert(It, loop1MBB);
791   MF->insert(It, loop2MBB);
792   MF->insert(It, exitMBB);
793
794   // Transfer the remainder of BB and its successor edges to exitMBB.
795   exitMBB->splice(exitMBB->begin(), BB,
796                   llvm::next(MachineBasicBlock::iterator(MI)),
797                   BB->end());
798   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
799
800   //  thisMBB:
801   //   ...
802   //   fallthrough --> loop1MBB
803   BB->addSuccessor(loop1MBB);
804
805   // loop1MBB:
806   //   ldxr dest, [ptr]
807   //   cmp dest, oldval
808   //   b.ne exitMBB
809   BB = loop1MBB;
810   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
811
812   unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
813   MRI.constrainRegClass(dest, TRCsp);
814   BuildMI(BB, dl, TII->get(CmpOp))
815     .addReg(dest).addReg(oldval).addImm(0);
816   BuildMI(BB, dl, TII->get(AArch64::Bcc))
817     .addImm(A64CC::NE).addMBB(exitMBB);
818   BB->addSuccessor(loop2MBB);
819   BB->addSuccessor(exitMBB);
820
821   // loop2MBB:
822   //   strex stxr_status, newval, [ptr]
823   //   cbnz stxr_status, loop1MBB
824   BB = loop2MBB;
825   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
826   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
827
828   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
829   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
830     .addReg(stxr_status).addMBB(loop1MBB);
831   BB->addSuccessor(loop1MBB);
832   BB->addSuccessor(exitMBB);
833
834   //  exitMBB:
835   //   ...
836   BB = exitMBB;
837
838   MI->eraseFromParent();   // The instruction is gone now.
839
840   return BB;
841 }
842
843 MachineBasicBlock *
844 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
845                                     MachineBasicBlock *MBB) const {
846   // We materialise the F128CSEL pseudo-instruction using conditional branches
847   // and loads, giving an instruciton sequence like:
848   //     str q0, [sp]
849   //     b.ne IfTrue
850   //     b Finish
851   // IfTrue:
852   //     str q1, [sp]
853   // Finish:
854   //     ldr q0, [sp]
855   //
856   // Using virtual registers would probably not be beneficial since COPY
857   // instructions are expensive for f128 (there's no actual instruction to
858   // implement them).
859   //
860   // An alternative would be to do an integer-CSEL on some address. E.g.:
861   //     mov x0, sp
862   //     add x1, sp, #16
863   //     str q0, [x0]
864   //     str q1, [x1]
865   //     csel x0, x0, x1, ne
866   //     ldr q0, [x0]
867   //
868   // It's unclear which approach is actually optimal.
869   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
870   MachineFunction *MF = MBB->getParent();
871   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
872   DebugLoc DL = MI->getDebugLoc();
873   MachineFunction::iterator It = MBB;
874   ++It;
875
876   unsigned DestReg = MI->getOperand(0).getReg();
877   unsigned IfTrueReg = MI->getOperand(1).getReg();
878   unsigned IfFalseReg = MI->getOperand(2).getReg();
879   unsigned CondCode = MI->getOperand(3).getImm();
880   bool NZCVKilled = MI->getOperand(4).isKill();
881
882   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
883   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
884   MF->insert(It, TrueBB);
885   MF->insert(It, EndBB);
886
887   // Transfer rest of current basic-block to EndBB
888   EndBB->splice(EndBB->begin(), MBB,
889                 llvm::next(MachineBasicBlock::iterator(MI)),
890                 MBB->end());
891   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
892
893   // We need somewhere to store the f128 value needed.
894   int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
895
896   //     [... start of incoming MBB ...]
897   //     str qIFFALSE, [sp]
898   //     b.cc IfTrue
899   //     b Done
900   BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
901     .addReg(IfFalseReg)
902     .addFrameIndex(ScratchFI)
903     .addImm(0);
904   BuildMI(MBB, DL, TII->get(AArch64::Bcc))
905     .addImm(CondCode)
906     .addMBB(TrueBB);
907   BuildMI(MBB, DL, TII->get(AArch64::Bimm))
908     .addMBB(EndBB);
909   MBB->addSuccessor(TrueBB);
910   MBB->addSuccessor(EndBB);
911
912   if (!NZCVKilled) {
913     // NZCV is live-through TrueBB.
914     TrueBB->addLiveIn(AArch64::NZCV);
915     EndBB->addLiveIn(AArch64::NZCV);
916   }
917
918   // IfTrue:
919   //     str qIFTRUE, [sp]
920   BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
921     .addReg(IfTrueReg)
922     .addFrameIndex(ScratchFI)
923     .addImm(0);
924
925   // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
926   // blocks.
927   TrueBB->addSuccessor(EndBB);
928
929   // Done:
930   //     ldr qDEST, [sp]
931   //     [... rest of incoming MBB ...]
932   MachineInstr *StartOfEnd = EndBB->begin();
933   BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
934     .addFrameIndex(ScratchFI)
935     .addImm(0);
936
937   MI->eraseFromParent();
938   return EndBB;
939 }
940
941 MachineBasicBlock *
942 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
943                                                  MachineBasicBlock *MBB) const {
944   switch (MI->getOpcode()) {
945   default: llvm_unreachable("Unhandled instruction with custom inserter");
946   case AArch64::F128CSEL:
947     return EmitF128CSEL(MI, MBB);
948   case AArch64::ATOMIC_LOAD_ADD_I8:
949     return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
950   case AArch64::ATOMIC_LOAD_ADD_I16:
951     return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
952   case AArch64::ATOMIC_LOAD_ADD_I32:
953     return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
954   case AArch64::ATOMIC_LOAD_ADD_I64:
955     return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
956
957   case AArch64::ATOMIC_LOAD_SUB_I8:
958     return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
959   case AArch64::ATOMIC_LOAD_SUB_I16:
960     return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
961   case AArch64::ATOMIC_LOAD_SUB_I32:
962     return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
963   case AArch64::ATOMIC_LOAD_SUB_I64:
964     return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
965
966   case AArch64::ATOMIC_LOAD_AND_I8:
967     return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
968   case AArch64::ATOMIC_LOAD_AND_I16:
969     return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
970   case AArch64::ATOMIC_LOAD_AND_I32:
971     return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
972   case AArch64::ATOMIC_LOAD_AND_I64:
973     return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
974
975   case AArch64::ATOMIC_LOAD_OR_I8:
976     return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
977   case AArch64::ATOMIC_LOAD_OR_I16:
978     return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
979   case AArch64::ATOMIC_LOAD_OR_I32:
980     return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
981   case AArch64::ATOMIC_LOAD_OR_I64:
982     return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
983
984   case AArch64::ATOMIC_LOAD_XOR_I8:
985     return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
986   case AArch64::ATOMIC_LOAD_XOR_I16:
987     return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
988   case AArch64::ATOMIC_LOAD_XOR_I32:
989     return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
990   case AArch64::ATOMIC_LOAD_XOR_I64:
991     return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
992
993   case AArch64::ATOMIC_LOAD_NAND_I8:
994     return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
995   case AArch64::ATOMIC_LOAD_NAND_I16:
996     return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
997   case AArch64::ATOMIC_LOAD_NAND_I32:
998     return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
999   case AArch64::ATOMIC_LOAD_NAND_I64:
1000     return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
1001
1002   case AArch64::ATOMIC_LOAD_MIN_I8:
1003     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
1004   case AArch64::ATOMIC_LOAD_MIN_I16:
1005     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
1006   case AArch64::ATOMIC_LOAD_MIN_I32:
1007     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
1008   case AArch64::ATOMIC_LOAD_MIN_I64:
1009     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
1010
1011   case AArch64::ATOMIC_LOAD_MAX_I8:
1012     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
1013   case AArch64::ATOMIC_LOAD_MAX_I16:
1014     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
1015   case AArch64::ATOMIC_LOAD_MAX_I32:
1016     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
1017   case AArch64::ATOMIC_LOAD_MAX_I64:
1018     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
1019
1020   case AArch64::ATOMIC_LOAD_UMIN_I8:
1021     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
1022   case AArch64::ATOMIC_LOAD_UMIN_I16:
1023     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
1024   case AArch64::ATOMIC_LOAD_UMIN_I32:
1025     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
1026   case AArch64::ATOMIC_LOAD_UMIN_I64:
1027     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
1028
1029   case AArch64::ATOMIC_LOAD_UMAX_I8:
1030     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
1031   case AArch64::ATOMIC_LOAD_UMAX_I16:
1032     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
1033   case AArch64::ATOMIC_LOAD_UMAX_I32:
1034     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
1035   case AArch64::ATOMIC_LOAD_UMAX_I64:
1036     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
1037
1038   case AArch64::ATOMIC_SWAP_I8:
1039     return emitAtomicBinary(MI, MBB, 1, 0);
1040   case AArch64::ATOMIC_SWAP_I16:
1041     return emitAtomicBinary(MI, MBB, 2, 0);
1042   case AArch64::ATOMIC_SWAP_I32:
1043     return emitAtomicBinary(MI, MBB, 4, 0);
1044   case AArch64::ATOMIC_SWAP_I64:
1045     return emitAtomicBinary(MI, MBB, 8, 0);
1046
1047   case AArch64::ATOMIC_CMP_SWAP_I8:
1048     return emitAtomicCmpSwap(MI, MBB, 1);
1049   case AArch64::ATOMIC_CMP_SWAP_I16:
1050     return emitAtomicCmpSwap(MI, MBB, 2);
1051   case AArch64::ATOMIC_CMP_SWAP_I32:
1052     return emitAtomicCmpSwap(MI, MBB, 4);
1053   case AArch64::ATOMIC_CMP_SWAP_I64:
1054     return emitAtomicCmpSwap(MI, MBB, 8);
1055   }
1056 }
1057
1058
1059 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1060   switch (Opcode) {
1061   case AArch64ISD::BR_CC:          return "AArch64ISD::BR_CC";
1062   case AArch64ISD::Call:           return "AArch64ISD::Call";
1063   case AArch64ISD::FPMOV:          return "AArch64ISD::FPMOV";
1064   case AArch64ISD::GOTLoad:        return "AArch64ISD::GOTLoad";
1065   case AArch64ISD::BFI:            return "AArch64ISD::BFI";
1066   case AArch64ISD::EXTR:           return "AArch64ISD::EXTR";
1067   case AArch64ISD::Ret:            return "AArch64ISD::Ret";
1068   case AArch64ISD::SBFX:           return "AArch64ISD::SBFX";
1069   case AArch64ISD::SELECT_CC:      return "AArch64ISD::SELECT_CC";
1070   case AArch64ISD::SETCC:          return "AArch64ISD::SETCC";
1071   case AArch64ISD::TC_RETURN:      return "AArch64ISD::TC_RETURN";
1072   case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1073   case AArch64ISD::TLSDESCCALL:    return "AArch64ISD::TLSDESCCALL";
1074   case AArch64ISD::WrapperLarge:   return "AArch64ISD::WrapperLarge";
1075   case AArch64ISD::WrapperSmall:   return "AArch64ISD::WrapperSmall";
1076
1077   case AArch64ISD::NEON_MOVIMM:
1078     return "AArch64ISD::NEON_MOVIMM";
1079   case AArch64ISD::NEON_MVNIMM:
1080     return "AArch64ISD::NEON_MVNIMM";
1081   case AArch64ISD::NEON_FMOVIMM:
1082     return "AArch64ISD::NEON_FMOVIMM";
1083   case AArch64ISD::NEON_CMP:
1084     return "AArch64ISD::NEON_CMP";
1085   case AArch64ISD::NEON_CMPZ:
1086     return "AArch64ISD::NEON_CMPZ";
1087   case AArch64ISD::NEON_TST:
1088     return "AArch64ISD::NEON_TST";
1089   case AArch64ISD::NEON_QSHLs:
1090     return "AArch64ISD::NEON_QSHLs";
1091   case AArch64ISD::NEON_QSHLu:
1092     return "AArch64ISD::NEON_QSHLu";
1093   case AArch64ISD::NEON_VDUP:
1094     return "AArch64ISD::NEON_VDUP";
1095   case AArch64ISD::NEON_VDUPLANE:
1096     return "AArch64ISD::NEON_VDUPLANE";
1097   case AArch64ISD::NEON_REV16:
1098     return "AArch64ISD::NEON_REV16";
1099   case AArch64ISD::NEON_REV32:
1100     return "AArch64ISD::NEON_REV32";
1101   case AArch64ISD::NEON_REV64:
1102     return "AArch64ISD::NEON_REV64";
1103   case AArch64ISD::NEON_UZP1:
1104     return "AArch64ISD::NEON_UZP1";
1105   case AArch64ISD::NEON_UZP2:
1106     return "AArch64ISD::NEON_UZP2";
1107   case AArch64ISD::NEON_ZIP1:
1108     return "AArch64ISD::NEON_ZIP1";
1109   case AArch64ISD::NEON_ZIP2:
1110     return "AArch64ISD::NEON_ZIP2";
1111   case AArch64ISD::NEON_TRN1:
1112     return "AArch64ISD::NEON_TRN1";
1113   case AArch64ISD::NEON_TRN2:
1114     return "AArch64ISD::NEON_TRN2";
1115   case AArch64ISD::NEON_LD1_UPD:
1116     return "AArch64ISD::NEON_LD1_UPD";
1117   case AArch64ISD::NEON_LD2_UPD:
1118     return "AArch64ISD::NEON_LD2_UPD";
1119   case AArch64ISD::NEON_LD3_UPD:
1120     return "AArch64ISD::NEON_LD3_UPD";
1121   case AArch64ISD::NEON_LD4_UPD:
1122     return "AArch64ISD::NEON_LD4_UPD";
1123   case AArch64ISD::NEON_ST1_UPD:
1124     return "AArch64ISD::NEON_ST1_UPD";
1125   case AArch64ISD::NEON_ST2_UPD:
1126     return "AArch64ISD::NEON_ST2_UPD";
1127   case AArch64ISD::NEON_ST3_UPD:
1128     return "AArch64ISD::NEON_ST3_UPD";
1129   case AArch64ISD::NEON_ST4_UPD:
1130     return "AArch64ISD::NEON_ST4_UPD";
1131   case AArch64ISD::NEON_LD1x2_UPD:
1132     return "AArch64ISD::NEON_LD1x2_UPD";
1133   case AArch64ISD::NEON_LD1x3_UPD:
1134     return "AArch64ISD::NEON_LD1x3_UPD";
1135   case AArch64ISD::NEON_LD1x4_UPD:
1136     return "AArch64ISD::NEON_LD1x4_UPD";
1137   case AArch64ISD::NEON_ST1x2_UPD:
1138     return "AArch64ISD::NEON_ST1x2_UPD";
1139   case AArch64ISD::NEON_ST1x3_UPD:
1140     return "AArch64ISD::NEON_ST1x3_UPD";
1141   case AArch64ISD::NEON_ST1x4_UPD:
1142     return "AArch64ISD::NEON_ST1x4_UPD";
1143   case AArch64ISD::NEON_LD2DUP:
1144     return "AArch64ISD::NEON_LD2DUP";
1145   case AArch64ISD::NEON_LD3DUP:
1146     return "AArch64ISD::NEON_LD3DUP";
1147   case AArch64ISD::NEON_LD4DUP:
1148     return "AArch64ISD::NEON_LD4DUP";
1149   case AArch64ISD::NEON_LD2DUP_UPD:
1150     return "AArch64ISD::NEON_LD2DUP_UPD";
1151   case AArch64ISD::NEON_LD3DUP_UPD:
1152     return "AArch64ISD::NEON_LD3DUP_UPD";
1153   case AArch64ISD::NEON_LD4DUP_UPD:
1154     return "AArch64ISD::NEON_LD4DUP_UPD";
1155   case AArch64ISD::NEON_LD2LN_UPD:
1156     return "AArch64ISD::NEON_LD2LN_UPD";
1157   case AArch64ISD::NEON_LD3LN_UPD:
1158     return "AArch64ISD::NEON_LD3LN_UPD";
1159   case AArch64ISD::NEON_LD4LN_UPD:
1160     return "AArch64ISD::NEON_LD4LN_UPD";
1161   case AArch64ISD::NEON_ST2LN_UPD:
1162     return "AArch64ISD::NEON_ST2LN_UPD";
1163   case AArch64ISD::NEON_ST3LN_UPD:
1164     return "AArch64ISD::NEON_ST3LN_UPD";
1165   case AArch64ISD::NEON_ST4LN_UPD:
1166     return "AArch64ISD::NEON_ST4LN_UPD";
1167   case AArch64ISD::NEON_VEXTRACT:
1168     return "AArch64ISD::NEON_VEXTRACT";
1169   default:
1170     return NULL;
1171   }
1172 }
1173
1174 static const uint16_t AArch64FPRArgRegs[] = {
1175   AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
1176   AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
1177 };
1178 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
1179
1180 static const uint16_t AArch64ArgRegs[] = {
1181   AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
1182   AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
1183 };
1184 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
1185
1186 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
1187                                  CCValAssign::LocInfo LocInfo,
1188                                  ISD::ArgFlagsTy ArgFlags, CCState &State) {
1189   // Mark all remaining general purpose registers as allocated. We don't
1190   // backtrack: if (for example) an i128 gets put on the stack, no subsequent
1191   // i64 will go in registers (C.11).
1192   for (unsigned i = 0; i < NumArgRegs; ++i)
1193     State.AllocateReg(AArch64ArgRegs[i]);
1194
1195   return false;
1196 }
1197
1198 #include "AArch64GenCallingConv.inc"
1199
1200 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1201
1202   switch(CC) {
1203   default: llvm_unreachable("Unsupported calling convention");
1204   case CallingConv::Fast:
1205   case CallingConv::C:
1206     return CC_A64_APCS;
1207   }
1208 }
1209
1210 void
1211 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
1212                                            SDLoc DL, SDValue &Chain) const {
1213   MachineFunction &MF = DAG.getMachineFunction();
1214   MachineFrameInfo *MFI = MF.getFrameInfo();
1215   AArch64MachineFunctionInfo *FuncInfo
1216     = MF.getInfo<AArch64MachineFunctionInfo>();
1217
1218   SmallVector<SDValue, 8> MemOps;
1219
1220   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
1221                                                          NumArgRegs);
1222   unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
1223                                                          NumFPRArgRegs);
1224
1225   unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
1226   int GPRIdx = 0;
1227   if (GPRSaveSize != 0) {
1228     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1229
1230     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1231
1232     for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
1233       unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
1234       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1235       SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
1236                                    MachinePointerInfo::getStack(i * 8),
1237                                    false, false, 0);
1238       MemOps.push_back(Store);
1239       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1240                         DAG.getConstant(8, getPointerTy()));
1241     }
1242   }
1243
1244   if (getSubtarget()->hasFPARMv8()) {
1245   unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1246   int FPRIdx = 0;
1247     // According to the AArch64 Procedure Call Standard, section B.1/B.3, we
1248     // can omit a register save area if we know we'll never use registers of
1249     // that class.
1250     if (FPRSaveSize != 0) {
1251       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1252
1253       SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1254
1255       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1256         unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
1257             &AArch64::FPR128RegClass);
1258         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1259         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
1260             MachinePointerInfo::getStack(i * 16),
1261             false, false, 0);
1262         MemOps.push_back(Store);
1263         FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1264             DAG.getConstant(16, getPointerTy()));
1265       }
1266     }
1267     FuncInfo->setVariadicFPRIdx(FPRIdx);
1268     FuncInfo->setVariadicFPRSize(FPRSaveSize);
1269   }
1270
1271   int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
1272
1273   FuncInfo->setVariadicStackIdx(StackIdx);
1274   FuncInfo->setVariadicGPRIdx(GPRIdx);
1275   FuncInfo->setVariadicGPRSize(GPRSaveSize);
1276
1277   if (!MemOps.empty()) {
1278     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
1279                         MemOps.size());
1280   }
1281 }
1282
1283
1284 SDValue
1285 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
1286                                       CallingConv::ID CallConv, bool isVarArg,
1287                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1288                                       SDLoc dl, SelectionDAG &DAG,
1289                                       SmallVectorImpl<SDValue> &InVals) const {
1290   MachineFunction &MF = DAG.getMachineFunction();
1291   AArch64MachineFunctionInfo *FuncInfo
1292     = MF.getInfo<AArch64MachineFunctionInfo>();
1293   MachineFrameInfo *MFI = MF.getFrameInfo();
1294   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1295
1296   SmallVector<CCValAssign, 16> ArgLocs;
1297   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1298                  getTargetMachine(), ArgLocs, *DAG.getContext());
1299   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1300
1301   SmallVector<SDValue, 16> ArgValues;
1302
1303   SDValue ArgValue;
1304   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1305     CCValAssign &VA = ArgLocs[i];
1306     ISD::ArgFlagsTy Flags = Ins[i].Flags;
1307
1308     if (Flags.isByVal()) {
1309       // Byval is used for small structs and HFAs in the PCS, but the system
1310       // should work in a non-compliant manner for larger structs.
1311       EVT PtrTy = getPointerTy();
1312       int Size = Flags.getByValSize();
1313       unsigned NumRegs = (Size + 7) / 8;
1314
1315       unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1316                                                  VA.getLocMemOffset(),
1317                                                  false);
1318       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1319       InVals.push_back(FrameIdxN);
1320
1321       continue;
1322     } else if (VA.isRegLoc()) {
1323       MVT RegVT = VA.getLocVT();
1324       const TargetRegisterClass *RC = getRegClassFor(RegVT);
1325       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1326
1327       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1328     } else { // VA.isRegLoc()
1329       assert(VA.isMemLoc());
1330
1331       int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1332                                       VA.getLocMemOffset(), true);
1333
1334       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1335       ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1336                              MachinePointerInfo::getFixedStack(FI),
1337                              false, false, false, 0);
1338
1339
1340     }
1341
1342     switch (VA.getLocInfo()) {
1343     default: llvm_unreachable("Unknown loc info!");
1344     case CCValAssign::Full: break;
1345     case CCValAssign::BCvt:
1346       ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1347       break;
1348     case CCValAssign::SExt:
1349     case CCValAssign::ZExt:
1350     case CCValAssign::AExt:
1351     case CCValAssign::FPExt: {
1352       unsigned DestSize = VA.getValVT().getSizeInBits();
1353       unsigned DestSubReg;
1354
1355       switch (DestSize) {
1356       case 8: DestSubReg = AArch64::sub_8; break;
1357       case 16: DestSubReg = AArch64::sub_16; break;
1358       case 32: DestSubReg = AArch64::sub_32; break;
1359       case 64: DestSubReg = AArch64::sub_64; break;
1360       default: llvm_unreachable("Unexpected argument promotion");
1361       }
1362
1363       ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1364                                    VA.getValVT(), ArgValue,
1365                                    DAG.getTargetConstant(DestSubReg, MVT::i32)),
1366                          0);
1367       break;
1368     }
1369     }
1370
1371     InVals.push_back(ArgValue);
1372   }
1373
1374   if (isVarArg)
1375     SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1376
1377   unsigned StackArgSize = CCInfo.getNextStackOffset();
1378   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1379     // This is a non-standard ABI so by fiat I say we're allowed to make full
1380     // use of the stack area to be popped, which must be aligned to 16 bytes in
1381     // any case:
1382     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1383
1384     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1385     // a multiple of 16.
1386     FuncInfo->setArgumentStackToRestore(StackArgSize);
1387
1388     // This realignment carries over to the available bytes below. Our own
1389     // callers will guarantee the space is free by giving an aligned value to
1390     // CALLSEQ_START.
1391   }
1392   // Even if we're not expected to free up the space, it's useful to know how
1393   // much is there while considering tail calls (because we can reuse it).
1394   FuncInfo->setBytesInStackArgArea(StackArgSize);
1395
1396   return Chain;
1397 }
1398
1399 SDValue
1400 AArch64TargetLowering::LowerReturn(SDValue Chain,
1401                                    CallingConv::ID CallConv, bool isVarArg,
1402                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1403                                    const SmallVectorImpl<SDValue> &OutVals,
1404                                    SDLoc dl, SelectionDAG &DAG) const {
1405   // CCValAssign - represent the assignment of the return value to a location.
1406   SmallVector<CCValAssign, 16> RVLocs;
1407
1408   // CCState - Info about the registers and stack slots.
1409   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1410                  getTargetMachine(), RVLocs, *DAG.getContext());
1411
1412   // Analyze outgoing return values.
1413   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1414
1415   SDValue Flag;
1416   SmallVector<SDValue, 4> RetOps(1, Chain);
1417
1418   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1419     // PCS: "If the type, T, of the result of a function is such that
1420     // void func(T arg) would require that arg be passed as a value in a
1421     // register (or set of registers) according to the rules in 5.4, then the
1422     // result is returned in the same registers as would be used for such an
1423     // argument.
1424     //
1425     // Otherwise, the caller shall reserve a block of memory of sufficient
1426     // size and alignment to hold the result. The address of the memory block
1427     // shall be passed as an additional argument to the function in x8."
1428     //
1429     // This is implemented in two places. The register-return values are dealt
1430     // with here, more complex returns are passed as an sret parameter, which
1431     // means we don't have to worry about it during actual return.
1432     CCValAssign &VA = RVLocs[i];
1433     assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1434
1435
1436     SDValue Arg = OutVals[i];
1437
1438     // There's no convenient note in the ABI about this as there is for normal
1439     // arguments, but it says return values are passed in the same registers as
1440     // an argument would be. I believe that includes the comments about
1441     // unspecified higher bits, putting the burden of widening on the *caller*
1442     // for return values.
1443     switch (VA.getLocInfo()) {
1444     default: llvm_unreachable("Unknown loc info");
1445     case CCValAssign::Full: break;
1446     case CCValAssign::SExt:
1447     case CCValAssign::ZExt:
1448     case CCValAssign::AExt:
1449       // Floating-point values should only be extended when they're going into
1450       // memory, which can't happen here so an integer extend is acceptable.
1451       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1452       break;
1453     case CCValAssign::BCvt:
1454       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1455       break;
1456     }
1457
1458     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1459     Flag = Chain.getValue(1);
1460     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1461   }
1462
1463   RetOps[0] = Chain;  // Update chain.
1464
1465   // Add the flag if we have it.
1466   if (Flag.getNode())
1467     RetOps.push_back(Flag);
1468
1469   return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1470                      &RetOps[0], RetOps.size());
1471 }
1472
1473 unsigned AArch64TargetLowering::getByValTypeAlignment(Type *Ty) const {
1474   // This is a new backend. For anything more precise than this a FE should
1475   // set an explicit alignment.
1476   return 4;
1477 }
1478
1479 SDValue
1480 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1481                                  SmallVectorImpl<SDValue> &InVals) const {
1482   SelectionDAG &DAG                     = CLI.DAG;
1483   SDLoc &dl                             = CLI.DL;
1484   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1485   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1486   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1487   SDValue Chain                         = CLI.Chain;
1488   SDValue Callee                        = CLI.Callee;
1489   bool &IsTailCall                      = CLI.IsTailCall;
1490   CallingConv::ID CallConv              = CLI.CallConv;
1491   bool IsVarArg                         = CLI.IsVarArg;
1492
1493   MachineFunction &MF = DAG.getMachineFunction();
1494   AArch64MachineFunctionInfo *FuncInfo
1495     = MF.getInfo<AArch64MachineFunctionInfo>();
1496   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1497   bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1498   bool IsSibCall = false;
1499
1500   if (IsTailCall) {
1501     IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1502                     IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1503                                                    Outs, OutVals, Ins, DAG);
1504
1505     // A sibling call is one where we're under the usual C ABI and not planning
1506     // to change that but can still do a tail call:
1507     if (!TailCallOpt && IsTailCall)
1508       IsSibCall = true;
1509   }
1510
1511   SmallVector<CCValAssign, 16> ArgLocs;
1512   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1513                  getTargetMachine(), ArgLocs, *DAG.getContext());
1514   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1515
1516   // On AArch64 (and all other architectures I'm aware of) the most this has to
1517   // do is adjust the stack pointer.
1518   unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1519   if (IsSibCall) {
1520     // Since we're not changing the ABI to make this a tail call, the memory
1521     // operands are already available in the caller's incoming argument space.
1522     NumBytes = 0;
1523   }
1524
1525   // FPDiff is the byte offset of the call's argument area from the callee's.
1526   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1527   // by this amount for a tail call. In a sibling call it must be 0 because the
1528   // caller will deallocate the entire stack and the callee still expects its
1529   // arguments to begin at SP+0. Completely unused for non-tail calls.
1530   int FPDiff = 0;
1531
1532   if (IsTailCall && !IsSibCall) {
1533     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1534
1535     // FPDiff will be negative if this tail call requires more space than we
1536     // would automatically have in our incoming argument space. Positive if we
1537     // can actually shrink the stack.
1538     FPDiff = NumReusableBytes - NumBytes;
1539
1540     // The stack pointer must be 16-byte aligned at all times it's used for a
1541     // memory operation, which in practice means at *all* times and in
1542     // particular across call boundaries. Therefore our own arguments started at
1543     // a 16-byte aligned SP and the delta applied for the tail call should
1544     // satisfy the same constraint.
1545     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1546   }
1547
1548   if (!IsSibCall)
1549     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1550                                  dl);
1551
1552   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1553                                         getPointerTy());
1554
1555   SmallVector<SDValue, 8> MemOpChains;
1556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1557
1558   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1559     CCValAssign &VA = ArgLocs[i];
1560     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1561     SDValue Arg = OutVals[i];
1562
1563     // Callee does the actual widening, so all extensions just use an implicit
1564     // definition of the rest of the Loc. Aesthetically, this would be nicer as
1565     // an ANY_EXTEND, but that isn't valid for floating-point types and this
1566     // alternative works on integer types too.
1567     switch (VA.getLocInfo()) {
1568     default: llvm_unreachable("Unknown loc info!");
1569     case CCValAssign::Full: break;
1570     case CCValAssign::SExt:
1571     case CCValAssign::ZExt:
1572     case CCValAssign::AExt:
1573     case CCValAssign::FPExt: {
1574       unsigned SrcSize = VA.getValVT().getSizeInBits();
1575       unsigned SrcSubReg;
1576
1577       switch (SrcSize) {
1578       case 8: SrcSubReg = AArch64::sub_8; break;
1579       case 16: SrcSubReg = AArch64::sub_16; break;
1580       case 32: SrcSubReg = AArch64::sub_32; break;
1581       case 64: SrcSubReg = AArch64::sub_64; break;
1582       default: llvm_unreachable("Unexpected argument promotion");
1583       }
1584
1585       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1586                                     VA.getLocVT(),
1587                                     DAG.getUNDEF(VA.getLocVT()),
1588                                     Arg,
1589                                     DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1590                     0);
1591
1592       break;
1593     }
1594     case CCValAssign::BCvt:
1595       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1596       break;
1597     }
1598
1599     if (VA.isRegLoc()) {
1600       // A normal register (sub-) argument. For now we just note it down because
1601       // we want to copy things into registers as late as possible to avoid
1602       // register-pressure (and possibly worse).
1603       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1604       continue;
1605     }
1606
1607     assert(VA.isMemLoc() && "unexpected argument location");
1608
1609     SDValue DstAddr;
1610     MachinePointerInfo DstInfo;
1611     if (IsTailCall) {
1612       uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1613                                           VA.getLocVT().getSizeInBits();
1614       OpSize = (OpSize + 7) / 8;
1615       int32_t Offset = VA.getLocMemOffset() + FPDiff;
1616       int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1617
1618       DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1619       DstInfo = MachinePointerInfo::getFixedStack(FI);
1620
1621       // Make sure any stack arguments overlapping with where we're storing are
1622       // loaded before this eventual operation. Otherwise they'll be clobbered.
1623       Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1624     } else {
1625       SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1626
1627       DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1628       DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1629     }
1630
1631     if (Flags.isByVal()) {
1632       SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1633       SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1634                                   Flags.getByValAlign(),
1635                                   /*isVolatile = */ false,
1636                                   /*alwaysInline = */ false,
1637                                   DstInfo, MachinePointerInfo(0));
1638       MemOpChains.push_back(Cpy);
1639     } else {
1640       // Normal stack argument, put it where it's needed.
1641       SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1642                                    false, false, 0);
1643       MemOpChains.push_back(Store);
1644     }
1645   }
1646
1647   // The loads and stores generated above shouldn't clash with each
1648   // other. Combining them with this TokenFactor notes that fact for the rest of
1649   // the backend.
1650   if (!MemOpChains.empty())
1651     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1652                         &MemOpChains[0], MemOpChains.size());
1653
1654   // Most of the rest of the instructions need to be glued together; we don't
1655   // want assignments to actual registers used by a call to be rearranged by a
1656   // well-meaning scheduler.
1657   SDValue InFlag;
1658
1659   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1660     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1661                              RegsToPass[i].second, InFlag);
1662     InFlag = Chain.getValue(1);
1663   }
1664
1665   // The linker is responsible for inserting veneers when necessary to put a
1666   // function call destination in range, so we don't need to bother with a
1667   // wrapper here.
1668   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1669     const GlobalValue *GV = G->getGlobal();
1670     Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1671   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1672     const char *Sym = S->getSymbol();
1673     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1674   }
1675
1676   // We don't usually want to end the call-sequence here because we would tidy
1677   // the frame up *after* the call, however in the ABI-changing tail-call case
1678   // we've carefully laid out the parameters so that when sp is reset they'll be
1679   // in the correct location.
1680   if (IsTailCall && !IsSibCall) {
1681     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1682                                DAG.getIntPtrConstant(0, true), InFlag, dl);
1683     InFlag = Chain.getValue(1);
1684   }
1685
1686   // We produce the following DAG scheme for the actual call instruction:
1687   //     (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1688   //
1689   // Most arguments aren't going to be used and just keep the values live as
1690   // far as LLVM is concerned. It's expected to be selected as simply "bl
1691   // callee" (for a direct, non-tail call).
1692   std::vector<SDValue> Ops;
1693   Ops.push_back(Chain);
1694   Ops.push_back(Callee);
1695
1696   if (IsTailCall) {
1697     // Each tail call may have to adjust the stack by a different amount, so
1698     // this information must travel along with the operation for eventual
1699     // consumption by emitEpilogue.
1700     Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1701   }
1702
1703   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1704     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1705                                   RegsToPass[i].second.getValueType()));
1706
1707
1708   // Add a register mask operand representing the call-preserved registers. This
1709   // is used later in codegen to constrain register-allocation.
1710   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1711   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1712   assert(Mask && "Missing call preserved mask for calling convention");
1713   Ops.push_back(DAG.getRegisterMask(Mask));
1714
1715   // If we needed glue, put it in as the last argument.
1716   if (InFlag.getNode())
1717     Ops.push_back(InFlag);
1718
1719   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1720
1721   if (IsTailCall) {
1722     return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1723   }
1724
1725   Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1726   InFlag = Chain.getValue(1);
1727
1728   // Now we can reclaim the stack, just as well do it before working out where
1729   // our return value is.
1730   if (!IsSibCall) {
1731     uint64_t CalleePopBytes
1732       = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1733
1734     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1735                                DAG.getIntPtrConstant(CalleePopBytes, true),
1736                                InFlag, dl);
1737     InFlag = Chain.getValue(1);
1738   }
1739
1740   return LowerCallResult(Chain, InFlag, CallConv,
1741                          IsVarArg, Ins, dl, DAG, InVals);
1742 }
1743
1744 SDValue
1745 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1746                                       CallingConv::ID CallConv, bool IsVarArg,
1747                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1748                                       SDLoc dl, SelectionDAG &DAG,
1749                                       SmallVectorImpl<SDValue> &InVals) const {
1750   // Assign locations to each value returned by this call.
1751   SmallVector<CCValAssign, 16> RVLocs;
1752   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1753                  getTargetMachine(), RVLocs, *DAG.getContext());
1754   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1755
1756   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1757     CCValAssign VA = RVLocs[i];
1758
1759     // Return values that are too big to fit into registers should use an sret
1760     // pointer, so this can be a lot simpler than the main argument code.
1761     assert(VA.isRegLoc() && "Memory locations not expected for call return");
1762
1763     SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1764                                      InFlag);
1765     Chain = Val.getValue(1);
1766     InFlag = Val.getValue(2);
1767
1768     switch (VA.getLocInfo()) {
1769     default: llvm_unreachable("Unknown loc info!");
1770     case CCValAssign::Full: break;
1771     case CCValAssign::BCvt:
1772       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1773       break;
1774     case CCValAssign::ZExt:
1775     case CCValAssign::SExt:
1776     case CCValAssign::AExt:
1777       // Floating-point arguments only get extended/truncated if they're going
1778       // in memory, so using the integer operation is acceptable here.
1779       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1780       break;
1781     }
1782
1783     InVals.push_back(Val);
1784   }
1785
1786   return Chain;
1787 }
1788
1789 bool
1790 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1791                                     CallingConv::ID CalleeCC,
1792                                     bool IsVarArg,
1793                                     bool IsCalleeStructRet,
1794                                     bool IsCallerStructRet,
1795                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1796                                     const SmallVectorImpl<SDValue> &OutVals,
1797                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1798                                     SelectionDAG& DAG) const {
1799
1800   // For CallingConv::C this function knows whether the ABI needs
1801   // changing. That's not true for other conventions so they will have to opt in
1802   // manually.
1803   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1804     return false;
1805
1806   const MachineFunction &MF = DAG.getMachineFunction();
1807   const Function *CallerF = MF.getFunction();
1808   CallingConv::ID CallerCC = CallerF->getCallingConv();
1809   bool CCMatch = CallerCC == CalleeCC;
1810
1811   // Byval parameters hand the function a pointer directly into the stack area
1812   // we want to reuse during a tail call. Working around this *is* possible (see
1813   // X86) but less efficient and uglier in LowerCall.
1814   for (Function::const_arg_iterator i = CallerF->arg_begin(),
1815          e = CallerF->arg_end(); i != e; ++i)
1816     if (i->hasByValAttr())
1817       return false;
1818
1819   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1820     if (IsTailCallConvention(CalleeCC) && CCMatch)
1821       return true;
1822     return false;
1823   }
1824
1825   // Now we search for cases where we can use a tail call without changing the
1826   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1827   // concept.
1828
1829   // I want anyone implementing a new calling convention to think long and hard
1830   // about this assert.
1831   assert((!IsVarArg || CalleeCC == CallingConv::C)
1832          && "Unexpected variadic calling convention");
1833
1834   if (IsVarArg && !Outs.empty()) {
1835     // At least two cases here: if caller is fastcc then we can't have any
1836     // memory arguments (we'd be expected to clean up the stack afterwards). If
1837     // caller is C then we could potentially use its argument area.
1838
1839     // FIXME: for now we take the most conservative of these in both cases:
1840     // disallow all variadic memory operands.
1841     SmallVector<CCValAssign, 16> ArgLocs;
1842     CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1843                    getTargetMachine(), ArgLocs, *DAG.getContext());
1844
1845     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1846     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1847       if (!ArgLocs[i].isRegLoc())
1848         return false;
1849   }
1850
1851   // If the calling conventions do not match, then we'd better make sure the
1852   // results are returned in the same way as what the caller expects.
1853   if (!CCMatch) {
1854     SmallVector<CCValAssign, 16> RVLocs1;
1855     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1856                     getTargetMachine(), RVLocs1, *DAG.getContext());
1857     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1858
1859     SmallVector<CCValAssign, 16> RVLocs2;
1860     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1861                     getTargetMachine(), RVLocs2, *DAG.getContext());
1862     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1863
1864     if (RVLocs1.size() != RVLocs2.size())
1865       return false;
1866     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1867       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1868         return false;
1869       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1870         return false;
1871       if (RVLocs1[i].isRegLoc()) {
1872         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1873           return false;
1874       } else {
1875         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1876           return false;
1877       }
1878     }
1879   }
1880
1881   // Nothing more to check if the callee is taking no arguments
1882   if (Outs.empty())
1883     return true;
1884
1885   SmallVector<CCValAssign, 16> ArgLocs;
1886   CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1887                  getTargetMachine(), ArgLocs, *DAG.getContext());
1888
1889   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1890
1891   const AArch64MachineFunctionInfo *FuncInfo
1892     = MF.getInfo<AArch64MachineFunctionInfo>();
1893
1894   // If the stack arguments for this call would fit into our own save area then
1895   // the call can be made tail.
1896   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1897 }
1898
1899 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1900                                                    bool TailCallOpt) const {
1901   return CallCC == CallingConv::Fast && TailCallOpt;
1902 }
1903
1904 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1905   return CallCC == CallingConv::Fast;
1906 }
1907
1908 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1909                                                    SelectionDAG &DAG,
1910                                                    MachineFrameInfo *MFI,
1911                                                    int ClobberedFI) const {
1912   SmallVector<SDValue, 8> ArgChains;
1913   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1914   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1915
1916   // Include the original chain at the beginning of the list. When this is
1917   // used by target LowerCall hooks, this helps legalize find the
1918   // CALLSEQ_BEGIN node.
1919   ArgChains.push_back(Chain);
1920
1921   // Add a chain value for each stack argument corresponding
1922   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1923          UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1924     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1925       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1926         if (FI->getIndex() < 0) {
1927           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1928           int64_t InLastByte = InFirstByte;
1929           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1930
1931           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1932               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1933             ArgChains.push_back(SDValue(L, 1));
1934         }
1935
1936    // Build a tokenfactor for all the chains.
1937    return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1938                       &ArgChains[0], ArgChains.size());
1939 }
1940
1941 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1942   switch (CC) {
1943   case ISD::SETEQ:  return A64CC::EQ;
1944   case ISD::SETGT:  return A64CC::GT;
1945   case ISD::SETGE:  return A64CC::GE;
1946   case ISD::SETLT:  return A64CC::LT;
1947   case ISD::SETLE:  return A64CC::LE;
1948   case ISD::SETNE:  return A64CC::NE;
1949   case ISD::SETUGT: return A64CC::HI;
1950   case ISD::SETUGE: return A64CC::HS;
1951   case ISD::SETULT: return A64CC::LO;
1952   case ISD::SETULE: return A64CC::LS;
1953   default: llvm_unreachable("Unexpected condition code");
1954   }
1955 }
1956
1957 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1958   // icmp is implemented using adds/subs immediate, which take an unsigned
1959   // 12-bit immediate, optionally shifted left by 12 bits.
1960
1961   // Symmetric by using adds/subs
1962   if (Val < 0)
1963     Val = -Val;
1964
1965   return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1966 }
1967
1968 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1969                                         ISD::CondCode CC, SDValue &A64cc,
1970                                         SelectionDAG &DAG, SDLoc &dl) const {
1971   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1972     int64_t C = 0;
1973     EVT VT = RHSC->getValueType(0);
1974     bool knownInvalid = false;
1975
1976     // I'm not convinced the rest of LLVM handles these edge cases properly, but
1977     // we can at least get it right.
1978     if (isSignedIntSetCC(CC)) {
1979       C = RHSC->getSExtValue();
1980     } else if (RHSC->getZExtValue() > INT64_MAX) {
1981       // A 64-bit constant not representable by a signed 64-bit integer is far
1982       // too big to fit into a SUBS immediate anyway.
1983       knownInvalid = true;
1984     } else {
1985       C = RHSC->getZExtValue();
1986     }
1987
1988     if (!knownInvalid && !isLegalICmpImmediate(C)) {
1989       // Constant does not fit, try adjusting it by one?
1990       switch (CC) {
1991       default: break;
1992       case ISD::SETLT:
1993       case ISD::SETGE:
1994         if (isLegalICmpImmediate(C-1)) {
1995           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1996           RHS = DAG.getConstant(C-1, VT);
1997         }
1998         break;
1999       case ISD::SETULT:
2000       case ISD::SETUGE:
2001         if (isLegalICmpImmediate(C-1)) {
2002           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2003           RHS = DAG.getConstant(C-1, VT);
2004         }
2005         break;
2006       case ISD::SETLE:
2007       case ISD::SETGT:
2008         if (isLegalICmpImmediate(C+1)) {
2009           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2010           RHS = DAG.getConstant(C+1, VT);
2011         }
2012         break;
2013       case ISD::SETULE:
2014       case ISD::SETUGT:
2015         if (isLegalICmpImmediate(C+1)) {
2016           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2017           RHS = DAG.getConstant(C+1, VT);
2018         }
2019         break;
2020       }
2021     }
2022   }
2023
2024   A64CC::CondCodes CondCode = IntCCToA64CC(CC);
2025   A64cc = DAG.getConstant(CondCode, MVT::i32);
2026   return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2027                      DAG.getCondCode(CC));
2028 }
2029
2030 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
2031                                     A64CC::CondCodes &Alternative) {
2032   A64CC::CondCodes CondCode = A64CC::Invalid;
2033   Alternative = A64CC::Invalid;
2034
2035   switch (CC) {
2036   default: llvm_unreachable("Unknown FP condition!");
2037   case ISD::SETEQ:
2038   case ISD::SETOEQ: CondCode = A64CC::EQ; break;
2039   case ISD::SETGT:
2040   case ISD::SETOGT: CondCode = A64CC::GT; break;
2041   case ISD::SETGE:
2042   case ISD::SETOGE: CondCode = A64CC::GE; break;
2043   case ISD::SETOLT: CondCode = A64CC::MI; break;
2044   case ISD::SETOLE: CondCode = A64CC::LS; break;
2045   case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
2046   case ISD::SETO:   CondCode = A64CC::VC; break;
2047   case ISD::SETUO:  CondCode = A64CC::VS; break;
2048   case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
2049   case ISD::SETUGT: CondCode = A64CC::HI; break;
2050   case ISD::SETUGE: CondCode = A64CC::PL; break;
2051   case ISD::SETLT:
2052   case ISD::SETULT: CondCode = A64CC::LT; break;
2053   case ISD::SETLE:
2054   case ISD::SETULE: CondCode = A64CC::LE; break;
2055   case ISD::SETNE:
2056   case ISD::SETUNE: CondCode = A64CC::NE; break;
2057   }
2058   return CondCode;
2059 }
2060
2061 SDValue
2062 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
2063   SDLoc DL(Op);
2064   EVT PtrVT = getPointerTy();
2065   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2066
2067   switch(getTargetMachine().getCodeModel()) {
2068   case CodeModel::Small:
2069     // The most efficient code is PC-relative anyway for the small memory model,
2070     // so we don't need to worry about relocation model.
2071     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2072                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
2073                                                  AArch64II::MO_NO_FLAG),
2074                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
2075                                                  AArch64II::MO_LO12),
2076                        DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
2077   case CodeModel::Large:
2078     return DAG.getNode(
2079       AArch64ISD::WrapperLarge, DL, PtrVT,
2080       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
2081       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
2082       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
2083       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
2084   default:
2085     llvm_unreachable("Only small and large code models supported now");
2086   }
2087 }
2088
2089
2090 // (BRCOND chain, val, dest)
2091 SDValue
2092 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2093   SDLoc dl(Op);
2094   SDValue Chain = Op.getOperand(0);
2095   SDValue TheBit = Op.getOperand(1);
2096   SDValue DestBB = Op.getOperand(2);
2097
2098   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2099   // that as the consumer we are responsible for ignoring rubbish in higher
2100   // bits.
2101   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2102                        DAG.getConstant(1, MVT::i32));
2103
2104   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2105                                DAG.getConstant(0, TheBit.getValueType()),
2106                                DAG.getCondCode(ISD::SETNE));
2107
2108   return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
2109                      A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
2110                      DestBB);
2111 }
2112
2113 // (BR_CC chain, condcode, lhs, rhs, dest)
2114 SDValue
2115 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2116   SDLoc dl(Op);
2117   SDValue Chain = Op.getOperand(0);
2118   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2119   SDValue LHS = Op.getOperand(2);
2120   SDValue RHS = Op.getOperand(3);
2121   SDValue DestBB = Op.getOperand(4);
2122
2123   if (LHS.getValueType() == MVT::f128) {
2124     // f128 comparisons are lowered to runtime calls by a routine which sets
2125     // LHS, RHS and CC appropriately for the rest of this function to continue.
2126     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2127
2128     // If softenSetCCOperands returned a scalar, we need to compare the result
2129     // against zero to select between true and false values.
2130     if (RHS.getNode() == 0) {
2131       RHS = DAG.getConstant(0, LHS.getValueType());
2132       CC = ISD::SETNE;
2133     }
2134   }
2135
2136   if (LHS.getValueType().isInteger()) {
2137     SDValue A64cc;
2138
2139     // Integers are handled in a separate function because the combinations of
2140     // immediates and tests can get hairy and we may want to fiddle things.
2141     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2142
2143     return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2144                        Chain, CmpOp, A64cc, DestBB);
2145   }
2146
2147   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2148   // conditional branch, hence FPCCToA64CC can set a second test, where either
2149   // passing is sufficient.
2150   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2151   CondCode = FPCCToA64CC(CC, Alternative);
2152   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2153   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2154                               DAG.getCondCode(CC));
2155   SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2156                                  Chain, SetCC, A64cc, DestBB);
2157
2158   if (Alternative != A64CC::Invalid) {
2159     A64cc = DAG.getConstant(Alternative, MVT::i32);
2160     A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2161                            A64BR_CC, SetCC, A64cc, DestBB);
2162
2163   }
2164
2165   return A64BR_CC;
2166 }
2167
2168 SDValue
2169 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
2170                                        RTLIB::Libcall Call) const {
2171   ArgListTy Args;
2172   ArgListEntry Entry;
2173   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
2174     EVT ArgVT = Op.getOperand(i).getValueType();
2175     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2176     Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
2177     Entry.isSExt = false;
2178     Entry.isZExt = false;
2179     Args.push_back(Entry);
2180   }
2181   SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
2182
2183   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
2184
2185   // By default, the input chain to this libcall is the entry node of the
2186   // function. If the libcall is going to be emitted as a tail call then
2187   // isUsedByReturnOnly will change it to the right chain if the return
2188   // node which is being folded has a non-entry input chain.
2189   SDValue InChain = DAG.getEntryNode();
2190
2191   // isTailCall may be true since the callee does not reference caller stack
2192   // frame. Check if it's in the right position.
2193   SDValue TCChain = InChain;
2194   bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
2195   if (isTailCall)
2196     InChain = TCChain;
2197
2198   TargetLowering::
2199   CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
2200                     0, getLibcallCallingConv(Call), isTailCall,
2201                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2202                     Callee, Args, DAG, SDLoc(Op));
2203   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2204
2205   if (!CallInfo.second.getNode())
2206     // It's a tailcall, return the chain (which is the DAG root).
2207     return DAG.getRoot();
2208
2209   return CallInfo.first;
2210 }
2211
2212 SDValue
2213 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2214   if (Op.getOperand(0).getValueType() != MVT::f128) {
2215     // It's legal except when f128 is involved
2216     return Op;
2217   }
2218
2219   RTLIB::Libcall LC;
2220   LC  = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2221
2222   SDValue SrcVal = Op.getOperand(0);
2223   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
2224                      /*isSigned*/ false, SDLoc(Op)).first;
2225 }
2226
2227 SDValue
2228 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
2229   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2230
2231   RTLIB::Libcall LC;
2232   LC  = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2233
2234   return LowerF128ToCall(Op, DAG, LC);
2235 }
2236
2237 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG,
2238                                     bool IsSigned) {
2239   SDLoc dl(Op);
2240   EVT VT = Op.getValueType();
2241   SDValue Vec = Op.getOperand(0);
2242   EVT OpVT = Vec.getValueType();
2243   unsigned Opc = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
2244
2245   if (VT.getVectorNumElements() == 1) {
2246     assert(OpVT == MVT::v1f64 && "Unexpected vector type!");
2247     if (VT.getSizeInBits() == OpVT.getSizeInBits())
2248       return Op;
2249     return DAG.UnrollVectorOp(Op.getNode());
2250   }
2251
2252   if (VT.getSizeInBits() > OpVT.getSizeInBits()) {
2253     assert(Vec.getValueType() == MVT::v2f32 && VT == MVT::v2i64 &&
2254            "Unexpected vector type!");
2255     Vec = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Vec);
2256     return DAG.getNode(Opc, dl, VT, Vec);
2257   } else if (VT.getSizeInBits() < OpVT.getSizeInBits()) {
2258     EVT CastVT = EVT::getIntegerVT(*DAG.getContext(),
2259                                    OpVT.getVectorElementType().getSizeInBits());
2260     CastVT =
2261         EVT::getVectorVT(*DAG.getContext(), CastVT, VT.getVectorNumElements());
2262     Vec = DAG.getNode(Opc, dl, CastVT, Vec);
2263     return DAG.getNode(ISD::TRUNCATE, dl, VT, Vec);
2264   }
2265   return DAG.getNode(Opc, dl, VT, Vec);
2266 }
2267
2268 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2269   // We custom lower concat_vectors with 4, 8, or 16 operands that are all the
2270   // same operand and of type v1* using the DUP instruction.
2271   unsigned NumOps = Op->getNumOperands();
2272   if (NumOps != 4 && NumOps != 8 && NumOps != 16)
2273     return Op;
2274
2275   // Must be a single value for VDUP.
2276   bool isConstant = true;
2277   SDValue Op0 = Op.getOperand(0);
2278   for (unsigned i = 1; i < NumOps; ++i) {
2279     SDValue OpN = Op.getOperand(i);
2280     if (Op0 != OpN)
2281       return Op;
2282
2283     if (!isa<ConstantSDNode>(OpN->getOperand(0)))
2284       isConstant = false;
2285   }
2286
2287   // Verify the value type.
2288   EVT EltVT = Op0.getValueType();
2289   switch (NumOps) {
2290   default: llvm_unreachable("Unexpected number of operands");
2291   case 4:
2292     if (EltVT != MVT::v1i16 && EltVT != MVT::v1i32)
2293       return Op;
2294     break;
2295   case 8:
2296     if (EltVT != MVT::v1i8 && EltVT != MVT::v1i16)
2297       return Op;
2298     break;
2299   case 16:
2300     if (EltVT != MVT::v1i8)
2301       return Op;
2302     break;
2303   }
2304
2305   SDLoc DL(Op);
2306   EVT VT = Op.getValueType();
2307   // VDUP produces better code for constants.
2308   if (isConstant)
2309     return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Op0->getOperand(0));
2310   return DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, Op0,
2311                      DAG.getConstant(0, MVT::i64));
2312 }
2313
2314 SDValue
2315 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
2316                                       bool IsSigned) const {
2317   if (Op.getValueType().isVector())
2318     return LowerVectorFP_TO_INT(Op, DAG, IsSigned);
2319   if (Op.getOperand(0).getValueType() != MVT::f128) {
2320     // It's legal except when f128 is involved
2321     return Op;
2322   }
2323
2324   RTLIB::Libcall LC;
2325   if (IsSigned)
2326     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2327   else
2328     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2329
2330   return LowerF128ToCall(Op, DAG, LC);
2331 }
2332
2333 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
2334   MachineFunction &MF = DAG.getMachineFunction();
2335   MachineFrameInfo *MFI = MF.getFrameInfo();
2336   MFI->setReturnAddressIsTaken(true);
2337
2338   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2339     return SDValue();
2340
2341   EVT VT = Op.getValueType();
2342   SDLoc dl(Op);
2343   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2344   if (Depth) {
2345     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
2346     SDValue Offset = DAG.getConstant(8, MVT::i64);
2347     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
2348                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
2349                        MachinePointerInfo(), false, false, false, 0);
2350   }
2351
2352   // Return X30, which contains the return address. Mark it an implicit live-in.
2353   unsigned Reg = MF.addLiveIn(AArch64::X30, getRegClassFor(MVT::i64));
2354   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, MVT::i64);
2355 }
2356
2357
2358 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG)
2359                                               const {
2360   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2361   MFI->setFrameAddressIsTaken(true);
2362
2363   EVT VT = Op.getValueType();
2364   SDLoc dl(Op);
2365   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2366   unsigned FrameReg = AArch64::X29;
2367   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2368   while (Depth--)
2369     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
2370                             MachinePointerInfo(),
2371                             false, false, false, 0);
2372   return FrameAddr;
2373 }
2374
2375 SDValue
2376 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
2377                                                   SelectionDAG &DAG) const {
2378   assert(getTargetMachine().getCodeModel() == CodeModel::Large);
2379   assert(getTargetMachine().getRelocationModel() == Reloc::Static);
2380
2381   EVT PtrVT = getPointerTy();
2382   SDLoc dl(Op);
2383   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2384   const GlobalValue *GV = GN->getGlobal();
2385
2386   SDValue GlobalAddr = DAG.getNode(
2387       AArch64ISD::WrapperLarge, dl, PtrVT,
2388       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
2389       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
2390       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
2391       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
2392
2393   if (GN->getOffset() != 0)
2394     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2395                        DAG.getConstant(GN->getOffset(), PtrVT));
2396
2397   return GlobalAddr;
2398 }
2399
2400 SDValue
2401 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
2402                                                   SelectionDAG &DAG) const {
2403   assert(getTargetMachine().getCodeModel() == CodeModel::Small);
2404
2405   EVT PtrVT = getPointerTy();
2406   SDLoc dl(Op);
2407   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2408   const GlobalValue *GV = GN->getGlobal();
2409   unsigned Alignment = GV->getAlignment();
2410   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2411   if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
2412     // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
2413     // to zero when they remain undefined. In PIC mode the GOT can take care of
2414     // this, but in absolute mode we use a constant pool load.
2415     SDValue PoolAddr;
2416     PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2417                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2418                                                      AArch64II::MO_NO_FLAG),
2419                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2420                                                      AArch64II::MO_LO12),
2421                            DAG.getConstant(8, MVT::i32));
2422     SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
2423                                      MachinePointerInfo::getConstantPool(),
2424                                      /*isVolatile=*/ false,
2425                                      /*isNonTemporal=*/ true,
2426                                      /*isInvariant=*/ true, 8);
2427     if (GN->getOffset() != 0)
2428       return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2429                          DAG.getConstant(GN->getOffset(), PtrVT));
2430
2431     return GlobalAddr;
2432   }
2433
2434   if (Alignment == 0) {
2435     const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2436     if (GVPtrTy->getElementType()->isSized()) {
2437       Alignment
2438         = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2439     } else {
2440       // Be conservative if we can't guess, not that it really matters:
2441       // functions and labels aren't valid for loads, and the methods used to
2442       // actually calculate an address work with any alignment.
2443       Alignment = 1;
2444     }
2445   }
2446
2447   unsigned char HiFixup, LoFixup;
2448   bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2449
2450   if (UseGOT) {
2451     HiFixup = AArch64II::MO_GOT;
2452     LoFixup = AArch64II::MO_GOT_LO12;
2453     Alignment = 8;
2454   } else {
2455     HiFixup = AArch64II::MO_NO_FLAG;
2456     LoFixup = AArch64II::MO_LO12;
2457   }
2458
2459   // AArch64's small model demands the following sequence:
2460   // ADRP x0, somewhere
2461   // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2462   SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2463                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2464                                                              HiFixup),
2465                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2466                                                              LoFixup),
2467                                   DAG.getConstant(Alignment, MVT::i32));
2468
2469   if (UseGOT) {
2470     GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2471                             GlobalRef);
2472   }
2473
2474   if (GN->getOffset() != 0)
2475     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2476                        DAG.getConstant(GN->getOffset(), PtrVT));
2477
2478   return GlobalRef;
2479 }
2480
2481 SDValue
2482 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2483                                              SelectionDAG &DAG) const {
2484   // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2485   // we make those distinctions here.
2486
2487   switch (getTargetMachine().getCodeModel()) {
2488   case CodeModel::Small:
2489     return LowerGlobalAddressELFSmall(Op, DAG);
2490   case CodeModel::Large:
2491     return LowerGlobalAddressELFLarge(Op, DAG);
2492   default:
2493     llvm_unreachable("Only small and large code models supported now");
2494   }
2495 }
2496
2497 SDValue
2498 AArch64TargetLowering::LowerConstantPool(SDValue Op,
2499                                          SelectionDAG &DAG) const {
2500   SDLoc DL(Op);
2501   EVT PtrVT = getPointerTy();
2502   ConstantPoolSDNode *CN = cast<ConstantPoolSDNode>(Op);
2503   const Constant *C = CN->getConstVal();
2504
2505   switch(getTargetMachine().getCodeModel()) {
2506   case CodeModel::Small:
2507     // The most efficient code is PC-relative anyway for the small memory model,
2508     // so we don't need to worry about relocation model.
2509     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2510                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2511                                                  AArch64II::MO_NO_FLAG),
2512                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2513                                                  AArch64II::MO_LO12),
2514                        DAG.getConstant(CN->getAlignment(), MVT::i32));
2515   case CodeModel::Large:
2516     return DAG.getNode(
2517       AArch64ISD::WrapperLarge, DL, PtrVT,
2518       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G3),
2519       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G2_NC),
2520       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G1_NC),
2521       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G0_NC));
2522   default:
2523     llvm_unreachable("Only small and large code models supported now");
2524   }
2525 }
2526
2527 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2528                                                 SDValue DescAddr,
2529                                                 SDLoc DL,
2530                                                 SelectionDAG &DAG) const {
2531   EVT PtrVT = getPointerTy();
2532
2533   // The function we need to call is simply the first entry in the GOT for this
2534   // descriptor, load it in preparation.
2535   SDValue Func, Chain;
2536   Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2537                      DescAddr);
2538
2539   // The function takes only one argument: the address of the descriptor itself
2540   // in X0.
2541   SDValue Glue;
2542   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2543   Glue = Chain.getValue(1);
2544
2545   // Finally, there's a special calling-convention which means that the lookup
2546   // must preserve all registers (except X0, obviously).
2547   const TargetRegisterInfo *TRI  = getTargetMachine().getRegisterInfo();
2548   const AArch64RegisterInfo *A64RI
2549     = static_cast<const AArch64RegisterInfo *>(TRI);
2550   const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2551
2552   // We're now ready to populate the argument list, as with a normal call:
2553   std::vector<SDValue> Ops;
2554   Ops.push_back(Chain);
2555   Ops.push_back(Func);
2556   Ops.push_back(SymAddr);
2557   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2558   Ops.push_back(DAG.getRegisterMask(Mask));
2559   Ops.push_back(Glue);
2560
2561   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2562   Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2563                       Ops.size());
2564   Glue = Chain.getValue(1);
2565
2566   // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2567   // back to the generic handling code.
2568   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2569 }
2570
2571 SDValue
2572 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2573                                              SelectionDAG &DAG) const {
2574   assert(getSubtarget()->isTargetELF() &&
2575          "TLS not implemented for non-ELF targets");
2576   assert(getTargetMachine().getCodeModel() == CodeModel::Small
2577          && "TLS only supported in small memory model");
2578   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2579
2580   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2581
2582   SDValue TPOff;
2583   EVT PtrVT = getPointerTy();
2584   SDLoc DL(Op);
2585   const GlobalValue *GV = GA->getGlobal();
2586
2587   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2588
2589   if (Model == TLSModel::InitialExec) {
2590     TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2591                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2592                                                    AArch64II::MO_GOTTPREL),
2593                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2594                                                    AArch64II::MO_GOTTPREL_LO12),
2595                         DAG.getConstant(8, MVT::i32));
2596     TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2597                         TPOff);
2598   } else if (Model == TLSModel::LocalExec) {
2599     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2600                                                AArch64II::MO_TPREL_G1);
2601     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2602                                                AArch64II::MO_TPREL_G0_NC);
2603
2604     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2605                                        DAG.getTargetConstant(1, MVT::i32)), 0);
2606     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2607                                        TPOff, LoVar,
2608                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2609   } else if (Model == TLSModel::GeneralDynamic) {
2610     // Accesses used in this sequence go via the TLS descriptor which lives in
2611     // the GOT. Prepare an address we can use to handle this.
2612     SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2613                                                 AArch64II::MO_TLSDESC);
2614     SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2615                                                 AArch64II::MO_TLSDESC_LO12);
2616     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2617                                    HiDesc, LoDesc,
2618                                    DAG.getConstant(8, MVT::i32));
2619     SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2620
2621     TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2622   } else if (Model == TLSModel::LocalDynamic) {
2623     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2624     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2625     // the beginning of the module's TLS region, followed by a DTPREL offset
2626     // calculation.
2627
2628     // These accesses will need deduplicating if there's more than one.
2629     AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2630       .getInfo<AArch64MachineFunctionInfo>();
2631     MFI->incNumLocalDynamicTLSAccesses();
2632
2633
2634     // Get the location of _TLS_MODULE_BASE_:
2635     SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2636                                                 AArch64II::MO_TLSDESC);
2637     SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2638                                                 AArch64II::MO_TLSDESC_LO12);
2639     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2640                                    HiDesc, LoDesc,
2641                                    DAG.getConstant(8, MVT::i32));
2642     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2643
2644     ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2645
2646     // Get the variable's offset from _TLS_MODULE_BASE_
2647     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2648                                                AArch64II::MO_DTPREL_G1);
2649     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2650                                                AArch64II::MO_DTPREL_G0_NC);
2651
2652     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2653                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2654     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2655                                        TPOff, LoVar,
2656                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2657   } else
2658       llvm_unreachable("Unsupported TLS access model");
2659
2660
2661   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2662 }
2663
2664 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2665                                     bool IsSigned) {
2666   SDLoc dl(Op);
2667   EVT VT = Op.getValueType();
2668   SDValue Vec = Op.getOperand(0);
2669   unsigned Opc = IsSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
2670
2671   if (VT.getVectorNumElements() == 1) {
2672     assert(VT == MVT::v1f64 && "Unexpected vector type!");
2673     if (VT.getSizeInBits() == Vec.getValueSizeInBits())
2674       return Op;
2675     return DAG.UnrollVectorOp(Op.getNode());
2676   }
2677
2678   if (VT.getSizeInBits() < Vec.getValueSizeInBits()) {
2679     assert(Vec.getValueType() == MVT::v2i64 && VT == MVT::v2f32 &&
2680            "Unexpected vector type!");
2681     Vec = DAG.getNode(Opc, dl, MVT::v2f64, Vec);
2682     return DAG.getNode(ISD::FP_ROUND, dl, VT, Vec, DAG.getIntPtrConstant(0));
2683   } else if (VT.getSizeInBits() > Vec.getValueSizeInBits()) {
2684     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2685     EVT CastVT = EVT::getIntegerVT(*DAG.getContext(),
2686                                    VT.getVectorElementType().getSizeInBits());
2687     CastVT =
2688         EVT::getVectorVT(*DAG.getContext(), CastVT, VT.getVectorNumElements());
2689     Vec = DAG.getNode(CastOpc, dl, CastVT, Vec);
2690   }
2691
2692   return DAG.getNode(Opc, dl, VT, Vec);
2693 }
2694
2695 SDValue
2696 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2697                                       bool IsSigned) const {
2698   if (Op.getValueType().isVector())
2699     return LowerVectorINT_TO_FP(Op, DAG, IsSigned);
2700   if (Op.getValueType() != MVT::f128) {
2701     // Legal for everything except f128.
2702     return Op;
2703   }
2704
2705   RTLIB::Libcall LC;
2706   if (IsSigned)
2707     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2708   else
2709     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2710
2711   return LowerF128ToCall(Op, DAG, LC);
2712 }
2713
2714
2715 SDValue
2716 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2717   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2718   SDLoc dl(JT);
2719   EVT PtrVT = getPointerTy();
2720
2721   // When compiling PIC, jump tables get put in the code section so a static
2722   // relocation-style is acceptable for both cases.
2723   switch (getTargetMachine().getCodeModel()) {
2724   case CodeModel::Small:
2725     return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2726                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2727                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2728                                               AArch64II::MO_LO12),
2729                        DAG.getConstant(1, MVT::i32));
2730   case CodeModel::Large:
2731     return DAG.getNode(
2732       AArch64ISD::WrapperLarge, dl, PtrVT,
2733       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2734       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2735       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2736       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2737   default:
2738     llvm_unreachable("Only small and large code models supported now");
2739   }
2740 }
2741
2742 // (SELECT testbit, iftrue, iffalse)
2743 SDValue
2744 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2745   SDLoc dl(Op);
2746   SDValue TheBit = Op.getOperand(0);
2747   SDValue IfTrue = Op.getOperand(1);
2748   SDValue IfFalse = Op.getOperand(2);
2749
2750   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2751   // that as the consumer we are responsible for ignoring rubbish in higher
2752   // bits.
2753   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2754                        DAG.getConstant(1, MVT::i32));
2755   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2756                                DAG.getConstant(0, TheBit.getValueType()),
2757                                DAG.getCondCode(ISD::SETNE));
2758
2759   return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2760                      A64CMP, IfTrue, IfFalse,
2761                      DAG.getConstant(A64CC::NE, MVT::i32));
2762 }
2763
2764 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2765   SDLoc DL(Op);
2766   SDValue LHS = Op.getOperand(0);
2767   SDValue RHS = Op.getOperand(1);
2768   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2769   EVT VT = Op.getValueType();
2770   bool Invert = false;
2771   SDValue Op0, Op1;
2772   unsigned Opcode;
2773
2774   if (LHS.getValueType().isInteger()) {
2775
2776     // Attempt to use Vector Integer Compare Mask Test instruction.
2777     // TST = icmp ne (and (op0, op1), zero).
2778     if (CC == ISD::SETNE) {
2779       if (((LHS.getOpcode() == ISD::AND) &&
2780            ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2781           ((RHS.getOpcode() == ISD::AND) &&
2782            ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2783
2784         SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2785         SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2786         SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2787         return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2788       }
2789     }
2790
2791     // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2792     // Note: Compare against Zero does not support unsigned predicates.
2793     if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2794          ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2795         !isUnsignedIntSetCC(CC)) {
2796
2797       // If LHS is the zero value, swap operands and CondCode.
2798       if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2799         CC = getSetCCSwappedOperands(CC);
2800         Op0 = RHS;
2801       } else
2802         Op0 = LHS;
2803
2804       // Ensure valid CondCode for Compare Mask against Zero instruction:
2805       // EQ, GE, GT, LE, LT.
2806       if (ISD::SETNE == CC) {
2807         Invert = true;
2808         CC = ISD::SETEQ;
2809       }
2810
2811       // Using constant type to differentiate integer and FP compares with zero.
2812       Op1 = DAG.getConstant(0, MVT::i32);
2813       Opcode = AArch64ISD::NEON_CMPZ;
2814
2815     } else {
2816       // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2817       // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2818       bool Swap = false;
2819       switch (CC) {
2820       default:
2821         llvm_unreachable("Illegal integer comparison.");
2822       case ISD::SETEQ:
2823       case ISD::SETGT:
2824       case ISD::SETGE:
2825       case ISD::SETUGT:
2826       case ISD::SETUGE:
2827         break;
2828       case ISD::SETNE:
2829         Invert = true;
2830         CC = ISD::SETEQ;
2831         break;
2832       case ISD::SETULT:
2833       case ISD::SETULE:
2834       case ISD::SETLT:
2835       case ISD::SETLE:
2836         Swap = true;
2837         CC = getSetCCSwappedOperands(CC);
2838       }
2839
2840       if (Swap)
2841         std::swap(LHS, RHS);
2842
2843       Opcode = AArch64ISD::NEON_CMP;
2844       Op0 = LHS;
2845       Op1 = RHS;
2846     }
2847
2848     // Generate Compare Mask instr or Compare Mask against Zero instr.
2849     SDValue NeonCmp =
2850         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2851
2852     if (Invert)
2853       NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2854
2855     return NeonCmp;
2856   }
2857
2858   // Now handle Floating Point cases.
2859   // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2860   if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2861       ISD::isBuildVectorAllZeros(LHS.getNode())) {
2862
2863     // If LHS is the zero value, swap operands and CondCode.
2864     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2865       CC = getSetCCSwappedOperands(CC);
2866       Op0 = RHS;
2867     } else
2868       Op0 = LHS;
2869
2870     // Using constant type to differentiate integer and FP compares with zero.
2871     Op1 = DAG.getConstantFP(0, MVT::f32);
2872     Opcode = AArch64ISD::NEON_CMPZ;
2873   } else {
2874     // Attempt to use Vector Floating Point Compare Mask instruction.
2875     Op0 = LHS;
2876     Op1 = RHS;
2877     Opcode = AArch64ISD::NEON_CMP;
2878   }
2879
2880   SDValue NeonCmpAlt;
2881   // Some register compares have to be implemented with swapped CC and operands,
2882   // e.g.: OLT implemented as OGT with swapped operands.
2883   bool SwapIfRegArgs = false;
2884
2885   // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2886   // EQ, GE, GT, LE, LT.
2887   // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2888   switch (CC) {
2889   default:
2890     llvm_unreachable("Illegal FP comparison");
2891   case ISD::SETUNE:
2892   case ISD::SETNE:
2893     Invert = true; // Fallthrough
2894   case ISD::SETOEQ:
2895   case ISD::SETEQ:
2896     CC = ISD::SETEQ;
2897     break;
2898   case ISD::SETOLT:
2899   case ISD::SETLT:
2900     CC = ISD::SETLT;
2901     SwapIfRegArgs = true;
2902     break;
2903   case ISD::SETOGT:
2904   case ISD::SETGT:
2905     CC = ISD::SETGT;
2906     break;
2907   case ISD::SETOLE:
2908   case ISD::SETLE:
2909     CC = ISD::SETLE;
2910     SwapIfRegArgs = true;
2911     break;
2912   case ISD::SETOGE:
2913   case ISD::SETGE:
2914     CC = ISD::SETGE;
2915     break;
2916   case ISD::SETUGE:
2917     Invert = true;
2918     CC = ISD::SETLT;
2919     SwapIfRegArgs = true;
2920     break;
2921   case ISD::SETULE:
2922     Invert = true;
2923     CC = ISD::SETGT;
2924     break;
2925   case ISD::SETUGT:
2926     Invert = true;
2927     CC = ISD::SETLE;
2928     SwapIfRegArgs = true;
2929     break;
2930   case ISD::SETULT:
2931     Invert = true;
2932     CC = ISD::SETGE;
2933     break;
2934   case ISD::SETUEQ:
2935     Invert = true; // Fallthrough
2936   case ISD::SETONE:
2937     // Expand this to (OGT |OLT).
2938     NeonCmpAlt =
2939         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2940     CC = ISD::SETLT;
2941     SwapIfRegArgs = true;
2942     break;
2943   case ISD::SETUO:
2944     Invert = true; // Fallthrough
2945   case ISD::SETO:
2946     // Expand this to (OGE | OLT).
2947     NeonCmpAlt =
2948         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2949     CC = ISD::SETLT;
2950     SwapIfRegArgs = true;
2951     break;
2952   }
2953
2954   if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2955     CC = getSetCCSwappedOperands(CC);
2956     std::swap(Op0, Op1);
2957   }
2958
2959   // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2960   SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2961
2962   if (NeonCmpAlt.getNode())
2963     NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2964
2965   if (Invert)
2966     NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2967
2968   return NeonCmp;
2969 }
2970
2971 // (SETCC lhs, rhs, condcode)
2972 SDValue
2973 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2974   SDLoc dl(Op);
2975   SDValue LHS = Op.getOperand(0);
2976   SDValue RHS = Op.getOperand(1);
2977   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2978   EVT VT = Op.getValueType();
2979
2980   if (VT.isVector())
2981     return LowerVectorSETCC(Op, DAG);
2982
2983   if (LHS.getValueType() == MVT::f128) {
2984     // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2985     // for the rest of the function (some i32 or i64 values).
2986     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2987
2988     // If softenSetCCOperands returned a scalar, use it.
2989     if (RHS.getNode() == 0) {
2990       assert(LHS.getValueType() == Op.getValueType() &&
2991              "Unexpected setcc expansion!");
2992       return LHS;
2993     }
2994   }
2995
2996   if (LHS.getValueType().isInteger()) {
2997     SDValue A64cc;
2998
2999     // Integers are handled in a separate function because the combinations of
3000     // immediates and tests can get hairy and we may want to fiddle things.
3001     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
3002
3003     return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
3004                        CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3005                        A64cc);
3006   }
3007
3008   // Note that some LLVM floating-point CondCodes can't be lowered to a single
3009   // conditional branch, hence FPCCToA64CC can set a second test, where either
3010   // passing is sufficient.
3011   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3012   CondCode = FPCCToA64CC(CC, Alternative);
3013   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3014   SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3015                               DAG.getCondCode(CC));
3016   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
3017                                      CmpOp, DAG.getConstant(1, VT),
3018                                      DAG.getConstant(0, VT), A64cc);
3019
3020   if (Alternative != A64CC::Invalid) {
3021     A64cc = DAG.getConstant(Alternative, MVT::i32);
3022     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
3023                                DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
3024   }
3025
3026   return A64SELECT_CC;
3027 }
3028
3029 static SDValue LowerVectorSELECT_CC(SDValue Op, SelectionDAG &DAG) {
3030   SDLoc dl(Op);
3031   SDValue LHS = Op.getOperand(0);
3032   SDValue RHS = Op.getOperand(1);
3033   SDValue IfTrue = Op.getOperand(2);
3034   SDValue IfFalse = Op.getOperand(3);
3035   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3036
3037   // If LHS & RHS are floating point and IfTrue & IfFalse are vectors, we will
3038   // use NEON compare.
3039   if ((LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64)) {
3040     EVT EltVT = LHS.getValueType();
3041     unsigned EltNum = 128 / EltVT.getSizeInBits();
3042     EVT VT = EVT::getVectorVT(*DAG.getContext(), EltVT, EltNum);
3043     unsigned SubConstant =
3044         (LHS.getValueType() == MVT::f32) ? AArch64::sub_32 :AArch64::sub_64;
3045     EVT CEltT = (LHS.getValueType() == MVT::f32) ? MVT::i32 : MVT::i64;
3046     EVT CVT = EVT::getVectorVT(*DAG.getContext(), CEltT, EltNum);
3047
3048     LHS
3049       = SDValue(DAG.getMachineNode(TargetOpcode::SUBREG_TO_REG, dl,
3050                   VT, DAG.getTargetConstant(0, MVT::i32), LHS,
3051                   DAG.getTargetConstant(SubConstant, MVT::i32)), 0);
3052     RHS
3053       = SDValue(DAG.getMachineNode(TargetOpcode::SUBREG_TO_REG, dl,
3054                   VT, DAG.getTargetConstant(0, MVT::i32), RHS,
3055                   DAG.getTargetConstant(SubConstant, MVT::i32)), 0);
3056
3057     SDValue VSetCC = DAG.getSetCC(dl, CVT, LHS, RHS, CC);
3058     SDValue ResCC = LowerVectorSETCC(VSetCC, DAG);
3059     EVT IfTrueVT = IfTrue.getValueType();
3060     EVT CastEltT =
3061         MVT::getIntegerVT(IfTrueVT.getVectorElementType().getSizeInBits());
3062     EVT CastVT = EVT::getVectorVT(*DAG.getContext(), CastEltT,
3063                                   IfTrueVT.getVectorNumElements());
3064     if (CEltT.getSizeInBits() < IfTrueVT.getSizeInBits()) {
3065       EVT DUPVT =
3066           EVT::getVectorVT(*DAG.getContext(), CEltT,
3067                            IfTrueVT.getSizeInBits() / CEltT.getSizeInBits());
3068       ResCC = DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, DUPVT, ResCC,
3069                           DAG.getConstant(0, MVT::i64, false));
3070
3071       ResCC = DAG.getNode(ISD::BITCAST, dl, CastVT, ResCC);
3072     } else {
3073       // FIXME: If IfTrue & IfFalse hold v1i8, v1i16 or v1i32, this function
3074       // can't handle them and will hit this assert.
3075       assert(CEltT.getSizeInBits() == IfTrueVT.getSizeInBits() &&
3076              "Vector of IfTrue & IfFalse is too small.");
3077
3078       unsigned ExEltNum =
3079           EltNum * IfTrueVT.getSizeInBits() / ResCC.getValueSizeInBits();
3080       EVT ExVT = EVT::getVectorVT(*DAG.getContext(), CEltT, ExEltNum);
3081       ResCC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ExVT, ResCC,
3082                           DAG.getConstant(0, MVT::i64, false));
3083       ResCC = DAG.getNode(ISD::BITCAST, dl, CastVT, ResCC);
3084     }
3085     SDValue VSelect = DAG.getNode(ISD::VSELECT, dl, IfTrue.getValueType(),
3086                                   ResCC, IfTrue, IfFalse);
3087     return VSelect;
3088   }
3089
3090   // Here we handle the case that LHS & RHS are integer and IfTrue & IfFalse are
3091   // vectors.
3092   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3093   CondCode = FPCCToA64CC(CC, Alternative);
3094   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3095   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3096                               DAG.getCondCode(CC));
3097   EVT SEVT = MVT::i32;
3098   if (IfTrue.getValueType().getVectorElementType().getSizeInBits() > 32)
3099     SEVT = MVT::i64;
3100   SDValue AllOne = DAG.getConstant(-1, SEVT);
3101   SDValue AllZero = DAG.getConstant(0, SEVT);
3102   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, SEVT, SetCC,
3103                                      AllOne, AllZero, A64cc);
3104
3105   if (Alternative != A64CC::Invalid) {
3106     A64cc = DAG.getConstant(Alternative, MVT::i32);
3107     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
3108                                SetCC, AllOne, A64SELECT_CC, A64cc);
3109   }
3110   SDValue VDup;
3111   if (IfTrue.getValueType().getVectorNumElements() == 1)
3112     VDup = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, IfTrue.getValueType(),
3113                        A64SELECT_CC);
3114   else
3115     VDup = DAG.getNode(AArch64ISD::NEON_VDUP, dl, IfTrue.getValueType(),
3116                        A64SELECT_CC);
3117   SDValue VSelect = DAG.getNode(ISD::VSELECT, dl, IfTrue.getValueType(),
3118                                 VDup, IfTrue, IfFalse);
3119   return VSelect;
3120 }
3121
3122 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
3123 SDValue
3124 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3125   SDLoc dl(Op);
3126   SDValue LHS = Op.getOperand(0);
3127   SDValue RHS = Op.getOperand(1);
3128   SDValue IfTrue = Op.getOperand(2);
3129   SDValue IfFalse = Op.getOperand(3);
3130   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3131
3132   if (IfTrue.getValueType().isVector())
3133     return LowerVectorSELECT_CC(Op, DAG);
3134
3135   if (LHS.getValueType() == MVT::f128) {
3136     // f128 comparisons are lowered to libcalls, but slot in nicely here
3137     // afterwards.
3138     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3139
3140     // If softenSetCCOperands returned a scalar, we need to compare the result
3141     // against zero to select between true and false values.
3142     if (RHS.getNode() == 0) {
3143       RHS = DAG.getConstant(0, LHS.getValueType());
3144       CC = ISD::SETNE;
3145     }
3146   }
3147
3148   if (LHS.getValueType().isInteger()) {
3149     SDValue A64cc;
3150
3151     // Integers are handled in a separate function because the combinations of
3152     // immediates and tests can get hairy and we may want to fiddle things.
3153     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
3154
3155     return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(), CmpOp,
3156                        IfTrue, IfFalse, A64cc);
3157   }
3158
3159   // Note that some LLVM floating-point CondCodes can't be lowered to a single
3160   // conditional branch, hence FPCCToA64CC can set a second test, where either
3161   // passing is sufficient.
3162   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3163   CondCode = FPCCToA64CC(CC, Alternative);
3164   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3165   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3166                               DAG.getCondCode(CC));
3167   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
3168                                      Op.getValueType(),
3169                                      SetCC, IfTrue, IfFalse, A64cc);
3170
3171   if (Alternative != A64CC::Invalid) {
3172     A64cc = DAG.getConstant(Alternative, MVT::i32);
3173     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
3174                                SetCC, IfTrue, A64SELECT_CC, A64cc);
3175
3176   }
3177
3178   return A64SELECT_CC;
3179 }
3180
3181 SDValue
3182 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3183   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3184   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3185
3186   // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
3187   // rather than just 8.
3188   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
3189                        Op.getOperand(1), Op.getOperand(2),
3190                        DAG.getConstant(32, MVT::i32), 8, false, false,
3191                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
3192 }
3193
3194 SDValue
3195 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3196   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3197   // Standard, section B.3.
3198   MachineFunction &MF = DAG.getMachineFunction();
3199   AArch64MachineFunctionInfo *FuncInfo
3200     = MF.getInfo<AArch64MachineFunctionInfo>();
3201   SDLoc DL(Op);
3202
3203   SDValue Chain = Op.getOperand(0);
3204   SDValue VAList = Op.getOperand(1);
3205   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3206   SmallVector<SDValue, 4> MemOps;
3207
3208   // void *__stack at offset 0
3209   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
3210                                     getPointerTy());
3211   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3212                                 MachinePointerInfo(SV), false, false, 0));
3213
3214   // void *__gr_top at offset 8
3215   int GPRSize = FuncInfo->getVariadicGPRSize();
3216   if (GPRSize > 0) {
3217     SDValue GRTop, GRTopAddr;
3218
3219     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3220                             DAG.getConstant(8, getPointerTy()));
3221
3222     GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
3223     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3224                         DAG.getConstant(GPRSize, getPointerTy()));
3225
3226     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3227                                   MachinePointerInfo(SV, 8),
3228                                   false, false, 0));
3229   }
3230
3231   // void *__vr_top at offset 16
3232   int FPRSize = FuncInfo->getVariadicFPRSize();
3233   if (FPRSize > 0) {
3234     SDValue VRTop, VRTopAddr;
3235     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3236                             DAG.getConstant(16, getPointerTy()));
3237
3238     VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
3239     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3240                         DAG.getConstant(FPRSize, getPointerTy()));
3241
3242     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3243                                   MachinePointerInfo(SV, 16),
3244                                   false, false, 0));
3245   }
3246
3247   // int __gr_offs at offset 24
3248   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3249                                    DAG.getConstant(24, getPointerTy()));
3250   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3251                                 GROffsAddr, MachinePointerInfo(SV, 24),
3252                                 false, false, 0));
3253
3254   // int __vr_offs at offset 28
3255   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3256                                    DAG.getConstant(28, getPointerTy()));
3257   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3258                                 VROffsAddr, MachinePointerInfo(SV, 28),
3259                                 false, false, 0));
3260
3261   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3262                      MemOps.size());
3263 }
3264
3265 SDValue
3266 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3267   switch (Op.getOpcode()) {
3268   default: llvm_unreachable("Don't know how to custom lower this!");
3269   case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
3270   case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
3271   case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
3272   case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
3273   case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
3274   case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
3275   case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
3276   case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
3277   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
3278   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
3279   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
3280   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
3281
3282   case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
3283   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3284   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
3285   case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
3286   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3287   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
3288   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3289   case ISD::SELECT: return LowerSELECT(Op, DAG);
3290   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
3291   case ISD::SETCC: return LowerSETCC(Op, DAG);
3292   case ISD::VACOPY: return LowerVACOPY(Op, DAG);
3293   case ISD::VASTART: return LowerVASTART(Op, DAG);
3294   case ISD::BUILD_VECTOR:
3295     return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
3296   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3297   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3298   }
3299
3300   return SDValue();
3301 }
3302
3303 /// Check if the specified splat value corresponds to a valid vector constant
3304 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI).  If
3305 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
3306 /// values.
3307 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3308                               unsigned SplatBitSize, SelectionDAG &DAG,
3309                               bool is128Bits, NeonModImmType type, EVT &VT,
3310                               unsigned &Imm, unsigned &OpCmode) {
3311   switch (SplatBitSize) {
3312   default:
3313     llvm_unreachable("unexpected size for isNeonModifiedImm");
3314   case 8: {
3315     if (type != Neon_Mov_Imm)
3316       return false;
3317     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3318     // Neon movi per byte: Op=0, Cmode=1110.
3319     OpCmode = 0xe;
3320     Imm = SplatBits;
3321     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3322     break;
3323   }
3324   case 16: {
3325     // Neon move inst per halfword
3326     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3327     if ((SplatBits & ~0xff) == 0) {
3328       // Value = 0x00nn is 0x00nn LSL 0
3329       // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
3330       // bic:  Op=1, Cmode=1001;  orr:  Op=0, Cmode=1001
3331       // Op=x, Cmode=100y
3332       Imm = SplatBits;
3333       OpCmode = 0x8;
3334       break;
3335     }
3336     if ((SplatBits & ~0xff00) == 0) {
3337       // Value = 0xnn00 is 0x00nn LSL 8
3338       // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
3339       // bic:  Op=1, Cmode=1011;  orr:  Op=0, Cmode=1011
3340       // Op=x, Cmode=101x
3341       Imm = SplatBits >> 8;
3342       OpCmode = 0xa;
3343       break;
3344     }
3345     // can't handle any other
3346     return false;
3347   }
3348
3349   case 32: {
3350     // First the LSL variants (MSL is unusable by some interested instructions).
3351
3352     // Neon move instr per word, shift zeros
3353     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3354     if ((SplatBits & ~0xff) == 0) {
3355       // Value = 0x000000nn is 0x000000nn LSL 0
3356       // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
3357       // bic:  Op=1, Cmode= 0001; orr:  Op=0, Cmode= 0001
3358       // Op=x, Cmode=000x
3359       Imm = SplatBits;
3360       OpCmode = 0;
3361       break;
3362     }
3363     if ((SplatBits & ~0xff00) == 0) {
3364       // Value = 0x0000nn00 is 0x000000nn LSL 8
3365       // movi: Op=0, Cmode= 0010;  mvni: Op=1, Cmode= 0010
3366       // bic:  Op=1, Cmode= 0011;  orr : Op=0, Cmode= 0011
3367       // Op=x, Cmode=001x
3368       Imm = SplatBits >> 8;
3369       OpCmode = 0x2;
3370       break;
3371     }
3372     if ((SplatBits & ~0xff0000) == 0) {
3373       // Value = 0x00nn0000 is 0x000000nn LSL 16
3374       // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
3375       // bic:  Op=1, Cmode= 0101; orr:  Op=0, Cmode= 0101
3376       // Op=x, Cmode=010x
3377       Imm = SplatBits >> 16;
3378       OpCmode = 0x4;
3379       break;
3380     }
3381     if ((SplatBits & ~0xff000000) == 0) {
3382       // Value = 0xnn000000 is 0x000000nn LSL 24
3383       // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
3384       // bic:  Op=1, Cmode= 0111; orr:  Op=0, Cmode= 0111
3385       // Op=x, Cmode=011x
3386       Imm = SplatBits >> 24;
3387       OpCmode = 0x6;
3388       break;
3389     }
3390
3391     // Now the MSL immediates.
3392
3393     // Neon move instr per word, shift ones
3394     if ((SplatBits & ~0xffff) == 0 &&
3395         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3396       // Value = 0x0000nnff is 0x000000nn MSL 8
3397       // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
3398       // Op=x, Cmode=1100
3399       Imm = SplatBits >> 8;
3400       OpCmode = 0xc;
3401       break;
3402     }
3403     if ((SplatBits & ~0xffffff) == 0 &&
3404         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3405       // Value = 0x00nnffff is 0x000000nn MSL 16
3406       // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
3407       // Op=x, Cmode=1101
3408       Imm = SplatBits >> 16;
3409       OpCmode = 0xd;
3410       break;
3411     }
3412     // can't handle any other
3413     return false;
3414   }
3415
3416   case 64: {
3417     if (type != Neon_Mov_Imm)
3418       return false;
3419     // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
3420     // movi Op=1, Cmode=1110.
3421     OpCmode = 0x1e;
3422     uint64_t BitMask = 0xff;
3423     uint64_t Val = 0;
3424     unsigned ImmMask = 1;
3425     Imm = 0;
3426     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3427       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3428         Val |= BitMask;
3429         Imm |= ImmMask;
3430       } else if ((SplatBits & BitMask) != 0) {
3431         return false;
3432       }
3433       BitMask <<= 8;
3434       ImmMask <<= 1;
3435     }
3436     SplatBits = Val;
3437     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3438     break;
3439   }
3440   }
3441
3442   return true;
3443 }
3444
3445 static SDValue PerformANDCombine(SDNode *N,
3446                                  TargetLowering::DAGCombinerInfo &DCI) {
3447
3448   SelectionDAG &DAG = DCI.DAG;
3449   SDLoc DL(N);
3450   EVT VT = N->getValueType(0);
3451
3452   // We're looking for an SRA/SHL pair which form an SBFX.
3453
3454   if (VT != MVT::i32 && VT != MVT::i64)
3455     return SDValue();
3456
3457   if (!isa<ConstantSDNode>(N->getOperand(1)))
3458     return SDValue();
3459
3460   uint64_t TruncMask = N->getConstantOperandVal(1);
3461   if (!isMask_64(TruncMask))
3462     return SDValue();
3463
3464   uint64_t Width = CountPopulation_64(TruncMask);
3465   SDValue Shift = N->getOperand(0);
3466
3467   if (Shift.getOpcode() != ISD::SRL)
3468     return SDValue();
3469
3470   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3471     return SDValue();
3472   uint64_t LSB = Shift->getConstantOperandVal(1);
3473
3474   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3475     return SDValue();
3476
3477   return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
3478                      DAG.getConstant(LSB, MVT::i64),
3479                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3480 }
3481
3482 /// For a true bitfield insert, the bits getting into that contiguous mask
3483 /// should come from the low part of an existing value: they must be formed from
3484 /// a compatible SHL operation (unless they're already low). This function
3485 /// checks that condition and returns the least-significant bit that's
3486 /// intended. If the operation not a field preparation, -1 is returned.
3487 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
3488                             SDValue &MaskedVal, uint64_t Mask) {
3489   if (!isShiftedMask_64(Mask))
3490     return -1;
3491
3492   // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
3493   // instruction. BFI will do a left-shift by LSB before applying the mask we've
3494   // spotted, so in general we should pre-emptively "undo" that by making sure
3495   // the incoming bits have had a right-shift applied to them.
3496   //
3497   // This right shift, however, will combine with existing left/right shifts. In
3498   // the simplest case of a completely straight bitfield operation, it will be
3499   // expected to completely cancel out with an existing SHL. More complicated
3500   // cases (e.g. bitfield to bitfield copy) may still need a real shift before
3501   // the BFI.
3502
3503   uint64_t LSB = countTrailingZeros(Mask);
3504   int64_t ShiftRightRequired = LSB;
3505   if (MaskedVal.getOpcode() == ISD::SHL &&
3506       isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3507     ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
3508     MaskedVal = MaskedVal.getOperand(0);
3509   } else if (MaskedVal.getOpcode() == ISD::SRL &&
3510              isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3511     ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
3512     MaskedVal = MaskedVal.getOperand(0);
3513   }
3514
3515   if (ShiftRightRequired > 0)
3516     MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
3517                             DAG.getConstant(ShiftRightRequired, MVT::i64));
3518   else if (ShiftRightRequired < 0) {
3519     // We could actually end up with a residual left shift, for example with
3520     // "struc.bitfield = val << 1".
3521     MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
3522                             DAG.getConstant(-ShiftRightRequired, MVT::i64));
3523   }
3524
3525   return LSB;
3526 }
3527
3528 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
3529 /// a mask and an extension. Returns true if a BFI was found and provides
3530 /// information on its surroundings.
3531 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
3532                           bool &Extended) {
3533   Extended = false;
3534   if (N.getOpcode() == ISD::ZERO_EXTEND) {
3535     Extended = true;
3536     N = N.getOperand(0);
3537   }
3538
3539   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
3540     Mask = N->getConstantOperandVal(1);
3541     N = N.getOperand(0);
3542   } else {
3543     // Mask is the whole width.
3544     Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
3545   }
3546
3547   if (N.getOpcode() == AArch64ISD::BFI) {
3548     BFI = N;
3549     return true;
3550   }
3551
3552   return false;
3553 }
3554
3555 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
3556 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
3557 /// can often be further combined with a larger mask. Ultimately, we want mask
3558 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
3559 static SDValue tryCombineToBFI(SDNode *N,
3560                                TargetLowering::DAGCombinerInfo &DCI,
3561                                const AArch64Subtarget *Subtarget) {
3562   SelectionDAG &DAG = DCI.DAG;
3563   SDLoc DL(N);
3564   EVT VT = N->getValueType(0);
3565
3566   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3567
3568   // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
3569   // abandon the effort.
3570   SDValue LHS = N->getOperand(0);
3571   if (LHS.getOpcode() != ISD::AND)
3572     return SDValue();
3573
3574   uint64_t LHSMask;
3575   if (isa<ConstantSDNode>(LHS.getOperand(1)))
3576     LHSMask = LHS->getConstantOperandVal(1);
3577   else
3578     return SDValue();
3579
3580   // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
3581   // is or abandon the effort.
3582   SDValue RHS = N->getOperand(1);
3583   if (RHS.getOpcode() != ISD::AND)
3584     return SDValue();
3585
3586   uint64_t RHSMask;
3587   if (isa<ConstantSDNode>(RHS.getOperand(1)))
3588     RHSMask = RHS->getConstantOperandVal(1);
3589   else
3590     return SDValue();
3591
3592   // Can't do anything if the masks are incompatible.
3593   if (LHSMask & RHSMask)
3594     return SDValue();
3595
3596   // Now we need one of the masks to be a contiguous field. Without loss of
3597   // generality that should be the RHS one.
3598   SDValue Bitfield = LHS.getOperand(0);
3599   if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3600     // We know that LHS is a candidate new value, and RHS isn't already a better
3601     // one.
3602     std::swap(LHS, RHS);
3603     std::swap(LHSMask, RHSMask);
3604   }
3605
3606   // We've done our best to put the right operands in the right places, all we
3607   // can do now is check whether a BFI exists.
3608   Bitfield = RHS.getOperand(0);
3609   int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3610   if (LSB == -1)
3611     return SDValue();
3612
3613   uint32_t Width = CountPopulation_64(RHSMask);
3614   assert(Width && "Expected non-zero bitfield width");
3615
3616   SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3617                             LHS.getOperand(0), Bitfield,
3618                             DAG.getConstant(LSB, MVT::i64),
3619                             DAG.getConstant(Width, MVT::i64));
3620
3621   // Mask is trivial
3622   if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3623     return BFI;
3624
3625   return DAG.getNode(ISD::AND, DL, VT, BFI,
3626                      DAG.getConstant(LHSMask | RHSMask, VT));
3627 }
3628
3629 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3630 /// original input. This is surprisingly common because SROA splits things up
3631 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3632 /// on the low (say) byte of a word. This is then orred into the rest of the
3633 /// word afterwards.
3634 ///
3635 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3636 ///
3637 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3638 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3639 /// involved.
3640 static SDValue tryCombineToLargerBFI(SDNode *N,
3641                                      TargetLowering::DAGCombinerInfo &DCI,
3642                                      const AArch64Subtarget *Subtarget) {
3643   SelectionDAG &DAG = DCI.DAG;
3644   SDLoc DL(N);
3645   EVT VT = N->getValueType(0);
3646
3647   // First job is to hunt for a MaskedBFI on either the left or right. Swap
3648   // operands if it's actually on the right.
3649   SDValue BFI;
3650   SDValue PossExtraMask;
3651   uint64_t ExistingMask = 0;
3652   bool Extended = false;
3653   if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3654     PossExtraMask = N->getOperand(1);
3655   else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3656     PossExtraMask = N->getOperand(0);
3657   else
3658     return SDValue();
3659
3660   // We can only combine a BFI with another compatible mask.
3661   if (PossExtraMask.getOpcode() != ISD::AND ||
3662       !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3663     return SDValue();
3664
3665   uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3666
3667   // Masks must be compatible.
3668   if (ExtraMask & ExistingMask)
3669     return SDValue();
3670
3671   SDValue OldBFIVal = BFI.getOperand(0);
3672   SDValue NewBFIVal = BFI.getOperand(1);
3673   if (Extended) {
3674     // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3675     // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3676     // need to be made compatible.
3677     assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3678            && "Invalid types for BFI");
3679     OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3680     NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3681   }
3682
3683   // We need the MaskedBFI to be combined with a mask of the *same* value.
3684   if (PossExtraMask.getOperand(0) != OldBFIVal)
3685     return SDValue();
3686
3687   BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3688                     OldBFIVal, NewBFIVal,
3689                     BFI.getOperand(2), BFI.getOperand(3));
3690
3691   // If the masking is trivial, we don't need to create it.
3692   if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3693     return BFI;
3694
3695   return DAG.getNode(ISD::AND, DL, VT, BFI,
3696                      DAG.getConstant(ExtraMask | ExistingMask, VT));
3697 }
3698
3699 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3700 /// searches for and classifies those shifts.
3701 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3702                          bool &FromHi) {
3703   if (N.getOpcode() == ISD::SHL)
3704     FromHi = false;
3705   else if (N.getOpcode() == ISD::SRL)
3706     FromHi = true;
3707   else
3708     return false;
3709
3710   if (!isa<ConstantSDNode>(N.getOperand(1)))
3711     return false;
3712
3713   ShiftAmount = N->getConstantOperandVal(1);
3714   Src = N->getOperand(0);
3715   return true;
3716 }
3717
3718 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3719 /// registers viewed as a high/low pair. This function looks for the pattern:
3720 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3721 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3722 /// independent.
3723 static SDValue tryCombineToEXTR(SDNode *N,
3724                                 TargetLowering::DAGCombinerInfo &DCI) {
3725   SelectionDAG &DAG = DCI.DAG;
3726   SDLoc DL(N);
3727   EVT VT = N->getValueType(0);
3728
3729   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3730
3731   if (VT != MVT::i32 && VT != MVT::i64)
3732     return SDValue();
3733
3734   SDValue LHS;
3735   uint32_t ShiftLHS = 0;
3736   bool LHSFromHi = 0;
3737   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3738     return SDValue();
3739
3740   SDValue RHS;
3741   uint32_t ShiftRHS = 0;
3742   bool RHSFromHi = 0;
3743   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3744     return SDValue();
3745
3746   // If they're both trying to come from the high part of the register, they're
3747   // not really an EXTR.
3748   if (LHSFromHi == RHSFromHi)
3749     return SDValue();
3750
3751   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3752     return SDValue();
3753
3754   if (LHSFromHi) {
3755     std::swap(LHS, RHS);
3756     std::swap(ShiftLHS, ShiftRHS);
3757   }
3758
3759   return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3760                      LHS, RHS,
3761                      DAG.getConstant(ShiftRHS, MVT::i64));
3762 }
3763
3764 /// Target-specific dag combine xforms for ISD::OR
3765 static SDValue PerformORCombine(SDNode *N,
3766                                 TargetLowering::DAGCombinerInfo &DCI,
3767                                 const AArch64Subtarget *Subtarget) {
3768
3769   SelectionDAG &DAG = DCI.DAG;
3770   SDLoc DL(N);
3771   EVT VT = N->getValueType(0);
3772
3773   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3774     return SDValue();
3775
3776   // Attempt to recognise bitfield-insert operations.
3777   SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3778   if (Res.getNode())
3779     return Res;
3780
3781   // Attempt to combine an existing MaskedBFI operation into one with a larger
3782   // mask.
3783   Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3784   if (Res.getNode())
3785     return Res;
3786
3787   Res = tryCombineToEXTR(N, DCI);
3788   if (Res.getNode())
3789     return Res;
3790
3791   if (!Subtarget->hasNEON())
3792     return SDValue();
3793
3794   // Attempt to use vector immediate-form BSL
3795   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3796
3797   SDValue N0 = N->getOperand(0);
3798   if (N0.getOpcode() != ISD::AND)
3799     return SDValue();
3800
3801   SDValue N1 = N->getOperand(1);
3802   if (N1.getOpcode() != ISD::AND)
3803     return SDValue();
3804
3805   if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3806     APInt SplatUndef;
3807     unsigned SplatBitSize;
3808     bool HasAnyUndefs;
3809     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3810     APInt SplatBits0;
3811     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3812                                       HasAnyUndefs) &&
3813         !HasAnyUndefs) {
3814       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3815       APInt SplatBits1;
3816       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3817                                         HasAnyUndefs) && !HasAnyUndefs &&
3818           SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
3819           SplatBits0 == ~SplatBits1) {
3820
3821         return DAG.getNode(ISD::VSELECT, DL, VT, N0->getOperand(1),
3822                            N0->getOperand(0), N1->getOperand(0));
3823       }
3824     }
3825   }
3826
3827   return SDValue();
3828 }
3829
3830 /// Target-specific dag combine xforms for ISD::SRA
3831 static SDValue PerformSRACombine(SDNode *N,
3832                                  TargetLowering::DAGCombinerInfo &DCI) {
3833
3834   SelectionDAG &DAG = DCI.DAG;
3835   SDLoc DL(N);
3836   EVT VT = N->getValueType(0);
3837
3838   // We're looking for an SRA/SHL pair which form an SBFX.
3839
3840   if (VT != MVT::i32 && VT != MVT::i64)
3841     return SDValue();
3842
3843   if (!isa<ConstantSDNode>(N->getOperand(1)))
3844     return SDValue();
3845
3846   uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3847   SDValue Shift = N->getOperand(0);
3848
3849   if (Shift.getOpcode() != ISD::SHL)
3850     return SDValue();
3851
3852   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3853     return SDValue();
3854
3855   uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3856   uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3857   uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3858
3859   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3860     return SDValue();
3861
3862   return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3863                      DAG.getConstant(LSB, MVT::i64),
3864                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3865 }
3866
3867 /// Check if this is a valid build_vector for the immediate operand of
3868 /// a vector shift operation, where all the elements of the build_vector
3869 /// must have the same constant integer value.
3870 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3871   // Ignore bit_converts.
3872   while (Op.getOpcode() == ISD::BITCAST)
3873     Op = Op.getOperand(0);
3874   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3875   APInt SplatBits, SplatUndef;
3876   unsigned SplatBitSize;
3877   bool HasAnyUndefs;
3878   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3879                                       HasAnyUndefs, ElementBits) ||
3880       SplatBitSize > ElementBits)
3881     return false;
3882   Cnt = SplatBits.getSExtValue();
3883   return true;
3884 }
3885
3886 /// Check if this is a valid build_vector for the immediate operand of
3887 /// a vector shift left operation.  That value must be in the range:
3888 /// 0 <= Value < ElementBits
3889 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3890   assert(VT.isVector() && "vector shift count is not a vector type");
3891   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3892   if (!getVShiftImm(Op, ElementBits, Cnt))
3893     return false;
3894   return (Cnt >= 0 && Cnt < ElementBits);
3895 }
3896
3897 /// Check if this is a valid build_vector for the immediate operand of a
3898 /// vector shift right operation. The value must be in the range:
3899 ///   1 <= Value <= ElementBits
3900 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3901   assert(VT.isVector() && "vector shift count is not a vector type");
3902   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3903   if (!getVShiftImm(Op, ElementBits, Cnt))
3904     return false;
3905   return (Cnt >= 1 && Cnt <= ElementBits);
3906 }
3907
3908 static SDValue GenForSextInreg(SDNode *N,
3909                                TargetLowering::DAGCombinerInfo &DCI,
3910                                EVT SrcVT, EVT DestVT, EVT SubRegVT,
3911                                const int *Mask, SDValue Src) {
3912   SelectionDAG &DAG = DCI.DAG;
3913   SDValue Bitcast
3914     = DAG.getNode(ISD::BITCAST, SDLoc(N), SrcVT, Src);
3915   SDValue Sext
3916     = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), DestVT, Bitcast);
3917   SDValue ShuffleVec
3918     = DAG.getVectorShuffle(DestVT, SDLoc(N), Sext, DAG.getUNDEF(DestVT), Mask);
3919   SDValue ExtractSubreg
3920     = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, SDLoc(N),
3921                 SubRegVT, ShuffleVec,
3922                 DAG.getTargetConstant(AArch64::sub_64, MVT::i32)), 0);
3923   return ExtractSubreg;
3924 }
3925
3926 /// Checks for vector shifts and lowers them.
3927 static SDValue PerformShiftCombine(SDNode *N,
3928                                    TargetLowering::DAGCombinerInfo &DCI,
3929                                    const AArch64Subtarget *ST) {
3930   SelectionDAG &DAG = DCI.DAG;
3931   EVT VT = N->getValueType(0);
3932   if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3933     return PerformSRACombine(N, DCI);
3934
3935   // We're looking for an SRA/SHL pair to help generating instruction
3936   //   sshll  v0.8h, v0.8b, #0
3937   // The instruction STXL is also the alias of this instruction.
3938   //
3939   // For example, for DAG like below,
3940   //   v2i32 = sra (v2i32 (shl v2i32, 16)), 16
3941   // we can transform it into
3942   //   v2i32 = EXTRACT_SUBREG 
3943   //             (v4i32 (suffle_vector
3944   //                       (v4i32 (sext (v4i16 (bitcast v2i32))), 
3945   //                       undef, (0, 2, u, u)),
3946   //             sub_64
3947   //
3948   // With this transformation we expect to generate "SSHLL + UZIP1"
3949   // Sometimes UZIP1 can be optimized away by combining with other context.
3950   int64_t ShrCnt, ShlCnt;
3951   if (N->getOpcode() == ISD::SRA
3952       && (VT == MVT::v2i32 || VT == MVT::v4i16)
3953       && isVShiftRImm(N->getOperand(1), VT, ShrCnt)
3954       && N->getOperand(0).getOpcode() == ISD::SHL
3955       && isVShiftRImm(N->getOperand(0).getOperand(1), VT, ShlCnt)) {
3956     SDValue Src = N->getOperand(0).getOperand(0);
3957     if (VT == MVT::v2i32 && ShrCnt == 16 && ShlCnt == 16) {
3958       // sext_inreg(v2i32, v2i16)
3959       // We essentially only care the Mask {0, 2, u, u}
3960       int Mask[4] = {0, 2, 4, 6};
3961       return GenForSextInreg(N, DCI, MVT::v4i16, MVT::v4i32, MVT::v2i32,
3962                              Mask, Src); 
3963     }
3964     else if (VT == MVT::v2i32 && ShrCnt == 24 && ShlCnt == 24) {
3965       // sext_inreg(v2i16, v2i8)
3966       // We essentially only care the Mask {0, u, 4, u, u, u, u, u, u, u, u, u}
3967       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
3968       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v2i32,
3969                              Mask, Src);
3970     }
3971     else if (VT == MVT::v4i16 && ShrCnt == 8 && ShlCnt == 8) {
3972       // sext_inreg(v4i16, v4i8)
3973       // We essentially only care the Mask {0, 2, 4, 6, u, u, u, u, u, u, u, u}
3974       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
3975       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v4i16,
3976                              Mask, Src);
3977     }
3978   }
3979
3980   // Nothing to be done for scalar shifts.
3981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3982   if (!VT.isVector() || !TLI.isTypeLegal(VT))
3983     return SDValue();
3984
3985   assert(ST->hasNEON() && "unexpected vector shift");
3986   int64_t Cnt;
3987
3988   switch (N->getOpcode()) {
3989   default:
3990     llvm_unreachable("unexpected shift opcode");
3991
3992   case ISD::SHL:
3993     if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3994       SDValue RHS =
3995           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3996                       DAG.getConstant(Cnt, MVT::i32));
3997       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3998     }
3999     break;
4000
4001   case ISD::SRA:
4002   case ISD::SRL:
4003     if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
4004       SDValue RHS =
4005           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
4006                       DAG.getConstant(Cnt, MVT::i32));
4007       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
4008     }
4009     break;
4010   }
4011
4012   return SDValue();
4013 }
4014
4015 /// ARM-specific DAG combining for intrinsics.
4016 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
4017   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4018
4019   switch (IntNo) {
4020   default:
4021     // Don't do anything for most intrinsics.
4022     break;
4023
4024   case Intrinsic::arm_neon_vqshifts:
4025   case Intrinsic::arm_neon_vqshiftu:
4026     EVT VT = N->getOperand(1).getValueType();
4027     int64_t Cnt;
4028     if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
4029       break;
4030     unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
4031                              ? AArch64ISD::NEON_QSHLs
4032                              : AArch64ISD::NEON_QSHLu;
4033     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
4034                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
4035   }
4036
4037   return SDValue();
4038 }
4039
4040 /// Target-specific DAG combine function for NEON load/store intrinsics
4041 /// to merge base address updates.
4042 static SDValue CombineBaseUpdate(SDNode *N,
4043                                  TargetLowering::DAGCombinerInfo &DCI) {
4044   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
4045     return SDValue();
4046
4047   SelectionDAG &DAG = DCI.DAG;
4048   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
4049                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
4050   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
4051   SDValue Addr = N->getOperand(AddrOpIdx);
4052
4053   // Search for a use of the address operand that is an increment.
4054   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
4055        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
4056     SDNode *User = *UI;
4057     if (User->getOpcode() != ISD::ADD ||
4058         UI.getUse().getResNo() != Addr.getResNo())
4059       continue;
4060
4061     // Check that the add is independent of the load/store.  Otherwise, folding
4062     // it would create a cycle.
4063     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
4064       continue;
4065
4066     // Find the new opcode for the updating load/store.
4067     bool isLoad = true;
4068     bool isLaneOp = false;
4069     unsigned NewOpc = 0;
4070     unsigned NumVecs = 0;
4071     if (isIntrinsic) {
4072       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
4073       switch (IntNo) {
4074       default: llvm_unreachable("unexpected intrinsic for Neon base update");
4075       case Intrinsic::arm_neon_vld1:       NewOpc = AArch64ISD::NEON_LD1_UPD;
4076         NumVecs = 1; break;
4077       case Intrinsic::arm_neon_vld2:       NewOpc = AArch64ISD::NEON_LD2_UPD;
4078         NumVecs = 2; break;
4079       case Intrinsic::arm_neon_vld3:       NewOpc = AArch64ISD::NEON_LD3_UPD;
4080         NumVecs = 3; break;
4081       case Intrinsic::arm_neon_vld4:       NewOpc = AArch64ISD::NEON_LD4_UPD;
4082         NumVecs = 4; break;
4083       case Intrinsic::arm_neon_vst1:       NewOpc = AArch64ISD::NEON_ST1_UPD;
4084         NumVecs = 1; isLoad = false; break;
4085       case Intrinsic::arm_neon_vst2:       NewOpc = AArch64ISD::NEON_ST2_UPD;
4086         NumVecs = 2; isLoad = false; break;
4087       case Intrinsic::arm_neon_vst3:       NewOpc = AArch64ISD::NEON_ST3_UPD;
4088         NumVecs = 3; isLoad = false; break;
4089       case Intrinsic::arm_neon_vst4:       NewOpc = AArch64ISD::NEON_ST4_UPD;
4090         NumVecs = 4; isLoad = false; break;
4091       case Intrinsic::aarch64_neon_vld1x2: NewOpc = AArch64ISD::NEON_LD1x2_UPD;
4092         NumVecs = 2; break;
4093       case Intrinsic::aarch64_neon_vld1x3: NewOpc = AArch64ISD::NEON_LD1x3_UPD;
4094         NumVecs = 3; break;
4095       case Intrinsic::aarch64_neon_vld1x4: NewOpc = AArch64ISD::NEON_LD1x4_UPD;
4096         NumVecs = 4; break;
4097       case Intrinsic::aarch64_neon_vst1x2: NewOpc = AArch64ISD::NEON_ST1x2_UPD;
4098         NumVecs = 2; isLoad = false; break;
4099       case Intrinsic::aarch64_neon_vst1x3: NewOpc = AArch64ISD::NEON_ST1x3_UPD;
4100         NumVecs = 3; isLoad = false; break;
4101       case Intrinsic::aarch64_neon_vst1x4: NewOpc = AArch64ISD::NEON_ST1x4_UPD;
4102         NumVecs = 4; isLoad = false; break;
4103       case Intrinsic::arm_neon_vld2lane:   NewOpc = AArch64ISD::NEON_LD2LN_UPD;
4104         NumVecs = 2; isLaneOp = true; break;
4105       case Intrinsic::arm_neon_vld3lane:   NewOpc = AArch64ISD::NEON_LD3LN_UPD;
4106         NumVecs = 3; isLaneOp = true; break;
4107       case Intrinsic::arm_neon_vld4lane:   NewOpc = AArch64ISD::NEON_LD4LN_UPD;
4108         NumVecs = 4; isLaneOp = true; break;
4109       case Intrinsic::arm_neon_vst2lane:   NewOpc = AArch64ISD::NEON_ST2LN_UPD;
4110         NumVecs = 2; isLoad = false; isLaneOp = true; break;
4111       case Intrinsic::arm_neon_vst3lane:   NewOpc = AArch64ISD::NEON_ST3LN_UPD;
4112         NumVecs = 3; isLoad = false; isLaneOp = true; break;
4113       case Intrinsic::arm_neon_vst4lane:   NewOpc = AArch64ISD::NEON_ST4LN_UPD;
4114         NumVecs = 4; isLoad = false; isLaneOp = true; break;
4115       }
4116     } else {
4117       isLaneOp = true;
4118       switch (N->getOpcode()) {
4119       default: llvm_unreachable("unexpected opcode for Neon base update");
4120       case AArch64ISD::NEON_LD2DUP: NewOpc = AArch64ISD::NEON_LD2DUP_UPD;
4121         NumVecs = 2; break;
4122       case AArch64ISD::NEON_LD3DUP: NewOpc = AArch64ISD::NEON_LD3DUP_UPD;
4123         NumVecs = 3; break;
4124       case AArch64ISD::NEON_LD4DUP: NewOpc = AArch64ISD::NEON_LD4DUP_UPD;
4125         NumVecs = 4; break;
4126       }
4127     }
4128
4129     // Find the size of memory referenced by the load/store.
4130     EVT VecTy;
4131     if (isLoad)
4132       VecTy = N->getValueType(0);
4133     else
4134       VecTy = N->getOperand(AddrOpIdx + 1).getValueType();
4135     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
4136     if (isLaneOp)
4137       NumBytes /= VecTy.getVectorNumElements();
4138
4139     // If the increment is a constant, it must match the memory ref size.
4140     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
4141     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
4142       uint32_t IncVal = CInc->getZExtValue();
4143       if (IncVal != NumBytes)
4144         continue;
4145       Inc = DAG.getTargetConstant(IncVal, MVT::i32);
4146     }
4147
4148     // Create the new updating load/store node.
4149     EVT Tys[6];
4150     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
4151     unsigned n;
4152     for (n = 0; n < NumResultVecs; ++n)
4153       Tys[n] = VecTy;
4154     Tys[n++] = MVT::i64;
4155     Tys[n] = MVT::Other;
4156     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs + 2);
4157     SmallVector<SDValue, 8> Ops;
4158     Ops.push_back(N->getOperand(0)); // incoming chain
4159     Ops.push_back(N->getOperand(AddrOpIdx));
4160     Ops.push_back(Inc);
4161     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
4162       Ops.push_back(N->getOperand(i));
4163     }
4164     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
4165     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
4166                                            Ops.data(), Ops.size(),
4167                                            MemInt->getMemoryVT(),
4168                                            MemInt->getMemOperand());
4169
4170     // Update the uses.
4171     std::vector<SDValue> NewResults;
4172     for (unsigned i = 0; i < NumResultVecs; ++i) {
4173       NewResults.push_back(SDValue(UpdN.getNode(), i));
4174     }
4175     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
4176     DCI.CombineTo(N, NewResults);
4177     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
4178
4179     break;
4180   }
4181   return SDValue();
4182 }
4183
4184 /// For a VDUPLANE node N, check if its source operand is a vldN-lane (N > 1)
4185 /// intrinsic, and if all the other uses of that intrinsic are also VDUPLANEs.
4186 /// If so, combine them to a vldN-dup operation and return true.
4187 static SDValue CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
4188   SelectionDAG &DAG = DCI.DAG;
4189   EVT VT = N->getValueType(0);
4190
4191   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
4192   SDNode *VLD = N->getOperand(0).getNode();
4193   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
4194     return SDValue();
4195   unsigned NumVecs = 0;
4196   unsigned NewOpc = 0;
4197   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
4198   if (IntNo == Intrinsic::arm_neon_vld2lane) {
4199     NumVecs = 2;
4200     NewOpc = AArch64ISD::NEON_LD2DUP;
4201   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
4202     NumVecs = 3;
4203     NewOpc = AArch64ISD::NEON_LD3DUP;
4204   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
4205     NumVecs = 4;
4206     NewOpc = AArch64ISD::NEON_LD4DUP;
4207   } else {
4208     return SDValue();
4209   }
4210
4211   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
4212   // numbers match the load.
4213   unsigned VLDLaneNo =
4214       cast<ConstantSDNode>(VLD->getOperand(NumVecs + 3))->getZExtValue();
4215   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
4216        UI != UE; ++UI) {
4217     // Ignore uses of the chain result.
4218     if (UI.getUse().getResNo() == NumVecs)
4219       continue;
4220     SDNode *User = *UI;
4221     if (User->getOpcode() != AArch64ISD::NEON_VDUPLANE ||
4222         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
4223       return SDValue();
4224   }
4225
4226   // Create the vldN-dup node.
4227   EVT Tys[5];
4228   unsigned n;
4229   for (n = 0; n < NumVecs; ++n)
4230     Tys[n] = VT;
4231   Tys[n] = MVT::Other;
4232   SDVTList SDTys = DAG.getVTList(Tys, NumVecs + 1);
4233   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
4234   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
4235   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, Ops, 2,
4236                                            VLDMemInt->getMemoryVT(),
4237                                            VLDMemInt->getMemOperand());
4238
4239   // Update the uses.
4240   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
4241        UI != UE; ++UI) {
4242     unsigned ResNo = UI.getUse().getResNo();
4243     // Ignore uses of the chain result.
4244     if (ResNo == NumVecs)
4245       continue;
4246     SDNode *User = *UI;
4247     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
4248   }
4249
4250   // Now the vldN-lane intrinsic is dead except for its chain result.
4251   // Update uses of the chain.
4252   std::vector<SDValue> VLDDupResults;
4253   for (unsigned n = 0; n < NumVecs; ++n)
4254     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
4255   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
4256   DCI.CombineTo(VLD, VLDDupResults);
4257
4258   return SDValue(N, 0);
4259 }
4260
4261 SDValue
4262 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
4263                                          DAGCombinerInfo &DCI) const {
4264   switch (N->getOpcode()) {
4265   default: break;
4266   case ISD::AND: return PerformANDCombine(N, DCI);
4267   case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
4268   case ISD::SHL:
4269   case ISD::SRA:
4270   case ISD::SRL:
4271     return PerformShiftCombine(N, DCI, getSubtarget());
4272   case ISD::INTRINSIC_WO_CHAIN:
4273     return PerformIntrinsicCombine(N, DCI.DAG);
4274   case AArch64ISD::NEON_VDUPLANE:
4275     return CombineVLDDUP(N, DCI);
4276   case AArch64ISD::NEON_LD2DUP:
4277   case AArch64ISD::NEON_LD3DUP:
4278   case AArch64ISD::NEON_LD4DUP:
4279     return CombineBaseUpdate(N, DCI);
4280   case ISD::INTRINSIC_VOID:
4281   case ISD::INTRINSIC_W_CHAIN:
4282     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
4283     case Intrinsic::arm_neon_vld1:
4284     case Intrinsic::arm_neon_vld2:
4285     case Intrinsic::arm_neon_vld3:
4286     case Intrinsic::arm_neon_vld4:
4287     case Intrinsic::arm_neon_vst1:
4288     case Intrinsic::arm_neon_vst2:
4289     case Intrinsic::arm_neon_vst3:
4290     case Intrinsic::arm_neon_vst4:
4291     case Intrinsic::arm_neon_vld2lane:
4292     case Intrinsic::arm_neon_vld3lane:
4293     case Intrinsic::arm_neon_vld4lane:
4294     case Intrinsic::aarch64_neon_vld1x2:
4295     case Intrinsic::aarch64_neon_vld1x3:
4296     case Intrinsic::aarch64_neon_vld1x4:
4297     case Intrinsic::aarch64_neon_vst1x2:
4298     case Intrinsic::aarch64_neon_vst1x3:
4299     case Intrinsic::aarch64_neon_vst1x4:
4300     case Intrinsic::arm_neon_vst2lane:
4301     case Intrinsic::arm_neon_vst3lane:
4302     case Intrinsic::arm_neon_vst4lane:
4303       return CombineBaseUpdate(N, DCI);
4304     default:
4305       break;
4306     }
4307   }
4308   return SDValue();
4309 }
4310
4311 bool
4312 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
4313   VT = VT.getScalarType();
4314
4315   if (!VT.isSimple())
4316     return false;
4317
4318   switch (VT.getSimpleVT().SimpleTy) {
4319   case MVT::f16:
4320   case MVT::f32:
4321   case MVT::f64:
4322     return true;
4323   case MVT::f128:
4324     return false;
4325   default:
4326     break;
4327   }
4328
4329   return false;
4330 }
4331 // Check whether a shuffle_vector could be presented as concat_vector.
4332 bool AArch64TargetLowering::isConcatVector(SDValue Op, SelectionDAG &DAG,
4333                                            SDValue V0, SDValue V1,
4334                                            const int *Mask,
4335                                            SDValue &Res) const {
4336   SDLoc DL(Op);
4337   EVT VT = Op.getValueType();
4338   if (VT.getSizeInBits() != 128)
4339     return false;
4340   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4341       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4342     return false;
4343
4344   unsigned NumElts = VT.getVectorNumElements();
4345   bool isContactVector = true;
4346   bool splitV0 = false;
4347   if (V0.getValueType().getSizeInBits() == 128)
4348     splitV0 = true;
4349
4350   for (int I = 0, E = NumElts / 2; I != E; I++) {
4351     if (Mask[I] != I) {
4352       isContactVector = false;
4353       break;
4354     }
4355   }
4356
4357   if (isContactVector) {
4358     int offset = NumElts / 2;
4359     for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4360       if (Mask[I] != I + splitV0 * offset) {
4361         isContactVector = false;
4362         break;
4363       }
4364     }
4365   }
4366
4367   if (isContactVector) {
4368     EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4369                                   NumElts / 2);
4370     if (splitV0) {
4371       V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4372                        DAG.getConstant(0, MVT::i64));
4373     }
4374     if (V1.getValueType().getSizeInBits() == 128) {
4375       V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4376                        DAG.getConstant(0, MVT::i64));
4377     }
4378     Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4379     return true;
4380   }
4381   return false;
4382 }
4383
4384 // Check whether a Build Vector could be presented as Shuffle Vector.
4385 // This Shuffle Vector maybe not legalized, so the length of its operand and
4386 // the length of result may not equal.
4387 bool AArch64TargetLowering::isKnownShuffleVector(SDValue Op, SelectionDAG &DAG,
4388                                                  SDValue &V0, SDValue &V1,
4389                                                  int *Mask) const {
4390   SDLoc DL(Op);
4391   EVT VT = Op.getValueType();
4392   unsigned NumElts = VT.getVectorNumElements();
4393   unsigned V0NumElts = 0;
4394
4395   // Check if all elements are extracted from less than 3 vectors.
4396   for (unsigned i = 0; i < NumElts; ++i) {
4397     SDValue Elt = Op.getOperand(i);
4398     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4399         Elt.getOperand(0).getValueType().getVectorElementType() !=
4400             VT.getVectorElementType())
4401       return false;
4402
4403     if (V0.getNode() == 0) {
4404       V0 = Elt.getOperand(0);
4405       V0NumElts = V0.getValueType().getVectorNumElements();
4406     }
4407     if (Elt.getOperand(0) == V0) {
4408       Mask[i] = (cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue());
4409       continue;
4410     } else if (V1.getNode() == 0) {
4411       V1 = Elt.getOperand(0);
4412     }
4413     if (Elt.getOperand(0) == V1) {
4414       unsigned Lane = cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue();
4415       Mask[i] = (Lane + V0NumElts);
4416       continue;
4417     } else {
4418       return false;
4419     }
4420   }
4421   return true;
4422 }
4423
4424 // If this is a case we can't handle, return null and let the default
4425 // expansion code take care of it.
4426 SDValue
4427 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4428                                          const AArch64Subtarget *ST) const {
4429
4430   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4431   SDLoc DL(Op);
4432   EVT VT = Op.getValueType();
4433
4434   APInt SplatBits, SplatUndef;
4435   unsigned SplatBitSize;
4436   bool HasAnyUndefs;
4437
4438   unsigned UseNeonMov = VT.getSizeInBits() >= 64;
4439
4440   // Note we favor lowering MOVI over MVNI.
4441   // This has implications on the definition of patterns in TableGen to select
4442   // BIC immediate instructions but not ORR immediate instructions.
4443   // If this lowering order is changed, TableGen patterns for BIC immediate and
4444   // ORR immediate instructions have to be updated.
4445   if (UseNeonMov &&
4446       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4447     if (SplatBitSize <= 64) {
4448       // First attempt to use vector immediate-form MOVI
4449       EVT NeonMovVT;
4450       unsigned Imm = 0;
4451       unsigned OpCmode = 0;
4452
4453       if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
4454                             SplatBitSize, DAG, VT.is128BitVector(),
4455                             Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
4456         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4457         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4458
4459         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4460           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
4461                                         ImmVal, OpCmodeVal);
4462           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4463         }
4464       }
4465
4466       // Then attempt to use vector immediate-form MVNI
4467       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4468       if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
4469                             DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
4470                             Imm, OpCmode)) {
4471         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4472         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4473         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4474           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
4475                                         ImmVal, OpCmodeVal);
4476           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4477         }
4478       }
4479
4480       // Attempt to use vector immediate-form FMOV
4481       if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
4482           (VT == MVT::v2f64 && SplatBitSize == 64)) {
4483         APFloat RealVal(
4484             SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
4485             SplatBits);
4486         uint32_t ImmVal;
4487         if (A64Imms::isFPImm(RealVal, ImmVal)) {
4488           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4489           return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
4490         }
4491       }
4492     }
4493   }
4494
4495   unsigned NumElts = VT.getVectorNumElements();
4496   bool isOnlyLowElement = true;
4497   bool usesOnlyOneValue = true;
4498   bool hasDominantValue = false;
4499   bool isConstant = true;
4500
4501   // Map of the number of times a particular SDValue appears in the
4502   // element list.
4503   DenseMap<SDValue, unsigned> ValueCounts;
4504   SDValue Value;
4505   for (unsigned i = 0; i < NumElts; ++i) {
4506     SDValue V = Op.getOperand(i);
4507     if (V.getOpcode() == ISD::UNDEF)
4508       continue;
4509     if (i > 0)
4510       isOnlyLowElement = false;
4511     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4512       isConstant = false;
4513
4514     ValueCounts.insert(std::make_pair(V, 0));
4515     unsigned &Count = ValueCounts[V];
4516
4517     // Is this value dominant? (takes up more than half of the lanes)
4518     if (++Count > (NumElts / 2)) {
4519       hasDominantValue = true;
4520       Value = V;
4521     }
4522   }
4523   if (ValueCounts.size() != 1)
4524     usesOnlyOneValue = false;
4525   if (!Value.getNode() && ValueCounts.size() > 0)
4526     Value = ValueCounts.begin()->first;
4527
4528   if (ValueCounts.size() == 0)
4529     return DAG.getUNDEF(VT);
4530
4531   if (isOnlyLowElement)
4532     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4533
4534   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4535   if (hasDominantValue && EltSize <= 64) {
4536     // Use VDUP for non-constant splats.
4537     if (!isConstant) {
4538       SDValue N;
4539
4540       // If we are DUPing a value that comes directly from a vector, we could
4541       // just use DUPLANE. We can only do this if the lane being extracted
4542       // is at a constant index, as the DUP from lane instructions only have
4543       // constant-index forms.
4544       //
4545       // If there is a TRUNCATE between EXTRACT_VECTOR_ELT and DUP, we can
4546       // remove TRUNCATE for DUPLANE by apdating the source vector to
4547       // appropriate vector type and lane index.
4548       //
4549       // FIXME: for now we have v1i8, v1i16, v1i32 legal vector types, if they
4550       // are not legal any more, no need to check the type size in bits should
4551       // be large than 64.
4552       SDValue V = Value;
4553       if (Value->getOpcode() == ISD::TRUNCATE)
4554         V = Value->getOperand(0);
4555       if (V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4556           isa<ConstantSDNode>(V->getOperand(1)) &&
4557           V->getOperand(0).getValueType().getSizeInBits() >= 64) {
4558
4559         // If the element size of source vector is larger than DUPLANE
4560         // element size, we can do transformation by,
4561         // 1) bitcasting source register to smaller element vector
4562         // 2) mutiplying the lane index by SrcEltSize/ResEltSize
4563         // For example, we can lower
4564         //     "v8i16 vdup_lane(v4i32, 1)"
4565         // to be
4566         //     "v8i16 vdup_lane(v8i16 bitcast(v4i32), 2)".
4567         SDValue SrcVec = V->getOperand(0);
4568         unsigned SrcEltSize =
4569             SrcVec.getValueType().getVectorElementType().getSizeInBits();
4570         unsigned ResEltSize = VT.getVectorElementType().getSizeInBits();
4571         if (SrcEltSize > ResEltSize) {
4572           assert((SrcEltSize % ResEltSize == 0) && "Invalid element size");
4573           SDValue BitCast;
4574           unsigned SrcSize = SrcVec.getValueType().getSizeInBits();
4575           unsigned ResSize = VT.getSizeInBits();
4576
4577           if (SrcSize > ResSize) {
4578             assert((SrcSize % ResSize == 0) && "Invalid vector size");
4579             EVT CastVT =
4580                 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4581                                  SrcSize / ResEltSize);
4582             BitCast = DAG.getNode(ISD::BITCAST, DL, CastVT, SrcVec);
4583           } else {
4584             assert((SrcSize == ResSize) && "Invalid vector size of source vec");
4585             BitCast = DAG.getNode(ISD::BITCAST, DL, VT, SrcVec);
4586           }
4587
4588           unsigned LaneIdx = V->getConstantOperandVal(1);
4589           SDValue Lane =
4590               DAG.getConstant((SrcEltSize / ResEltSize) * LaneIdx, MVT::i64);
4591           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, BitCast, Lane);
4592         } else {
4593           assert((SrcEltSize == ResEltSize) &&
4594                  "Invalid element size of source vec");
4595           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, V->getOperand(0),
4596                           V->getOperand(1));
4597         }
4598       } else
4599         N = DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4600
4601       if (!usesOnlyOneValue) {
4602         // The dominant value was splatted as 'N', but we now have to insert
4603         // all differing elements.
4604         for (unsigned I = 0; I < NumElts; ++I) {
4605           if (Op.getOperand(I) == Value)
4606             continue;
4607           SmallVector<SDValue, 3> Ops;
4608           Ops.push_back(N);
4609           Ops.push_back(Op.getOperand(I));
4610           Ops.push_back(DAG.getConstant(I, MVT::i64));
4611           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, &Ops[0], 3);
4612         }
4613       }
4614       return N;
4615     }
4616     if (usesOnlyOneValue && isConstant) {
4617       return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4618     }
4619   }
4620   // If all elements are constants and the case above didn't get hit, fall back
4621   // to the default expansion, which will generate a load from the constant
4622   // pool.
4623   if (isConstant)
4624     return SDValue();
4625
4626   // Try to lower this in lowering ShuffleVector way.
4627   SDValue V0, V1;
4628   int Mask[16];
4629   if (isKnownShuffleVector(Op, DAG, V0, V1, Mask)) {
4630     unsigned V0NumElts = V0.getValueType().getVectorNumElements();
4631     if (!V1.getNode() && V0NumElts == NumElts * 2) {
4632       V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4633                        DAG.getConstant(NumElts, MVT::i64));
4634       V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4635                        DAG.getConstant(0, MVT::i64));
4636       V0NumElts = V0.getValueType().getVectorNumElements();
4637     }
4638
4639     if (V1.getNode() && NumElts == V0NumElts &&
4640         V0NumElts == V1.getValueType().getVectorNumElements()) {
4641       SDValue Shuffle = DAG.getVectorShuffle(VT, DL, V0, V1, Mask);
4642       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
4643         return Shuffle;
4644       else
4645         return LowerVECTOR_SHUFFLE(Shuffle, DAG);
4646     } else {
4647       SDValue Res;
4648       if (isConcatVector(Op, DAG, V0, V1, Mask, Res))
4649         return Res;
4650     }
4651   }
4652
4653   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4654   // know the default expansion would otherwise fall back on something even
4655   // worse. For a vector with one or two non-undef values, that's
4656   // scalar_to_vector for the elements followed by a shuffle (provided the
4657   // shuffle is valid for the target) and materialization element by element
4658   // on the stack followed by a load for everything else.
4659   if (!isConstant && !usesOnlyOneValue) {
4660     SDValue Vec = DAG.getUNDEF(VT);
4661     for (unsigned i = 0 ; i < NumElts; ++i) {
4662       SDValue V = Op.getOperand(i);
4663       if (V.getOpcode() == ISD::UNDEF)
4664         continue;
4665       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
4666       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, LaneIdx);
4667     }
4668     return Vec;
4669   }
4670   return SDValue();
4671 }
4672
4673 /// isREVMask - Check if a vector shuffle corresponds to a REV
4674 /// instruction with the specified blocksize.  (The order of the elements
4675 /// within each block of the vector is reversed.)
4676 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4677   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4678          "Only possible block sizes for REV are: 16, 32, 64");
4679
4680   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4681   if (EltSz == 64)
4682     return false;
4683
4684   unsigned NumElts = VT.getVectorNumElements();
4685   unsigned BlockElts = M[0] + 1;
4686   // If the first shuffle index is UNDEF, be optimistic.
4687   if (M[0] < 0)
4688     BlockElts = BlockSize / EltSz;
4689
4690   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4691     return false;
4692
4693   for (unsigned i = 0; i < NumElts; ++i) {
4694     if (M[i] < 0)
4695       continue; // ignore UNDEF indices
4696     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4697       return false;
4698   }
4699
4700   return true;
4701 }
4702
4703 // isPermuteMask - Check whether the vector shuffle matches to UZP, ZIP and
4704 // TRN instruction.
4705 static unsigned isPermuteMask(ArrayRef<int> M, EVT VT, bool isV2undef) {
4706   unsigned NumElts = VT.getVectorNumElements();
4707   if (NumElts < 4)
4708     return 0;
4709
4710   bool ismatch = true;
4711
4712   // Check UZP1
4713   for (unsigned i = 0; i < NumElts; ++i) {
4714     unsigned answer = i * 2;
4715     if (isV2undef && answer >= NumElts)
4716       answer -= NumElts;
4717     if (M[i] != -1 && (unsigned)M[i] != answer) {
4718       ismatch = false;
4719       break;
4720     }
4721   }
4722   if (ismatch)
4723     return AArch64ISD::NEON_UZP1;
4724
4725   // Check UZP2
4726   ismatch = true;
4727   for (unsigned i = 0; i < NumElts; ++i) {
4728     unsigned answer = i * 2 + 1;
4729     if (isV2undef && answer >= NumElts)
4730       answer -= NumElts;
4731     if (M[i] != -1 && (unsigned)M[i] != answer) {
4732       ismatch = false;
4733       break;
4734     }
4735   }
4736   if (ismatch)
4737     return AArch64ISD::NEON_UZP2;
4738
4739   // Check ZIP1
4740   ismatch = true;
4741   for (unsigned i = 0; i < NumElts; ++i) {
4742     unsigned answer = i / 2 + NumElts * (i % 2);
4743     if (isV2undef && answer >= NumElts)
4744       answer -= NumElts;
4745     if (M[i] != -1 && (unsigned)M[i] != answer) {
4746       ismatch = false;
4747       break;
4748     }
4749   }
4750   if (ismatch)
4751     return AArch64ISD::NEON_ZIP1;
4752
4753   // Check ZIP2
4754   ismatch = true;
4755   for (unsigned i = 0; i < NumElts; ++i) {
4756     unsigned answer = (NumElts + i) / 2 + NumElts * (i % 2);
4757     if (isV2undef && answer >= NumElts)
4758       answer -= NumElts;
4759     if (M[i] != -1 && (unsigned)M[i] != answer) {
4760       ismatch = false;
4761       break;
4762     }
4763   }
4764   if (ismatch)
4765     return AArch64ISD::NEON_ZIP2;
4766
4767   // Check TRN1
4768   ismatch = true;
4769   for (unsigned i = 0; i < NumElts; ++i) {
4770     unsigned answer = i + (NumElts - 1) * (i % 2);
4771     if (isV2undef && answer >= NumElts)
4772       answer -= NumElts;
4773     if (M[i] != -1 && (unsigned)M[i] != answer) {
4774       ismatch = false;
4775       break;
4776     }
4777   }
4778   if (ismatch)
4779     return AArch64ISD::NEON_TRN1;
4780
4781   // Check TRN2
4782   ismatch = true;
4783   for (unsigned i = 0; i < NumElts; ++i) {
4784     unsigned answer = 1 + i + (NumElts - 1) * (i % 2);
4785     if (isV2undef && answer >= NumElts)
4786       answer -= NumElts;
4787     if (M[i] != -1 && (unsigned)M[i] != answer) {
4788       ismatch = false;
4789       break;
4790     }
4791   }
4792   if (ismatch)
4793     return AArch64ISD::NEON_TRN2;
4794
4795   return 0;
4796 }
4797
4798 SDValue
4799 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4800                                            SelectionDAG &DAG) const {
4801   SDValue V1 = Op.getOperand(0);
4802   SDValue V2 = Op.getOperand(1);
4803   SDLoc dl(Op);
4804   EVT VT = Op.getValueType();
4805   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4806
4807   // Convert shuffles that are directly supported on NEON to target-specific
4808   // DAG nodes, instead of keeping them as shuffles and matching them again
4809   // during code selection.  This is more efficient and avoids the possibility
4810   // of inconsistencies between legalization and selection.
4811   ArrayRef<int> ShuffleMask = SVN->getMask();
4812
4813   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4814   if (EltSize > 64)
4815     return SDValue();
4816
4817   if (isREVMask(ShuffleMask, VT, 64))
4818     return DAG.getNode(AArch64ISD::NEON_REV64, dl, VT, V1);
4819   if (isREVMask(ShuffleMask, VT, 32))
4820     return DAG.getNode(AArch64ISD::NEON_REV32, dl, VT, V1);
4821   if (isREVMask(ShuffleMask, VT, 16))
4822     return DAG.getNode(AArch64ISD::NEON_REV16, dl, VT, V1);
4823
4824   unsigned ISDNo;
4825   if (V2.getOpcode() == ISD::UNDEF)
4826     ISDNo = isPermuteMask(ShuffleMask, VT, true);
4827   else
4828     ISDNo = isPermuteMask(ShuffleMask, VT, false);
4829
4830   if (ISDNo) {
4831     if (V2.getOpcode() == ISD::UNDEF)
4832       return DAG.getNode(ISDNo, dl, VT, V1, V1);
4833     else
4834       return DAG.getNode(ISDNo, dl, VT, V1, V2);
4835   }
4836
4837   SDValue Res;
4838   if (isConcatVector(Op, DAG, V1, V2, &ShuffleMask[0], Res))
4839     return Res;
4840
4841   // If the element of shuffle mask are all the same constant, we can
4842   // transform it into either NEON_VDUP or NEON_VDUPLANE
4843   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4844     int Lane = SVN->getSplatIndex();
4845     // If this is undef splat, generate it via "just" vdup, if possible.
4846     if (Lane == -1) Lane = 0;
4847
4848     // Test if V1 is a SCALAR_TO_VECTOR.
4849     if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4850       return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT, V1.getOperand(0));
4851     }
4852     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR.
4853     if (V1.getOpcode() == ISD::BUILD_VECTOR) {
4854       bool IsScalarToVector = true;
4855       for (unsigned i = 0, e = V1.getNumOperands(); i != e; ++i)
4856         if (V1.getOperand(i).getOpcode() != ISD::UNDEF &&
4857             i != (unsigned)Lane) {
4858           IsScalarToVector = false;
4859           break;
4860         }
4861       if (IsScalarToVector)
4862         return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT,
4863                            V1.getOperand(Lane));
4864     }
4865
4866     // Test if V1 is a EXTRACT_SUBVECTOR.
4867     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4868       int ExtLane = cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4869       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1.getOperand(0),
4870                          DAG.getConstant(Lane + ExtLane, MVT::i64));
4871     }
4872     // Test if V1 is a CONCAT_VECTORS.
4873     if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
4874         V1.getOperand(1).getOpcode() == ISD::UNDEF) {
4875       SDValue Op0 = V1.getOperand(0);
4876       assert((unsigned)Lane < Op0.getValueType().getVectorNumElements() &&
4877              "Invalid vector lane access");
4878       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, Op0,
4879                          DAG.getConstant(Lane, MVT::i64));
4880     }
4881
4882     return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
4883                        DAG.getConstant(Lane, MVT::i64));
4884   }
4885
4886   int Length = ShuffleMask.size();
4887   int V1EltNum = V1.getValueType().getVectorNumElements();
4888
4889   // If the number of v1 elements is the same as the number of shuffle mask
4890   // element and the shuffle masks are sequential values, we can transform
4891   // it into NEON_VEXTRACT.
4892   if (V1EltNum == Length) {
4893     // Check if the shuffle mask is sequential.
4894     int SkipUndef = 0;
4895     while (ShuffleMask[SkipUndef] == -1) {
4896       SkipUndef++;
4897     }
4898     int CurMask = ShuffleMask[SkipUndef];
4899     if (CurMask >= SkipUndef) {
4900       bool IsSequential = true;
4901       for (int I = SkipUndef; I < Length; ++I) {
4902         if (ShuffleMask[I] != -1 && ShuffleMask[I] != CurMask) {
4903           IsSequential = false;
4904           break;
4905         }
4906         CurMask++;
4907       }
4908       if (IsSequential) {
4909         assert((EltSize % 8 == 0) && "Bitsize of vector element is incorrect");
4910         unsigned VecSize = EltSize * V1EltNum;
4911         unsigned Index = (EltSize / 8) * (ShuffleMask[SkipUndef] - SkipUndef);
4912         if (VecSize == 64 || VecSize == 128)
4913           return DAG.getNode(AArch64ISD::NEON_VEXTRACT, dl, VT, V1, V2,
4914                              DAG.getConstant(Index, MVT::i64));
4915       }
4916     }
4917   }
4918
4919   // For shuffle mask like "0, 1, 2, 3, 4, 5, 13, 7", try to generate insert
4920   // by element from V2 to V1 .
4921   // If shuffle mask is like "0, 1, 10, 11, 12, 13, 14, 15", V2 would be a
4922   // better choice to be inserted than V1 as less insert needed, so we count
4923   // element to be inserted for both V1 and V2, and select less one as insert
4924   // target.
4925
4926   // Collect elements need to be inserted and their index.
4927   SmallVector<int, 8> NV1Elt;
4928   SmallVector<int, 8> N1Index;
4929   SmallVector<int, 8> NV2Elt;
4930   SmallVector<int, 8> N2Index;
4931   for (int I = 0; I != Length; ++I) {
4932     if (ShuffleMask[I] != I) {
4933       NV1Elt.push_back(ShuffleMask[I]);
4934       N1Index.push_back(I);
4935     }
4936   }
4937   for (int I = 0; I != Length; ++I) {
4938     if (ShuffleMask[I] != (I + V1EltNum)) {
4939       NV2Elt.push_back(ShuffleMask[I]);
4940       N2Index.push_back(I);
4941     }
4942   }
4943
4944   // Decide which to be inserted. If all lanes mismatch, neither V1 nor V2
4945   // will be inserted.
4946   SDValue InsV = V1;
4947   SmallVector<int, 8> InsMasks = NV1Elt;
4948   SmallVector<int, 8> InsIndex = N1Index;
4949   if ((int)NV1Elt.size() != Length || (int)NV2Elt.size() != Length) {
4950     if (NV1Elt.size() > NV2Elt.size()) {
4951       InsV = V2;
4952       InsMasks = NV2Elt;
4953       InsIndex = N2Index;
4954     }
4955   } else {
4956     InsV = DAG.getNode(ISD::UNDEF, dl, VT);
4957   }
4958
4959   for (int I = 0, E = InsMasks.size(); I != E; ++I) {
4960     SDValue ExtV = V1;
4961     int Mask = InsMasks[I];
4962     if (Mask >= V1EltNum) {
4963       ExtV = V2;
4964       Mask -= V1EltNum;
4965     }
4966     // Any value type smaller than i32 is illegal in AArch64, and this lower
4967     // function is called after legalize pass, so we need to legalize
4968     // the result here.
4969     EVT EltVT;
4970     if (VT.getVectorElementType().isFloatingPoint())
4971       EltVT = (EltSize == 64) ? MVT::f64 : MVT::f32;
4972     else
4973       EltVT = (EltSize == 64) ? MVT::i64 : MVT::i32;
4974
4975     if (Mask >= 0) {
4976       ExtV = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ExtV,
4977                          DAG.getConstant(Mask, MVT::i64));
4978       InsV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, InsV, ExtV,
4979                          DAG.getConstant(InsIndex[I], MVT::i64));
4980     }
4981   }
4982   return InsV;
4983 }
4984
4985 AArch64TargetLowering::ConstraintType
4986 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4987   if (Constraint.size() == 1) {
4988     switch (Constraint[0]) {
4989     default: break;
4990     case 'w': // An FP/SIMD vector register
4991       return C_RegisterClass;
4992     case 'I': // Constant that can be used with an ADD instruction
4993     case 'J': // Constant that can be used with a SUB instruction
4994     case 'K': // Constant that can be used with a 32-bit logical instruction
4995     case 'L': // Constant that can be used with a 64-bit logical instruction
4996     case 'M': // Constant that can be used as a 32-bit MOV immediate
4997     case 'N': // Constant that can be used as a 64-bit MOV immediate
4998     case 'Y': // Floating point constant zero
4999     case 'Z': // Integer constant zero
5000       return C_Other;
5001     case 'Q': // A memory reference with base register and no offset
5002       return C_Memory;
5003     case 'S': // A symbolic address
5004       return C_Other;
5005     }
5006   }
5007
5008   // FIXME: Ump, Utf, Usa, Ush
5009   // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
5010   //      whatever they may be
5011   // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
5012   // Usa: An absolute symbolic address
5013   // Ush: The high part (bits 32:12) of a pc-relative symbolic address
5014   assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
5015          && Constraint != "Ush" && "Unimplemented constraints");
5016
5017   return TargetLowering::getConstraintType(Constraint);
5018 }
5019
5020 TargetLowering::ConstraintWeight
5021 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
5022                                                 const char *Constraint) const {
5023
5024   llvm_unreachable("Constraint weight unimplemented");
5025 }
5026
5027 void
5028 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5029                                                     std::string &Constraint,
5030                                                     std::vector<SDValue> &Ops,
5031                                                     SelectionDAG &DAG) const {
5032   SDValue Result(0, 0);
5033
5034   // Only length 1 constraints are C_Other.
5035   if (Constraint.size() != 1) return;
5036
5037   // Only C_Other constraints get lowered like this. That means constants for us
5038   // so return early if there's no hope the constraint can be lowered.
5039
5040   switch(Constraint[0]) {
5041   default: break;
5042   case 'I': case 'J': case 'K': case 'L':
5043   case 'M': case 'N': case 'Z': {
5044     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5045     if (!C)
5046       return;
5047
5048     uint64_t CVal = C->getZExtValue();
5049     uint32_t Bits;
5050
5051     switch (Constraint[0]) {
5052     default:
5053       // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
5054       // is a peculiarly useless SUB constraint.
5055       llvm_unreachable("Unimplemented C_Other constraint");
5056     case 'I':
5057       if (CVal <= 0xfff)
5058         break;
5059       return;
5060     case 'K':
5061       if (A64Imms::isLogicalImm(32, CVal, Bits))
5062         break;
5063       return;
5064     case 'L':
5065       if (A64Imms::isLogicalImm(64, CVal, Bits))
5066         break;
5067       return;
5068     case 'Z':
5069       if (CVal == 0)
5070         break;
5071       return;
5072     }
5073
5074     Result = DAG.getTargetConstant(CVal, Op.getValueType());
5075     break;
5076   }
5077   case 'S': {
5078     // An absolute symbolic address or label reference.
5079     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5080       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5081                                           GA->getValueType(0));
5082     } else if (const BlockAddressSDNode *BA
5083                  = dyn_cast<BlockAddressSDNode>(Op)) {
5084       Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
5085                                          BA->getValueType(0));
5086     } else if (const ExternalSymbolSDNode *ES
5087                  = dyn_cast<ExternalSymbolSDNode>(Op)) {
5088       Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
5089                                            ES->getValueType(0));
5090     } else
5091       return;
5092     break;
5093   }
5094   case 'Y':
5095     if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
5096       if (CFP->isExactlyValue(0.0)) {
5097         Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
5098         break;
5099       }
5100     }
5101     return;
5102   }
5103
5104   if (Result.getNode()) {
5105     Ops.push_back(Result);
5106     return;
5107   }
5108
5109   // It's an unknown constraint for us. Let generic code have a go.
5110   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5111 }
5112
5113 std::pair<unsigned, const TargetRegisterClass*>
5114 AArch64TargetLowering::getRegForInlineAsmConstraint(
5115                                                   const std::string &Constraint,
5116                                                   MVT VT) const {
5117   if (Constraint.size() == 1) {
5118     switch (Constraint[0]) {
5119     case 'r':
5120       if (VT.getSizeInBits() <= 32)
5121         return std::make_pair(0U, &AArch64::GPR32RegClass);
5122       else if (VT == MVT::i64)
5123         return std::make_pair(0U, &AArch64::GPR64RegClass);
5124       break;
5125     case 'w':
5126       if (VT == MVT::f16)
5127         return std::make_pair(0U, &AArch64::FPR16RegClass);
5128       else if (VT == MVT::f32)
5129         return std::make_pair(0U, &AArch64::FPR32RegClass);
5130       else if (VT.getSizeInBits() == 64)
5131         return std::make_pair(0U, &AArch64::FPR64RegClass);
5132       else if (VT.getSizeInBits() == 128)
5133         return std::make_pair(0U, &AArch64::FPR128RegClass);
5134       break;
5135     }
5136   }
5137
5138   // Use the default implementation in TargetLowering to convert the register
5139   // constraint into a member of a register class.
5140   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5141 }
5142
5143 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
5144 /// The associated MachineMemOperands record the alignment specified
5145 /// in the intrinsic calls.
5146 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5147                                                const CallInst &I,
5148                                                unsigned Intrinsic) const {
5149   switch (Intrinsic) {
5150   case Intrinsic::arm_neon_vld1:
5151   case Intrinsic::arm_neon_vld2:
5152   case Intrinsic::arm_neon_vld3:
5153   case Intrinsic::arm_neon_vld4:
5154   case Intrinsic::aarch64_neon_vld1x2:
5155   case Intrinsic::aarch64_neon_vld1x3:
5156   case Intrinsic::aarch64_neon_vld1x4:
5157   case Intrinsic::arm_neon_vld2lane:
5158   case Intrinsic::arm_neon_vld3lane:
5159   case Intrinsic::arm_neon_vld4lane: {
5160     Info.opc = ISD::INTRINSIC_W_CHAIN;
5161     // Conservatively set memVT to the entire set of vectors loaded.
5162     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5163     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5164     Info.ptrVal = I.getArgOperand(0);
5165     Info.offset = 0;
5166     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
5167     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
5168     Info.vol = false; // volatile loads with NEON intrinsics not supported
5169     Info.readMem = true;
5170     Info.writeMem = false;
5171     return true;
5172   }
5173   case Intrinsic::arm_neon_vst1:
5174   case Intrinsic::arm_neon_vst2:
5175   case Intrinsic::arm_neon_vst3:
5176   case Intrinsic::arm_neon_vst4:
5177   case Intrinsic::aarch64_neon_vst1x2:
5178   case Intrinsic::aarch64_neon_vst1x3:
5179   case Intrinsic::aarch64_neon_vst1x4:
5180   case Intrinsic::arm_neon_vst2lane:
5181   case Intrinsic::arm_neon_vst3lane:
5182   case Intrinsic::arm_neon_vst4lane: {
5183     Info.opc = ISD::INTRINSIC_VOID;
5184     // Conservatively set memVT to the entire set of vectors stored.
5185     unsigned NumElts = 0;
5186     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5187       Type *ArgTy = I.getArgOperand(ArgI)->getType();
5188       if (!ArgTy->isVectorTy())
5189         break;
5190       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5191     }
5192     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5193     Info.ptrVal = I.getArgOperand(0);
5194     Info.offset = 0;
5195     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
5196     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
5197     Info.vol = false; // volatile stores with NEON intrinsics not supported
5198     Info.readMem = false;
5199     Info.writeMem = true;
5200     return true;
5201   }
5202   default:
5203     break;
5204   }
5205
5206   return false;
5207 }