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