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