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