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