a016e6e4855078de6cd03d0ca3462f966376fede
[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) const {
2413   unsigned Reg = StringSwitch<unsigned>(RegName)
2414                        .Case("sp", AArch64::XSP)
2415                        .Default(0);
2416   if (Reg)
2417     return Reg;
2418   report_fatal_error("Invalid register name global variable");
2419 }
2420
2421 SDValue
2422 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
2423                                                   SelectionDAG &DAG) const {
2424   assert(getTargetMachine().getCodeModel() == CodeModel::Large);
2425   assert(getTargetMachine().getRelocationModel() == Reloc::Static);
2426
2427   EVT PtrVT = getPointerTy();
2428   SDLoc dl(Op);
2429   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2430   const GlobalValue *GV = GN->getGlobal();
2431
2432   SDValue GlobalAddr = DAG.getNode(
2433       AArch64ISD::WrapperLarge, dl, PtrVT,
2434       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
2435       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
2436       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
2437       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
2438
2439   if (GN->getOffset() != 0)
2440     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2441                        DAG.getConstant(GN->getOffset(), PtrVT));
2442
2443   return GlobalAddr;
2444 }
2445
2446 SDValue
2447 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
2448                                                   SelectionDAG &DAG) const {
2449   assert(getTargetMachine().getCodeModel() == CodeModel::Small);
2450
2451   EVT PtrVT = getPointerTy();
2452   SDLoc dl(Op);
2453   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2454   const GlobalValue *GV = GN->getGlobal();
2455   unsigned Alignment = GV->getAlignment();
2456   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2457   if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
2458     // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
2459     // to zero when they remain undefined. In PIC mode the GOT can take care of
2460     // this, but in absolute mode we use a constant pool load.
2461     SDValue PoolAddr;
2462     PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2463                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2464                                                      AArch64II::MO_NO_FLAG),
2465                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2466                                                      AArch64II::MO_LO12),
2467                            DAG.getConstant(8, MVT::i32));
2468     SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
2469                                      MachinePointerInfo::getConstantPool(),
2470                                      /*isVolatile=*/ false,
2471                                      /*isNonTemporal=*/ true,
2472                                      /*isInvariant=*/ true, 8);
2473     if (GN->getOffset() != 0)
2474       return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2475                          DAG.getConstant(GN->getOffset(), PtrVT));
2476
2477     return GlobalAddr;
2478   }
2479
2480   if (Alignment == 0) {
2481     const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2482     if (GVPtrTy->getElementType()->isSized()) {
2483       Alignment
2484         = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2485     } else {
2486       // Be conservative if we can't guess, not that it really matters:
2487       // functions and labels aren't valid for loads, and the methods used to
2488       // actually calculate an address work with any alignment.
2489       Alignment = 1;
2490     }
2491   }
2492
2493   unsigned char HiFixup, LoFixup;
2494   bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2495
2496   if (UseGOT) {
2497     HiFixup = AArch64II::MO_GOT;
2498     LoFixup = AArch64II::MO_GOT_LO12;
2499     Alignment = 8;
2500   } else {
2501     HiFixup = AArch64II::MO_NO_FLAG;
2502     LoFixup = AArch64II::MO_LO12;
2503   }
2504
2505   // AArch64's small model demands the following sequence:
2506   // ADRP x0, somewhere
2507   // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2508   SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2509                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2510                                                              HiFixup),
2511                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2512                                                              LoFixup),
2513                                   DAG.getConstant(Alignment, MVT::i32));
2514
2515   if (UseGOT) {
2516     GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2517                             GlobalRef);
2518   }
2519
2520   if (GN->getOffset() != 0)
2521     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2522                        DAG.getConstant(GN->getOffset(), PtrVT));
2523
2524   return GlobalRef;
2525 }
2526
2527 SDValue
2528 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2529                                              SelectionDAG &DAG) const {
2530   // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2531   // we make those distinctions here.
2532
2533   switch (getTargetMachine().getCodeModel()) {
2534   case CodeModel::Small:
2535     return LowerGlobalAddressELFSmall(Op, DAG);
2536   case CodeModel::Large:
2537     return LowerGlobalAddressELFLarge(Op, DAG);
2538   default:
2539     llvm_unreachable("Only small and large code models supported now");
2540   }
2541 }
2542
2543 SDValue
2544 AArch64TargetLowering::LowerConstantPool(SDValue Op,
2545                                          SelectionDAG &DAG) const {
2546   SDLoc DL(Op);
2547   EVT PtrVT = getPointerTy();
2548   ConstantPoolSDNode *CN = cast<ConstantPoolSDNode>(Op);
2549   const Constant *C = CN->getConstVal();
2550
2551   switch(getTargetMachine().getCodeModel()) {
2552   case CodeModel::Small:
2553     // The most efficient code is PC-relative anyway for the small memory model,
2554     // so we don't need to worry about relocation model.
2555     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2556                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2557                                                  AArch64II::MO_NO_FLAG),
2558                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2559                                                  AArch64II::MO_LO12),
2560                        DAG.getConstant(CN->getAlignment(), MVT::i32));
2561   case CodeModel::Large:
2562     return DAG.getNode(
2563       AArch64ISD::WrapperLarge, DL, PtrVT,
2564       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G3),
2565       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G2_NC),
2566       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G1_NC),
2567       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G0_NC));
2568   default:
2569     llvm_unreachable("Only small and large code models supported now");
2570   }
2571 }
2572
2573 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2574                                                 SDValue DescAddr,
2575                                                 SDLoc DL,
2576                                                 SelectionDAG &DAG) const {
2577   EVT PtrVT = getPointerTy();
2578
2579   // The function we need to call is simply the first entry in the GOT for this
2580   // descriptor, load it in preparation.
2581   SDValue Func, Chain;
2582   Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2583                      DescAddr);
2584
2585   // The function takes only one argument: the address of the descriptor itself
2586   // in X0.
2587   SDValue Glue;
2588   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2589   Glue = Chain.getValue(1);
2590
2591   // Finally, there's a special calling-convention which means that the lookup
2592   // must preserve all registers (except X0, obviously).
2593   const TargetRegisterInfo *TRI  = getTargetMachine().getRegisterInfo();
2594   const AArch64RegisterInfo *A64RI
2595     = static_cast<const AArch64RegisterInfo *>(TRI);
2596   const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2597
2598   // We're now ready to populate the argument list, as with a normal call:
2599   std::vector<SDValue> Ops;
2600   Ops.push_back(Chain);
2601   Ops.push_back(Func);
2602   Ops.push_back(SymAddr);
2603   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2604   Ops.push_back(DAG.getRegisterMask(Mask));
2605   Ops.push_back(Glue);
2606
2607   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2608   Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, Ops);
2609   Glue = Chain.getValue(1);
2610
2611   // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2612   // back to the generic handling code.
2613   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2614 }
2615
2616 SDValue
2617 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2618                                              SelectionDAG &DAG) const {
2619   assert(getSubtarget()->isTargetELF() &&
2620          "TLS not implemented for non-ELF targets");
2621   assert(getTargetMachine().getCodeModel() == CodeModel::Small
2622          && "TLS only supported in small memory model");
2623   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2624
2625   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2626
2627   SDValue TPOff;
2628   EVT PtrVT = getPointerTy();
2629   SDLoc DL(Op);
2630   const GlobalValue *GV = GA->getGlobal();
2631
2632   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2633
2634   if (Model == TLSModel::InitialExec) {
2635     TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2636                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2637                                                    AArch64II::MO_GOTTPREL),
2638                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2639                                                    AArch64II::MO_GOTTPREL_LO12),
2640                         DAG.getConstant(8, MVT::i32));
2641     TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2642                         TPOff);
2643   } else if (Model == TLSModel::LocalExec) {
2644     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2645                                                AArch64II::MO_TPREL_G1);
2646     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2647                                                AArch64II::MO_TPREL_G0_NC);
2648
2649     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2650                                        DAG.getTargetConstant(1, MVT::i32)), 0);
2651     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2652                                        TPOff, LoVar,
2653                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2654   } else if (Model == TLSModel::GeneralDynamic) {
2655     // Accesses used in this sequence go via the TLS descriptor which lives in
2656     // the GOT. Prepare an address we can use to handle this.
2657     SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2658                                                 AArch64II::MO_TLSDESC);
2659     SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2660                                                 AArch64II::MO_TLSDESC_LO12);
2661     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2662                                    HiDesc, LoDesc,
2663                                    DAG.getConstant(8, MVT::i32));
2664     SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2665
2666     TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2667   } else if (Model == TLSModel::LocalDynamic) {
2668     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2669     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2670     // the beginning of the module's TLS region, followed by a DTPREL offset
2671     // calculation.
2672
2673     // These accesses will need deduplicating if there's more than one.
2674     AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2675       .getInfo<AArch64MachineFunctionInfo>();
2676     MFI->incNumLocalDynamicTLSAccesses();
2677
2678
2679     // Get the location of _TLS_MODULE_BASE_:
2680     SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2681                                                 AArch64II::MO_TLSDESC);
2682     SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2683                                                 AArch64II::MO_TLSDESC_LO12);
2684     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2685                                    HiDesc, LoDesc,
2686                                    DAG.getConstant(8, MVT::i32));
2687     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2688
2689     ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2690
2691     // Get the variable's offset from _TLS_MODULE_BASE_
2692     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2693                                                AArch64II::MO_DTPREL_G1);
2694     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2695                                                AArch64II::MO_DTPREL_G0_NC);
2696
2697     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2698                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2699     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2700                                        TPOff, LoVar,
2701                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2702   } else
2703       llvm_unreachable("Unsupported TLS access model");
2704
2705
2706   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2707 }
2708
2709 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2710                                     bool IsSigned) {
2711   SDLoc dl(Op);
2712   EVT VT = Op.getValueType();
2713   SDValue Vec = Op.getOperand(0);
2714   unsigned Opc = IsSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
2715
2716   if (VT.getVectorNumElements() == 1) {
2717     assert(VT == MVT::v1f64 && "Unexpected vector type!");
2718     if (VT.getSizeInBits() == Vec.getValueSizeInBits())
2719       return Op;
2720     return DAG.UnrollVectorOp(Op.getNode());
2721   }
2722
2723   if (VT.getSizeInBits() < Vec.getValueSizeInBits()) {
2724     assert(Vec.getValueType() == MVT::v2i64 && VT == MVT::v2f32 &&
2725            "Unexpected vector type!");
2726     Vec = DAG.getNode(Opc, dl, MVT::v2f64, Vec);
2727     return DAG.getNode(ISD::FP_ROUND, dl, VT, Vec, DAG.getIntPtrConstant(0));
2728   } else if (VT.getSizeInBits() > Vec.getValueSizeInBits()) {
2729     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2730     EVT CastVT = EVT::getIntegerVT(*DAG.getContext(),
2731                                    VT.getVectorElementType().getSizeInBits());
2732     CastVT =
2733         EVT::getVectorVT(*DAG.getContext(), CastVT, VT.getVectorNumElements());
2734     Vec = DAG.getNode(CastOpc, dl, CastVT, Vec);
2735   }
2736
2737   return DAG.getNode(Opc, dl, VT, Vec);
2738 }
2739
2740 SDValue
2741 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2742                                       bool IsSigned) const {
2743   if (Op.getValueType().isVector())
2744     return LowerVectorINT_TO_FP(Op, DAG, IsSigned);
2745   if (Op.getValueType() != MVT::f128) {
2746     // Legal for everything except f128.
2747     return Op;
2748   }
2749
2750   RTLIB::Libcall LC;
2751   if (IsSigned)
2752     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2753   else
2754     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2755
2756   return LowerF128ToCall(Op, DAG, LC);
2757 }
2758
2759
2760 SDValue
2761 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2762   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2763   SDLoc dl(JT);
2764   EVT PtrVT = getPointerTy();
2765
2766   // When compiling PIC, jump tables get put in the code section so a static
2767   // relocation-style is acceptable for both cases.
2768   switch (getTargetMachine().getCodeModel()) {
2769   case CodeModel::Small:
2770     return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2771                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2772                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2773                                               AArch64II::MO_LO12),
2774                        DAG.getConstant(1, MVT::i32));
2775   case CodeModel::Large:
2776     return DAG.getNode(
2777       AArch64ISD::WrapperLarge, dl, PtrVT,
2778       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2779       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2780       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2781       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2782   default:
2783     llvm_unreachable("Only small and large code models supported now");
2784   }
2785 }
2786
2787 // (SELECT testbit, iftrue, iffalse)
2788 SDValue
2789 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2790   SDLoc dl(Op);
2791   SDValue TheBit = Op.getOperand(0);
2792   SDValue IfTrue = Op.getOperand(1);
2793   SDValue IfFalse = Op.getOperand(2);
2794
2795   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2796   // that as the consumer we are responsible for ignoring rubbish in higher
2797   // bits.
2798   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2799                        DAG.getConstant(1, MVT::i32));
2800   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2801                                DAG.getConstant(0, TheBit.getValueType()),
2802                                DAG.getCondCode(ISD::SETNE));
2803
2804   return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2805                      A64CMP, IfTrue, IfFalse,
2806                      DAG.getConstant(A64CC::NE, MVT::i32));
2807 }
2808
2809 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2810   SDLoc DL(Op);
2811   SDValue LHS = Op.getOperand(0);
2812   SDValue RHS = Op.getOperand(1);
2813   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2814   EVT VT = Op.getValueType();
2815   bool Invert = false;
2816   SDValue Op0, Op1;
2817   unsigned Opcode;
2818
2819   if (LHS.getValueType().isInteger()) {
2820
2821     // Attempt to use Vector Integer Compare Mask Test instruction.
2822     // TST = icmp ne (and (op0, op1), zero).
2823     if (CC == ISD::SETNE) {
2824       if (((LHS.getOpcode() == ISD::AND) &&
2825            ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2826           ((RHS.getOpcode() == ISD::AND) &&
2827            ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2828
2829         SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2830         SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2831         SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2832         return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2833       }
2834     }
2835
2836     // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2837     // Note: Compare against Zero does not support unsigned predicates.
2838     if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2839          ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2840         !isUnsignedIntSetCC(CC)) {
2841
2842       // If LHS is the zero value, swap operands and CondCode.
2843       if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2844         CC = getSetCCSwappedOperands(CC);
2845         Op0 = RHS;
2846       } else
2847         Op0 = LHS;
2848
2849       // Ensure valid CondCode for Compare Mask against Zero instruction:
2850       // EQ, GE, GT, LE, LT.
2851       if (ISD::SETNE == CC) {
2852         Invert = true;
2853         CC = ISD::SETEQ;
2854       }
2855
2856       // Using constant type to differentiate integer and FP compares with zero.
2857       Op1 = DAG.getConstant(0, MVT::i32);
2858       Opcode = AArch64ISD::NEON_CMPZ;
2859
2860     } else {
2861       // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2862       // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2863       bool Swap = false;
2864       switch (CC) {
2865       default:
2866         llvm_unreachable("Illegal integer comparison.");
2867       case ISD::SETEQ:
2868       case ISD::SETGT:
2869       case ISD::SETGE:
2870       case ISD::SETUGT:
2871       case ISD::SETUGE:
2872         break;
2873       case ISD::SETNE:
2874         Invert = true;
2875         CC = ISD::SETEQ;
2876         break;
2877       case ISD::SETULT:
2878       case ISD::SETULE:
2879       case ISD::SETLT:
2880       case ISD::SETLE:
2881         Swap = true;
2882         CC = getSetCCSwappedOperands(CC);
2883       }
2884
2885       if (Swap)
2886         std::swap(LHS, RHS);
2887
2888       Opcode = AArch64ISD::NEON_CMP;
2889       Op0 = LHS;
2890       Op1 = RHS;
2891     }
2892
2893     // Generate Compare Mask instr or Compare Mask against Zero instr.
2894     SDValue NeonCmp =
2895         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2896
2897     if (Invert)
2898       NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2899
2900     return NeonCmp;
2901   }
2902
2903   // Now handle Floating Point cases.
2904   // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2905   if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2906       ISD::isBuildVectorAllZeros(LHS.getNode())) {
2907
2908     // If LHS is the zero value, swap operands and CondCode.
2909     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2910       CC = getSetCCSwappedOperands(CC);
2911       Op0 = RHS;
2912     } else
2913       Op0 = LHS;
2914
2915     // Using constant type to differentiate integer and FP compares with zero.
2916     Op1 = DAG.getConstantFP(0, MVT::f32);
2917     Opcode = AArch64ISD::NEON_CMPZ;
2918   } else {
2919     // Attempt to use Vector Floating Point Compare Mask instruction.
2920     Op0 = LHS;
2921     Op1 = RHS;
2922     Opcode = AArch64ISD::NEON_CMP;
2923   }
2924
2925   SDValue NeonCmpAlt;
2926   // Some register compares have to be implemented with swapped CC and operands,
2927   // e.g.: OLT implemented as OGT with swapped operands.
2928   bool SwapIfRegArgs = false;
2929
2930   // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2931   // EQ, GE, GT, LE, LT.
2932   // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2933   switch (CC) {
2934   default:
2935     llvm_unreachable("Illegal FP comparison");
2936   case ISD::SETUNE:
2937   case ISD::SETNE:
2938     Invert = true; // Fallthrough
2939   case ISD::SETOEQ:
2940   case ISD::SETEQ:
2941     CC = ISD::SETEQ;
2942     break;
2943   case ISD::SETOLT:
2944   case ISD::SETLT:
2945     CC = ISD::SETLT;
2946     SwapIfRegArgs = true;
2947     break;
2948   case ISD::SETOGT:
2949   case ISD::SETGT:
2950     CC = ISD::SETGT;
2951     break;
2952   case ISD::SETOLE:
2953   case ISD::SETLE:
2954     CC = ISD::SETLE;
2955     SwapIfRegArgs = true;
2956     break;
2957   case ISD::SETOGE:
2958   case ISD::SETGE:
2959     CC = ISD::SETGE;
2960     break;
2961   case ISD::SETUGE:
2962     Invert = true;
2963     CC = ISD::SETLT;
2964     SwapIfRegArgs = true;
2965     break;
2966   case ISD::SETULE:
2967     Invert = true;
2968     CC = ISD::SETGT;
2969     break;
2970   case ISD::SETUGT:
2971     Invert = true;
2972     CC = ISD::SETLE;
2973     SwapIfRegArgs = true;
2974     break;
2975   case ISD::SETULT:
2976     Invert = true;
2977     CC = ISD::SETGE;
2978     break;
2979   case ISD::SETUEQ:
2980     Invert = true; // Fallthrough
2981   case ISD::SETONE:
2982     // Expand this to (OGT |OLT).
2983     NeonCmpAlt =
2984         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2985     CC = ISD::SETLT;
2986     SwapIfRegArgs = true;
2987     break;
2988   case ISD::SETUO:
2989     Invert = true; // Fallthrough
2990   case ISD::SETO:
2991     // Expand this to (OGE | OLT).
2992     NeonCmpAlt =
2993         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2994     CC = ISD::SETLT;
2995     SwapIfRegArgs = true;
2996     break;
2997   }
2998
2999   if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
3000     CC = getSetCCSwappedOperands(CC);
3001     std::swap(Op0, Op1);
3002   }
3003
3004   // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
3005   SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
3006
3007   if (NeonCmpAlt.getNode())
3008     NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
3009
3010   if (Invert)
3011     NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
3012
3013   return NeonCmp;
3014 }
3015
3016 // (SETCC lhs, rhs, condcode)
3017 SDValue
3018 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3019   SDLoc dl(Op);
3020   SDValue LHS = Op.getOperand(0);
3021   SDValue RHS = Op.getOperand(1);
3022   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3023   EVT VT = Op.getValueType();
3024
3025   if (VT.isVector())
3026     return LowerVectorSETCC(Op, DAG);
3027
3028   if (LHS.getValueType() == MVT::f128) {
3029     // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
3030     // for the rest of the function (some i32 or i64 values).
3031     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3032
3033     // If softenSetCCOperands returned a scalar, use it.
3034     if (!RHS.getNode()) {
3035       assert(LHS.getValueType() == Op.getValueType() &&
3036              "Unexpected setcc expansion!");
3037       return LHS;
3038     }
3039   }
3040
3041   if (LHS.getValueType().isInteger()) {
3042     SDValue A64cc;
3043
3044     // Integers are handled in a separate function because the combinations of
3045     // immediates and tests can get hairy and we may want to fiddle things.
3046     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
3047
3048     return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
3049                        CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3050                        A64cc);
3051   }
3052
3053   // Note that some LLVM floating-point CondCodes can't be lowered to a single
3054   // conditional branch, hence FPCCToA64CC can set a second test, where either
3055   // passing is sufficient.
3056   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3057   CondCode = FPCCToA64CC(CC, Alternative);
3058   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3059   SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3060                               DAG.getCondCode(CC));
3061   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
3062                                      CmpOp, DAG.getConstant(1, VT),
3063                                      DAG.getConstant(0, VT), A64cc);
3064
3065   if (Alternative != A64CC::Invalid) {
3066     A64cc = DAG.getConstant(Alternative, MVT::i32);
3067     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
3068                                DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
3069   }
3070
3071   return A64SELECT_CC;
3072 }
3073
3074 static SDValue LowerVectorSELECT_CC(SDValue Op, SelectionDAG &DAG) {
3075   SDLoc dl(Op);
3076   SDValue LHS = Op.getOperand(0);
3077   SDValue RHS = Op.getOperand(1);
3078   SDValue IfTrue = Op.getOperand(2);
3079   SDValue IfFalse = Op.getOperand(3);
3080   EVT IfTrueVT = IfTrue.getValueType();
3081   EVT CondVT = IfTrueVT.changeVectorElementTypeToInteger();
3082   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3083
3084   // If LHS & RHS are floating point and IfTrue & IfFalse are vectors, we will
3085   // use NEON compare.
3086   if ((LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64)) {
3087     EVT EltVT = LHS.getValueType();
3088     unsigned EltNum = 128 / EltVT.getSizeInBits();
3089     EVT VT = EVT::getVectorVT(*DAG.getContext(), EltVT, EltNum);
3090     unsigned SubConstant =
3091         (LHS.getValueType() == MVT::f32) ? AArch64::sub_32 :AArch64::sub_64;
3092     EVT CEltT = (LHS.getValueType() == MVT::f32) ? MVT::i32 : MVT::i64;
3093     EVT CVT = EVT::getVectorVT(*DAG.getContext(), CEltT, EltNum);
3094
3095     LHS
3096       = SDValue(DAG.getMachineNode(TargetOpcode::SUBREG_TO_REG, dl,
3097                   VT, DAG.getTargetConstant(0, MVT::i32), LHS,
3098                   DAG.getTargetConstant(SubConstant, MVT::i32)), 0);
3099     RHS
3100       = SDValue(DAG.getMachineNode(TargetOpcode::SUBREG_TO_REG, dl,
3101                   VT, DAG.getTargetConstant(0, MVT::i32), RHS,
3102                   DAG.getTargetConstant(SubConstant, MVT::i32)), 0);
3103
3104     SDValue VSetCC = DAG.getSetCC(dl, CVT, LHS, RHS, CC);
3105     SDValue ResCC = LowerVectorSETCC(VSetCC, DAG);
3106     if (CEltT.getSizeInBits() < IfTrueVT.getSizeInBits()) {
3107       EVT DUPVT =
3108           EVT::getVectorVT(*DAG.getContext(), CEltT,
3109                            IfTrueVT.getSizeInBits() / CEltT.getSizeInBits());
3110       ResCC = DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, DUPVT, ResCC,
3111                           DAG.getConstant(0, MVT::i64, false));
3112
3113       ResCC = DAG.getNode(ISD::BITCAST, dl, CondVT, ResCC);
3114     } else {
3115       // FIXME: If IfTrue & IfFalse hold v1i8, v1i16 or v1i32, this function
3116       // can't handle them and will hit this assert.
3117       assert(CEltT.getSizeInBits() == IfTrueVT.getSizeInBits() &&
3118              "Vector of IfTrue & IfFalse is too small.");
3119
3120       unsigned ExEltNum =
3121           EltNum * IfTrueVT.getSizeInBits() / ResCC.getValueSizeInBits();
3122       EVT ExVT = EVT::getVectorVT(*DAG.getContext(), CEltT, ExEltNum);
3123       ResCC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ExVT, ResCC,
3124                           DAG.getConstant(0, MVT::i64, false));
3125       ResCC = DAG.getNode(ISD::BITCAST, dl, CondVT, ResCC);
3126     }
3127     SDValue VSelect = DAG.getNode(ISD::VSELECT, dl, IfTrue.getValueType(),
3128                                   ResCC, IfTrue, IfFalse);
3129     return VSelect;
3130   }
3131
3132   // Here we handle the case that LHS & RHS are integer and IfTrue & IfFalse are
3133   // vectors.
3134   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3135   CondCode = FPCCToA64CC(CC, Alternative);
3136   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3137   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3138                               DAG.getCondCode(CC));
3139   EVT SEVT = MVT::i32;
3140   if (IfTrue.getValueType().getVectorElementType().getSizeInBits() > 32)
3141     SEVT = MVT::i64;
3142   SDValue AllOne = DAG.getConstant(-1, SEVT);
3143   SDValue AllZero = DAG.getConstant(0, SEVT);
3144   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, SEVT, SetCC,
3145                                      AllOne, AllZero, A64cc);
3146
3147   if (Alternative != A64CC::Invalid) {
3148     A64cc = DAG.getConstant(Alternative, MVT::i32);
3149     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
3150                                SetCC, AllOne, A64SELECT_CC, A64cc);
3151   }
3152   SDValue VDup;
3153   if (IfTrue.getValueType().getVectorNumElements() == 1)
3154     VDup = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, CondVT, A64SELECT_CC);
3155   else
3156     VDup = DAG.getNode(AArch64ISD::NEON_VDUP, dl, CondVT, A64SELECT_CC);
3157   SDValue VSelect = DAG.getNode(ISD::VSELECT, dl, IfTrue.getValueType(),
3158                                 VDup, IfTrue, IfFalse);
3159   return VSelect;
3160 }
3161
3162 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
3163 SDValue
3164 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3165   SDLoc dl(Op);
3166   SDValue LHS = Op.getOperand(0);
3167   SDValue RHS = Op.getOperand(1);
3168   SDValue IfTrue = Op.getOperand(2);
3169   SDValue IfFalse = Op.getOperand(3);
3170   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3171
3172   if (IfTrue.getValueType().isVector())
3173     return LowerVectorSELECT_CC(Op, DAG);
3174
3175   if (LHS.getValueType() == MVT::f128) {
3176     // f128 comparisons are lowered to libcalls, but slot in nicely here
3177     // afterwards.
3178     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3179
3180     // If softenSetCCOperands returned a scalar, we need to compare the result
3181     // against zero to select between true and false values.
3182     if (!RHS.getNode()) {
3183       RHS = DAG.getConstant(0, LHS.getValueType());
3184       CC = ISD::SETNE;
3185     }
3186   }
3187
3188   if (LHS.getValueType().isInteger()) {
3189     SDValue A64cc;
3190
3191     // Integers are handled in a separate function because the combinations of
3192     // immediates and tests can get hairy and we may want to fiddle things.
3193     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
3194
3195     return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(), CmpOp,
3196                        IfTrue, IfFalse, A64cc);
3197   }
3198
3199   // Note that some LLVM floating-point CondCodes can't be lowered to a single
3200   // conditional branch, hence FPCCToA64CC can set a second test, where either
3201   // passing is sufficient.
3202   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
3203   CondCode = FPCCToA64CC(CC, Alternative);
3204   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
3205   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
3206                               DAG.getCondCode(CC));
3207   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
3208                                      Op.getValueType(),
3209                                      SetCC, IfTrue, IfFalse, A64cc);
3210
3211   if (Alternative != A64CC::Invalid) {
3212     A64cc = DAG.getConstant(Alternative, MVT::i32);
3213     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
3214                                SetCC, IfTrue, A64SELECT_CC, A64cc);
3215
3216   }
3217
3218   return A64SELECT_CC;
3219 }
3220
3221 SDValue
3222 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3223   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3224   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3225
3226   // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
3227   // rather than just 8.
3228   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
3229                        Op.getOperand(1), Op.getOperand(2),
3230                        DAG.getConstant(32, MVT::i32), 8, false, false,
3231                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
3232 }
3233
3234 SDValue
3235 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3236   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3237   // Standard, section B.3.
3238   MachineFunction &MF = DAG.getMachineFunction();
3239   AArch64MachineFunctionInfo *FuncInfo
3240     = MF.getInfo<AArch64MachineFunctionInfo>();
3241   SDLoc DL(Op);
3242
3243   SDValue Chain = Op.getOperand(0);
3244   SDValue VAList = Op.getOperand(1);
3245   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3246   SmallVector<SDValue, 4> MemOps;
3247
3248   // void *__stack at offset 0
3249   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
3250                                     getPointerTy());
3251   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3252                                 MachinePointerInfo(SV), false, false, 0));
3253
3254   // void *__gr_top at offset 8
3255   int GPRSize = FuncInfo->getVariadicGPRSize();
3256   if (GPRSize > 0) {
3257     SDValue GRTop, GRTopAddr;
3258
3259     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3260                             DAG.getConstant(8, getPointerTy()));
3261
3262     GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
3263     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3264                         DAG.getConstant(GPRSize, getPointerTy()));
3265
3266     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3267                                   MachinePointerInfo(SV, 8),
3268                                   false, false, 0));
3269   }
3270
3271   // void *__vr_top at offset 16
3272   int FPRSize = FuncInfo->getVariadicFPRSize();
3273   if (FPRSize > 0) {
3274     SDValue VRTop, VRTopAddr;
3275     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3276                             DAG.getConstant(16, getPointerTy()));
3277
3278     VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
3279     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3280                         DAG.getConstant(FPRSize, getPointerTy()));
3281
3282     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3283                                   MachinePointerInfo(SV, 16),
3284                                   false, false, 0));
3285   }
3286
3287   // int __gr_offs at offset 24
3288   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3289                                    DAG.getConstant(24, getPointerTy()));
3290   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3291                                 GROffsAddr, MachinePointerInfo(SV, 24),
3292                                 false, false, 0));
3293
3294   // int __vr_offs at offset 28
3295   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3296                                    DAG.getConstant(28, getPointerTy()));
3297   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3298                                 VROffsAddr, MachinePointerInfo(SV, 28),
3299                                 false, false, 0));
3300
3301   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3302 }
3303
3304 SDValue
3305 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3306   switch (Op.getOpcode()) {
3307   default: llvm_unreachable("Don't know how to custom lower this!");
3308   case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
3309   case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
3310   case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
3311   case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
3312   case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
3313   case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
3314   case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
3315   case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
3316   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
3317   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
3318   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
3319   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
3320
3321   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
3322   case ISD::SRL_PARTS:
3323   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
3324
3325   case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
3326   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3327   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
3328   case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
3329   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3330   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
3331   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3332   case ISD::SELECT: return LowerSELECT(Op, DAG);
3333   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
3334   case ISD::SETCC: return LowerSETCC(Op, DAG);
3335   case ISD::VACOPY: return LowerVACOPY(Op, DAG);
3336   case ISD::VASTART: return LowerVASTART(Op, DAG);
3337   case ISD::BUILD_VECTOR:
3338     return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
3339   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3340   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3341   }
3342
3343   return SDValue();
3344 }
3345
3346 /// Check if the specified splat value corresponds to a valid vector constant
3347 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI).  If
3348 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
3349 /// values.
3350 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3351                               unsigned SplatBitSize, SelectionDAG &DAG,
3352                               bool is128Bits, NeonModImmType type, EVT &VT,
3353                               unsigned &Imm, unsigned &OpCmode) {
3354   switch (SplatBitSize) {
3355   default:
3356     llvm_unreachable("unexpected size for isNeonModifiedImm");
3357   case 8: {
3358     if (type != Neon_Mov_Imm)
3359       return false;
3360     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3361     // Neon movi per byte: Op=0, Cmode=1110.
3362     OpCmode = 0xe;
3363     Imm = SplatBits;
3364     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3365     break;
3366   }
3367   case 16: {
3368     // Neon move inst per halfword
3369     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3370     if ((SplatBits & ~0xff) == 0) {
3371       // Value = 0x00nn is 0x00nn LSL 0
3372       // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
3373       // bic:  Op=1, Cmode=1001;  orr:  Op=0, Cmode=1001
3374       // Op=x, Cmode=100y
3375       Imm = SplatBits;
3376       OpCmode = 0x8;
3377       break;
3378     }
3379     if ((SplatBits & ~0xff00) == 0) {
3380       // Value = 0xnn00 is 0x00nn LSL 8
3381       // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
3382       // bic:  Op=1, Cmode=1011;  orr:  Op=0, Cmode=1011
3383       // Op=x, Cmode=101x
3384       Imm = SplatBits >> 8;
3385       OpCmode = 0xa;
3386       break;
3387     }
3388     // can't handle any other
3389     return false;
3390   }
3391
3392   case 32: {
3393     // First the LSL variants (MSL is unusable by some interested instructions).
3394
3395     // Neon move instr per word, shift zeros
3396     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3397     if ((SplatBits & ~0xff) == 0) {
3398       // Value = 0x000000nn is 0x000000nn LSL 0
3399       // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
3400       // bic:  Op=1, Cmode= 0001; orr:  Op=0, Cmode= 0001
3401       // Op=x, Cmode=000x
3402       Imm = SplatBits;
3403       OpCmode = 0;
3404       break;
3405     }
3406     if ((SplatBits & ~0xff00) == 0) {
3407       // Value = 0x0000nn00 is 0x000000nn LSL 8
3408       // movi: Op=0, Cmode= 0010;  mvni: Op=1, Cmode= 0010
3409       // bic:  Op=1, Cmode= 0011;  orr : Op=0, Cmode= 0011
3410       // Op=x, Cmode=001x
3411       Imm = SplatBits >> 8;
3412       OpCmode = 0x2;
3413       break;
3414     }
3415     if ((SplatBits & ~0xff0000) == 0) {
3416       // Value = 0x00nn0000 is 0x000000nn LSL 16
3417       // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
3418       // bic:  Op=1, Cmode= 0101; orr:  Op=0, Cmode= 0101
3419       // Op=x, Cmode=010x
3420       Imm = SplatBits >> 16;
3421       OpCmode = 0x4;
3422       break;
3423     }
3424     if ((SplatBits & ~0xff000000) == 0) {
3425       // Value = 0xnn000000 is 0x000000nn LSL 24
3426       // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
3427       // bic:  Op=1, Cmode= 0111; orr:  Op=0, Cmode= 0111
3428       // Op=x, Cmode=011x
3429       Imm = SplatBits >> 24;
3430       OpCmode = 0x6;
3431       break;
3432     }
3433
3434     // Now the MSL immediates.
3435
3436     // Neon move instr per word, shift ones
3437     if ((SplatBits & ~0xffff) == 0 &&
3438         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3439       // Value = 0x0000nnff is 0x000000nn MSL 8
3440       // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
3441       // Op=x, Cmode=1100
3442       Imm = SplatBits >> 8;
3443       OpCmode = 0xc;
3444       break;
3445     }
3446     if ((SplatBits & ~0xffffff) == 0 &&
3447         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3448       // Value = 0x00nnffff is 0x000000nn MSL 16
3449       // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
3450       // Op=x, Cmode=1101
3451       Imm = SplatBits >> 16;
3452       OpCmode = 0xd;
3453       break;
3454     }
3455     // can't handle any other
3456     return false;
3457   }
3458
3459   case 64: {
3460     if (type != Neon_Mov_Imm)
3461       return false;
3462     // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
3463     // movi Op=1, Cmode=1110.
3464     OpCmode = 0x1e;
3465     uint64_t BitMask = 0xff;
3466     uint64_t Val = 0;
3467     unsigned ImmMask = 1;
3468     Imm = 0;
3469     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3470       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3471         Val |= BitMask;
3472         Imm |= ImmMask;
3473       } else if ((SplatBits & BitMask) != 0) {
3474         return false;
3475       }
3476       BitMask <<= 8;
3477       ImmMask <<= 1;
3478     }
3479     SplatBits = Val;
3480     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3481     break;
3482   }
3483   }
3484
3485   return true;
3486 }
3487
3488 static SDValue PerformANDCombine(SDNode *N,
3489                                  TargetLowering::DAGCombinerInfo &DCI) {
3490
3491   SelectionDAG &DAG = DCI.DAG;
3492   SDLoc DL(N);
3493   EVT VT = N->getValueType(0);
3494
3495   // We're looking for an SRA/SHL pair which form an SBFX.
3496
3497   if (VT != MVT::i32 && VT != MVT::i64)
3498     return SDValue();
3499
3500   if (!isa<ConstantSDNode>(N->getOperand(1)))
3501     return SDValue();
3502
3503   uint64_t TruncMask = N->getConstantOperandVal(1);
3504   if (!isMask_64(TruncMask))
3505     return SDValue();
3506
3507   uint64_t Width = CountPopulation_64(TruncMask);
3508   SDValue Shift = N->getOperand(0);
3509
3510   if (Shift.getOpcode() != ISD::SRL)
3511     return SDValue();
3512
3513   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3514     return SDValue();
3515   uint64_t LSB = Shift->getConstantOperandVal(1);
3516
3517   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3518     return SDValue();
3519
3520   return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
3521                      DAG.getConstant(LSB, MVT::i64),
3522                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3523 }
3524
3525 /// For a true bitfield insert, the bits getting into that contiguous mask
3526 /// should come from the low part of an existing value: they must be formed from
3527 /// a compatible SHL operation (unless they're already low). This function
3528 /// checks that condition and returns the least-significant bit that's
3529 /// intended. If the operation not a field preparation, -1 is returned.
3530 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
3531                             SDValue &MaskedVal, uint64_t Mask) {
3532   if (!isShiftedMask_64(Mask))
3533     return -1;
3534
3535   // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
3536   // instruction. BFI will do a left-shift by LSB before applying the mask we've
3537   // spotted, so in general we should pre-emptively "undo" that by making sure
3538   // the incoming bits have had a right-shift applied to them.
3539   //
3540   // This right shift, however, will combine with existing left/right shifts. In
3541   // the simplest case of a completely straight bitfield operation, it will be
3542   // expected to completely cancel out with an existing SHL. More complicated
3543   // cases (e.g. bitfield to bitfield copy) may still need a real shift before
3544   // the BFI.
3545
3546   uint64_t LSB = countTrailingZeros(Mask);
3547   int64_t ShiftRightRequired = LSB;
3548   if (MaskedVal.getOpcode() == ISD::SHL &&
3549       isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3550     ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
3551     MaskedVal = MaskedVal.getOperand(0);
3552   } else if (MaskedVal.getOpcode() == ISD::SRL &&
3553              isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3554     ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
3555     MaskedVal = MaskedVal.getOperand(0);
3556   }
3557
3558   if (ShiftRightRequired > 0)
3559     MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
3560                             DAG.getConstant(ShiftRightRequired, MVT::i64));
3561   else if (ShiftRightRequired < 0) {
3562     // We could actually end up with a residual left shift, for example with
3563     // "struc.bitfield = val << 1".
3564     MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
3565                             DAG.getConstant(-ShiftRightRequired, MVT::i64));
3566   }
3567
3568   return LSB;
3569 }
3570
3571 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
3572 /// a mask and an extension. Returns true if a BFI was found and provides
3573 /// information on its surroundings.
3574 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
3575                           bool &Extended) {
3576   Extended = false;
3577   if (N.getOpcode() == ISD::ZERO_EXTEND) {
3578     Extended = true;
3579     N = N.getOperand(0);
3580   }
3581
3582   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
3583     Mask = N->getConstantOperandVal(1);
3584     N = N.getOperand(0);
3585   } else {
3586     // Mask is the whole width.
3587     Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
3588   }
3589
3590   if (N.getOpcode() == AArch64ISD::BFI) {
3591     BFI = N;
3592     return true;
3593   }
3594
3595   return false;
3596 }
3597
3598 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
3599 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
3600 /// can often be further combined with a larger mask. Ultimately, we want mask
3601 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
3602 static SDValue tryCombineToBFI(SDNode *N,
3603                                TargetLowering::DAGCombinerInfo &DCI,
3604                                const AArch64Subtarget *Subtarget) {
3605   SelectionDAG &DAG = DCI.DAG;
3606   SDLoc DL(N);
3607   EVT VT = N->getValueType(0);
3608
3609   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3610
3611   // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
3612   // abandon the effort.
3613   SDValue LHS = N->getOperand(0);
3614   if (LHS.getOpcode() != ISD::AND)
3615     return SDValue();
3616
3617   uint64_t LHSMask;
3618   if (isa<ConstantSDNode>(LHS.getOperand(1)))
3619     LHSMask = LHS->getConstantOperandVal(1);
3620   else
3621     return SDValue();
3622
3623   // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
3624   // is or abandon the effort.
3625   SDValue RHS = N->getOperand(1);
3626   if (RHS.getOpcode() != ISD::AND)
3627     return SDValue();
3628
3629   uint64_t RHSMask;
3630   if (isa<ConstantSDNode>(RHS.getOperand(1)))
3631     RHSMask = RHS->getConstantOperandVal(1);
3632   else
3633     return SDValue();
3634
3635   // Can't do anything if the masks are incompatible.
3636   if (LHSMask & RHSMask)
3637     return SDValue();
3638
3639   // Now we need one of the masks to be a contiguous field. Without loss of
3640   // generality that should be the RHS one.
3641   SDValue Bitfield = LHS.getOperand(0);
3642   if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3643     // We know that LHS is a candidate new value, and RHS isn't already a better
3644     // one.
3645     std::swap(LHS, RHS);
3646     std::swap(LHSMask, RHSMask);
3647   }
3648
3649   // We've done our best to put the right operands in the right places, all we
3650   // can do now is check whether a BFI exists.
3651   Bitfield = RHS.getOperand(0);
3652   int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3653   if (LSB == -1)
3654     return SDValue();
3655
3656   uint32_t Width = CountPopulation_64(RHSMask);
3657   assert(Width && "Expected non-zero bitfield width");
3658
3659   SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3660                             LHS.getOperand(0), Bitfield,
3661                             DAG.getConstant(LSB, MVT::i64),
3662                             DAG.getConstant(Width, MVT::i64));
3663
3664   // Mask is trivial
3665   if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3666     return BFI;
3667
3668   return DAG.getNode(ISD::AND, DL, VT, BFI,
3669                      DAG.getConstant(LHSMask | RHSMask, VT));
3670 }
3671
3672 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3673 /// original input. This is surprisingly common because SROA splits things up
3674 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3675 /// on the low (say) byte of a word. This is then orred into the rest of the
3676 /// word afterwards.
3677 ///
3678 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3679 ///
3680 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3681 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3682 /// involved.
3683 static SDValue tryCombineToLargerBFI(SDNode *N,
3684                                      TargetLowering::DAGCombinerInfo &DCI,
3685                                      const AArch64Subtarget *Subtarget) {
3686   SelectionDAG &DAG = DCI.DAG;
3687   SDLoc DL(N);
3688   EVT VT = N->getValueType(0);
3689
3690   // First job is to hunt for a MaskedBFI on either the left or right. Swap
3691   // operands if it's actually on the right.
3692   SDValue BFI;
3693   SDValue PossExtraMask;
3694   uint64_t ExistingMask = 0;
3695   bool Extended = false;
3696   if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3697     PossExtraMask = N->getOperand(1);
3698   else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3699     PossExtraMask = N->getOperand(0);
3700   else
3701     return SDValue();
3702
3703   // We can only combine a BFI with another compatible mask.
3704   if (PossExtraMask.getOpcode() != ISD::AND ||
3705       !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3706     return SDValue();
3707
3708   uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3709
3710   // Masks must be compatible.
3711   if (ExtraMask & ExistingMask)
3712     return SDValue();
3713
3714   SDValue OldBFIVal = BFI.getOperand(0);
3715   SDValue NewBFIVal = BFI.getOperand(1);
3716   if (Extended) {
3717     // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3718     // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3719     // need to be made compatible.
3720     assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3721            && "Invalid types for BFI");
3722     OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3723     NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3724   }
3725
3726   // We need the MaskedBFI to be combined with a mask of the *same* value.
3727   if (PossExtraMask.getOperand(0) != OldBFIVal)
3728     return SDValue();
3729
3730   BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3731                     OldBFIVal, NewBFIVal,
3732                     BFI.getOperand(2), BFI.getOperand(3));
3733
3734   // If the masking is trivial, we don't need to create it.
3735   if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3736     return BFI;
3737
3738   return DAG.getNode(ISD::AND, DL, VT, BFI,
3739                      DAG.getConstant(ExtraMask | ExistingMask, VT));
3740 }
3741
3742 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3743 /// searches for and classifies those shifts.
3744 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3745                          bool &FromHi) {
3746   if (N.getOpcode() == ISD::SHL)
3747     FromHi = false;
3748   else if (N.getOpcode() == ISD::SRL)
3749     FromHi = true;
3750   else
3751     return false;
3752
3753   if (!isa<ConstantSDNode>(N.getOperand(1)))
3754     return false;
3755
3756   ShiftAmount = N->getConstantOperandVal(1);
3757   Src = N->getOperand(0);
3758   return true;
3759 }
3760
3761 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3762 /// registers viewed as a high/low pair. This function looks for the pattern:
3763 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3764 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3765 /// independent.
3766 static SDValue tryCombineToEXTR(SDNode *N,
3767                                 TargetLowering::DAGCombinerInfo &DCI) {
3768   SelectionDAG &DAG = DCI.DAG;
3769   SDLoc DL(N);
3770   EVT VT = N->getValueType(0);
3771
3772   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3773
3774   if (VT != MVT::i32 && VT != MVT::i64)
3775     return SDValue();
3776
3777   SDValue LHS;
3778   uint32_t ShiftLHS = 0;
3779   bool LHSFromHi = 0;
3780   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3781     return SDValue();
3782
3783   SDValue RHS;
3784   uint32_t ShiftRHS = 0;
3785   bool RHSFromHi = 0;
3786   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3787     return SDValue();
3788
3789   // If they're both trying to come from the high part of the register, they're
3790   // not really an EXTR.
3791   if (LHSFromHi == RHSFromHi)
3792     return SDValue();
3793
3794   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3795     return SDValue();
3796
3797   if (LHSFromHi) {
3798     std::swap(LHS, RHS);
3799     std::swap(ShiftLHS, ShiftRHS);
3800   }
3801
3802   return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3803                      LHS, RHS,
3804                      DAG.getConstant(ShiftRHS, MVT::i64));
3805 }
3806
3807 /// Target-specific dag combine xforms for ISD::OR
3808 static SDValue PerformORCombine(SDNode *N,
3809                                 TargetLowering::DAGCombinerInfo &DCI,
3810                                 const AArch64Subtarget *Subtarget) {
3811
3812   SelectionDAG &DAG = DCI.DAG;
3813   SDLoc DL(N);
3814   EVT VT = N->getValueType(0);
3815
3816   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3817     return SDValue();
3818
3819   // Attempt to recognise bitfield-insert operations.
3820   SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3821   if (Res.getNode())
3822     return Res;
3823
3824   // Attempt to combine an existing MaskedBFI operation into one with a larger
3825   // mask.
3826   Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3827   if (Res.getNode())
3828     return Res;
3829
3830   Res = tryCombineToEXTR(N, DCI);
3831   if (Res.getNode())
3832     return Res;
3833
3834   if (!Subtarget->hasNEON())
3835     return SDValue();
3836
3837   // Attempt to use vector immediate-form BSL
3838   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3839
3840   SDValue N0 = N->getOperand(0);
3841   if (N0.getOpcode() != ISD::AND)
3842     return SDValue();
3843
3844   SDValue N1 = N->getOperand(1);
3845   if (N1.getOpcode() != ISD::AND)
3846     return SDValue();
3847
3848   if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3849     APInt SplatUndef;
3850     unsigned SplatBitSize;
3851     bool HasAnyUndefs;
3852     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3853     APInt SplatBits0;
3854     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3855                                       HasAnyUndefs) &&
3856         !HasAnyUndefs) {
3857       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3858       APInt SplatBits1;
3859       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3860                                         HasAnyUndefs) && !HasAnyUndefs &&
3861           SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
3862           SplatBits0 == ~SplatBits1) {
3863
3864         return DAG.getNode(ISD::VSELECT, DL, VT, N0->getOperand(1),
3865                            N0->getOperand(0), N1->getOperand(0));
3866       }
3867     }
3868   }
3869
3870   return SDValue();
3871 }
3872
3873 /// Target-specific dag combine xforms for ISD::SRA
3874 static SDValue PerformSRACombine(SDNode *N,
3875                                  TargetLowering::DAGCombinerInfo &DCI) {
3876
3877   SelectionDAG &DAG = DCI.DAG;
3878   SDLoc DL(N);
3879   EVT VT = N->getValueType(0);
3880
3881   // We're looking for an SRA/SHL pair which form an SBFX.
3882
3883   if (VT != MVT::i32 && VT != MVT::i64)
3884     return SDValue();
3885
3886   if (!isa<ConstantSDNode>(N->getOperand(1)))
3887     return SDValue();
3888
3889   uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3890   SDValue Shift = N->getOperand(0);
3891
3892   if (Shift.getOpcode() != ISD::SHL)
3893     return SDValue();
3894
3895   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3896     return SDValue();
3897
3898   uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3899   uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3900   uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3901
3902   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3903     return SDValue();
3904
3905   return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3906                      DAG.getConstant(LSB, MVT::i64),
3907                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3908 }
3909
3910 /// Check if this is a valid build_vector for the immediate operand of
3911 /// a vector shift operation, where all the elements of the build_vector
3912 /// must have the same constant integer value.
3913 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3914   // Ignore bit_converts.
3915   while (Op.getOpcode() == ISD::BITCAST)
3916     Op = Op.getOperand(0);
3917   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3918   APInt SplatBits, SplatUndef;
3919   unsigned SplatBitSize;
3920   bool HasAnyUndefs;
3921   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3922                                       HasAnyUndefs, ElementBits) ||
3923       SplatBitSize > ElementBits)
3924     return false;
3925   Cnt = SplatBits.getSExtValue();
3926   return true;
3927 }
3928
3929 /// Check if this is a valid build_vector for the immediate operand of
3930 /// a vector shift left operation.  That value must be in the range:
3931 /// 0 <= Value < ElementBits
3932 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3933   assert(VT.isVector() && "vector shift count is not a vector type");
3934   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3935   if (!getVShiftImm(Op, ElementBits, Cnt))
3936     return false;
3937   return (Cnt >= 0 && Cnt < ElementBits);
3938 }
3939
3940 /// Check if this is a valid build_vector for the immediate operand of a
3941 /// vector shift right operation. The value must be in the range:
3942 ///   1 <= Value <= ElementBits
3943 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3944   assert(VT.isVector() && "vector shift count is not a vector type");
3945   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3946   if (!getVShiftImm(Op, ElementBits, Cnt))
3947     return false;
3948   return (Cnt >= 1 && Cnt <= ElementBits);
3949 }
3950
3951 static SDValue GenForSextInreg(SDNode *N,
3952                                TargetLowering::DAGCombinerInfo &DCI,
3953                                EVT SrcVT, EVT DestVT, EVT SubRegVT,
3954                                const int *Mask, SDValue Src) {
3955   SelectionDAG &DAG = DCI.DAG;
3956   SDValue Bitcast
3957     = DAG.getNode(ISD::BITCAST, SDLoc(N), SrcVT, Src);
3958   SDValue Sext
3959     = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), DestVT, Bitcast);
3960   SDValue ShuffleVec
3961     = DAG.getVectorShuffle(DestVT, SDLoc(N), Sext, DAG.getUNDEF(DestVT), Mask);
3962   SDValue ExtractSubreg
3963     = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, SDLoc(N),
3964                 SubRegVT, ShuffleVec,
3965                 DAG.getTargetConstant(AArch64::sub_64, MVT::i32)), 0);
3966   return ExtractSubreg;
3967 }
3968
3969 /// Checks for vector shifts and lowers them.
3970 static SDValue PerformShiftCombine(SDNode *N,
3971                                    TargetLowering::DAGCombinerInfo &DCI,
3972                                    const AArch64Subtarget *ST) {
3973   SelectionDAG &DAG = DCI.DAG;
3974   EVT VT = N->getValueType(0);
3975   if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3976     return PerformSRACombine(N, DCI);
3977
3978   // We're looking for an SRA/SHL pair to help generating instruction
3979   //   sshll  v0.8h, v0.8b, #0
3980   // The instruction STXL is also the alias of this instruction.
3981   //
3982   // For example, for DAG like below,
3983   //   v2i32 = sra (v2i32 (shl v2i32, 16)), 16
3984   // we can transform it into
3985   //   v2i32 = EXTRACT_SUBREG 
3986   //             (v4i32 (suffle_vector
3987   //                       (v4i32 (sext (v4i16 (bitcast v2i32))), 
3988   //                       undef, (0, 2, u, u)),
3989   //             sub_64
3990   //
3991   // With this transformation we expect to generate "SSHLL + UZIP1"
3992   // Sometimes UZIP1 can be optimized away by combining with other context.
3993   int64_t ShrCnt, ShlCnt;
3994   if (N->getOpcode() == ISD::SRA
3995       && (VT == MVT::v2i32 || VT == MVT::v4i16)
3996       && isVShiftRImm(N->getOperand(1), VT, ShrCnt)
3997       && N->getOperand(0).getOpcode() == ISD::SHL
3998       && isVShiftRImm(N->getOperand(0).getOperand(1), VT, ShlCnt)) {
3999     SDValue Src = N->getOperand(0).getOperand(0);
4000     if (VT == MVT::v2i32 && ShrCnt == 16 && ShlCnt == 16) {
4001       // sext_inreg(v2i32, v2i16)
4002       // We essentially only care the Mask {0, 2, u, u}
4003       int Mask[4] = {0, 2, 4, 6};
4004       return GenForSextInreg(N, DCI, MVT::v4i16, MVT::v4i32, MVT::v2i32,
4005                              Mask, Src); 
4006     }
4007     else if (VT == MVT::v2i32 && ShrCnt == 24 && ShlCnt == 24) {
4008       // sext_inreg(v2i16, v2i8)
4009       // We essentially only care the Mask {0, u, 4, u, u, u, u, u, u, u, u, u}
4010       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
4011       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v2i32,
4012                              Mask, Src);
4013     }
4014     else if (VT == MVT::v4i16 && ShrCnt == 8 && ShlCnt == 8) {
4015       // sext_inreg(v4i16, v4i8)
4016       // We essentially only care the Mask {0, 2, 4, 6, u, u, u, u, u, u, u, u}
4017       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
4018       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v4i16,
4019                              Mask, Src);
4020     }
4021   }
4022
4023   // Nothing to be done for scalar shifts.
4024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4025   if (!VT.isVector() || !TLI.isTypeLegal(VT))
4026     return SDValue();
4027
4028   assert(ST->hasNEON() && "unexpected vector shift");
4029   int64_t Cnt;
4030
4031   switch (N->getOpcode()) {
4032   default:
4033     llvm_unreachable("unexpected shift opcode");
4034
4035   case ISD::SHL:
4036     if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
4037       SDValue RHS =
4038           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
4039                       DAG.getConstant(Cnt, MVT::i32));
4040       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
4041     }
4042     break;
4043
4044   case ISD::SRA:
4045   case ISD::SRL:
4046     if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
4047       SDValue RHS =
4048           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
4049                       DAG.getConstant(Cnt, MVT::i32));
4050       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
4051     }
4052     break;
4053   }
4054
4055   return SDValue();
4056 }
4057
4058 /// ARM-specific DAG combining for intrinsics.
4059 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
4060   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4061
4062   switch (IntNo) {
4063   default:
4064     // Don't do anything for most intrinsics.
4065     break;
4066
4067   case Intrinsic::arm_neon_vqshifts:
4068   case Intrinsic::arm_neon_vqshiftu:
4069     EVT VT = N->getOperand(1).getValueType();
4070     int64_t Cnt;
4071     if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
4072       break;
4073     unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
4074                              ? AArch64ISD::NEON_QSHLs
4075                              : AArch64ISD::NEON_QSHLu;
4076     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
4077                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
4078   }
4079
4080   return SDValue();
4081 }
4082
4083 /// Target-specific DAG combine function for NEON load/store intrinsics
4084 /// to merge base address updates.
4085 static SDValue CombineBaseUpdate(SDNode *N,
4086                                  TargetLowering::DAGCombinerInfo &DCI) {
4087   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
4088     return SDValue();
4089
4090   SelectionDAG &DAG = DCI.DAG;
4091   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
4092                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
4093   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
4094   SDValue Addr = N->getOperand(AddrOpIdx);
4095
4096   // Search for a use of the address operand that is an increment.
4097   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
4098        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
4099     SDNode *User = *UI;
4100     if (User->getOpcode() != ISD::ADD ||
4101         UI.getUse().getResNo() != Addr.getResNo())
4102       continue;
4103
4104     // Check that the add is independent of the load/store.  Otherwise, folding
4105     // it would create a cycle.
4106     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
4107       continue;
4108
4109     // Find the new opcode for the updating load/store.
4110     bool isLoad = true;
4111     bool isLaneOp = false;
4112     unsigned NewOpc = 0;
4113     unsigned NumVecs = 0;
4114     if (isIntrinsic) {
4115       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
4116       switch (IntNo) {
4117       default: llvm_unreachable("unexpected intrinsic for Neon base update");
4118       case Intrinsic::arm_neon_vld1:       NewOpc = AArch64ISD::NEON_LD1_UPD;
4119         NumVecs = 1; break;
4120       case Intrinsic::arm_neon_vld2:       NewOpc = AArch64ISD::NEON_LD2_UPD;
4121         NumVecs = 2; break;
4122       case Intrinsic::arm_neon_vld3:       NewOpc = AArch64ISD::NEON_LD3_UPD;
4123         NumVecs = 3; break;
4124       case Intrinsic::arm_neon_vld4:       NewOpc = AArch64ISD::NEON_LD4_UPD;
4125         NumVecs = 4; break;
4126       case Intrinsic::arm_neon_vst1:       NewOpc = AArch64ISD::NEON_ST1_UPD;
4127         NumVecs = 1; isLoad = false; break;
4128       case Intrinsic::arm_neon_vst2:       NewOpc = AArch64ISD::NEON_ST2_UPD;
4129         NumVecs = 2; isLoad = false; break;
4130       case Intrinsic::arm_neon_vst3:       NewOpc = AArch64ISD::NEON_ST3_UPD;
4131         NumVecs = 3; isLoad = false; break;
4132       case Intrinsic::arm_neon_vst4:       NewOpc = AArch64ISD::NEON_ST4_UPD;
4133         NumVecs = 4; isLoad = false; break;
4134       case Intrinsic::aarch64_neon_vld1x2: NewOpc = AArch64ISD::NEON_LD1x2_UPD;
4135         NumVecs = 2; break;
4136       case Intrinsic::aarch64_neon_vld1x3: NewOpc = AArch64ISD::NEON_LD1x3_UPD;
4137         NumVecs = 3; break;
4138       case Intrinsic::aarch64_neon_vld1x4: NewOpc = AArch64ISD::NEON_LD1x4_UPD;
4139         NumVecs = 4; break;
4140       case Intrinsic::aarch64_neon_vst1x2: NewOpc = AArch64ISD::NEON_ST1x2_UPD;
4141         NumVecs = 2; isLoad = false; break;
4142       case Intrinsic::aarch64_neon_vst1x3: NewOpc = AArch64ISD::NEON_ST1x3_UPD;
4143         NumVecs = 3; isLoad = false; break;
4144       case Intrinsic::aarch64_neon_vst1x4: NewOpc = AArch64ISD::NEON_ST1x4_UPD;
4145         NumVecs = 4; isLoad = false; break;
4146       case Intrinsic::arm_neon_vld2lane:   NewOpc = AArch64ISD::NEON_LD2LN_UPD;
4147         NumVecs = 2; isLaneOp = true; break;
4148       case Intrinsic::arm_neon_vld3lane:   NewOpc = AArch64ISD::NEON_LD3LN_UPD;
4149         NumVecs = 3; isLaneOp = true; break;
4150       case Intrinsic::arm_neon_vld4lane:   NewOpc = AArch64ISD::NEON_LD4LN_UPD;
4151         NumVecs = 4; isLaneOp = true; break;
4152       case Intrinsic::arm_neon_vst2lane:   NewOpc = AArch64ISD::NEON_ST2LN_UPD;
4153         NumVecs = 2; isLoad = false; isLaneOp = true; break;
4154       case Intrinsic::arm_neon_vst3lane:   NewOpc = AArch64ISD::NEON_ST3LN_UPD;
4155         NumVecs = 3; isLoad = false; isLaneOp = true; break;
4156       case Intrinsic::arm_neon_vst4lane:   NewOpc = AArch64ISD::NEON_ST4LN_UPD;
4157         NumVecs = 4; isLoad = false; isLaneOp = true; break;
4158       }
4159     } else {
4160       isLaneOp = true;
4161       switch (N->getOpcode()) {
4162       default: llvm_unreachable("unexpected opcode for Neon base update");
4163       case AArch64ISD::NEON_LD2DUP: NewOpc = AArch64ISD::NEON_LD2DUP_UPD;
4164         NumVecs = 2; break;
4165       case AArch64ISD::NEON_LD3DUP: NewOpc = AArch64ISD::NEON_LD3DUP_UPD;
4166         NumVecs = 3; break;
4167       case AArch64ISD::NEON_LD4DUP: NewOpc = AArch64ISD::NEON_LD4DUP_UPD;
4168         NumVecs = 4; break;
4169       }
4170     }
4171
4172     // Find the size of memory referenced by the load/store.
4173     EVT VecTy;
4174     if (isLoad)
4175       VecTy = N->getValueType(0);
4176     else
4177       VecTy = N->getOperand(AddrOpIdx + 1).getValueType();
4178     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
4179     if (isLaneOp)
4180       NumBytes /= VecTy.getVectorNumElements();
4181
4182     // If the increment is a constant, it must match the memory ref size.
4183     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
4184     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
4185       uint32_t IncVal = CInc->getZExtValue();
4186       if (IncVal != NumBytes)
4187         continue;
4188       Inc = DAG.getTargetConstant(IncVal, MVT::i32);
4189     }
4190
4191     // Create the new updating load/store node.
4192     EVT Tys[6];
4193     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
4194     unsigned n;
4195     for (n = 0; n < NumResultVecs; ++n)
4196       Tys[n] = VecTy;
4197     Tys[n++] = MVT::i64;
4198     Tys[n] = MVT::Other;
4199     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs + 2));
4200     SmallVector<SDValue, 8> Ops;
4201     Ops.push_back(N->getOperand(0)); // incoming chain
4202     Ops.push_back(N->getOperand(AddrOpIdx));
4203     Ops.push_back(Inc);
4204     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
4205       Ops.push_back(N->getOperand(i));
4206     }
4207     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
4208     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
4209                                            Ops, MemInt->getMemoryVT(),
4210                                            MemInt->getMemOperand());
4211
4212     // Update the uses.
4213     std::vector<SDValue> NewResults;
4214     for (unsigned i = 0; i < NumResultVecs; ++i) {
4215       NewResults.push_back(SDValue(UpdN.getNode(), i));
4216     }
4217     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
4218     DCI.CombineTo(N, NewResults);
4219     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
4220
4221     break;
4222   }
4223   return SDValue();
4224 }
4225
4226 /// For a VDUPLANE node N, check if its source operand is a vldN-lane (N > 1)
4227 /// intrinsic, and if all the other uses of that intrinsic are also VDUPLANEs.
4228 /// If so, combine them to a vldN-dup operation and return true.
4229 static SDValue CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
4230   SelectionDAG &DAG = DCI.DAG;
4231   EVT VT = N->getValueType(0);
4232
4233   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
4234   SDNode *VLD = N->getOperand(0).getNode();
4235   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
4236     return SDValue();
4237   unsigned NumVecs = 0;
4238   unsigned NewOpc = 0;
4239   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
4240   if (IntNo == Intrinsic::arm_neon_vld2lane) {
4241     NumVecs = 2;
4242     NewOpc = AArch64ISD::NEON_LD2DUP;
4243   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
4244     NumVecs = 3;
4245     NewOpc = AArch64ISD::NEON_LD3DUP;
4246   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
4247     NumVecs = 4;
4248     NewOpc = AArch64ISD::NEON_LD4DUP;
4249   } else {
4250     return SDValue();
4251   }
4252
4253   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
4254   // numbers match the load.
4255   unsigned VLDLaneNo =
4256       cast<ConstantSDNode>(VLD->getOperand(NumVecs + 3))->getZExtValue();
4257   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
4258        UI != UE; ++UI) {
4259     // Ignore uses of the chain result.
4260     if (UI.getUse().getResNo() == NumVecs)
4261       continue;
4262     SDNode *User = *UI;
4263     if (User->getOpcode() != AArch64ISD::NEON_VDUPLANE ||
4264         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
4265       return SDValue();
4266   }
4267
4268   // Create the vldN-dup node.
4269   EVT Tys[5];
4270   unsigned n;
4271   for (n = 0; n < NumVecs; ++n)
4272     Tys[n] = VT;
4273   Tys[n] = MVT::Other;
4274   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs + 1));
4275   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
4276   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
4277   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, Ops,
4278                                            VLDMemInt->getMemoryVT(),
4279                                            VLDMemInt->getMemOperand());
4280
4281   // Update the uses.
4282   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
4283        UI != UE; ++UI) {
4284     unsigned ResNo = UI.getUse().getResNo();
4285     // Ignore uses of the chain result.
4286     if (ResNo == NumVecs)
4287       continue;
4288     SDNode *User = *UI;
4289     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
4290   }
4291
4292   // Now the vldN-lane intrinsic is dead except for its chain result.
4293   // Update uses of the chain.
4294   std::vector<SDValue> VLDDupResults;
4295   for (unsigned n = 0; n < NumVecs; ++n)
4296     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
4297   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
4298   DCI.CombineTo(VLD, VLDDupResults);
4299
4300   return SDValue(N, 0);
4301 }
4302
4303 // vselect (v1i1 setcc) ->
4304 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
4305 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
4306 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
4307 // such VSELECT.
4308 static SDValue PerformVSelectCombine(SDNode *N, SelectionDAG &DAG) {
4309   SDValue N0 = N->getOperand(0);
4310   EVT CCVT = N0.getValueType();
4311
4312   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
4313       CCVT.getVectorElementType() != MVT::i1)
4314     return SDValue();
4315
4316   EVT ResVT = N->getValueType(0);
4317   EVT CmpVT = N0.getOperand(0).getValueType();
4318   // Only combine when the result type is of the same size as the compared
4319   // operands.
4320   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
4321     return SDValue();
4322
4323   SDValue IfTrue = N->getOperand(1);
4324   SDValue IfFalse = N->getOperand(2);
4325   SDValue SetCC =
4326       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
4327                    N0.getOperand(0), N0.getOperand(1),
4328                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
4329   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
4330                      IfTrue, IfFalse);
4331 }
4332
4333 // sign_extend (extract_vector_elt (v1i1 setcc)) ->
4334 //     extract_vector_elt (v1iXX setcc)
4335 // (XX is the size of the compared operand type)
4336 static SDValue PerformSignExtendCombine(SDNode *N, SelectionDAG &DAG) {
4337   SDValue N0 = N->getOperand(0);
4338   SDValue Vec = N0.getOperand(0);
4339
4340   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4341       Vec.getOpcode() != ISD::SETCC)
4342     return SDValue();
4343
4344   EVT ResVT = N->getValueType(0);
4345   EVT CmpVT = Vec.getOperand(0).getValueType();
4346   // Only optimize when the result type is of the same size as the element
4347   // type of the compared operand.
4348   if (ResVT.getSizeInBits() != CmpVT.getVectorElementType().getSizeInBits())
4349     return SDValue();
4350
4351   SDValue Lane = N0.getOperand(1);
4352   SDValue SetCC =
4353       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
4354                    Vec.getOperand(0), Vec.getOperand(1),
4355                    cast<CondCodeSDNode>(Vec.getOperand(2))->get());
4356   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ResVT,
4357                      SetCC, Lane);
4358 }
4359
4360 SDValue
4361 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
4362                                          DAGCombinerInfo &DCI) const {
4363   switch (N->getOpcode()) {
4364   default: break;
4365   case ISD::AND: return PerformANDCombine(N, DCI);
4366   case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
4367   case ISD::SHL:
4368   case ISD::SRA:
4369   case ISD::SRL:
4370     return PerformShiftCombine(N, DCI, getSubtarget());
4371   case ISD::VSELECT: return PerformVSelectCombine(N, DCI.DAG);
4372   case ISD::SIGN_EXTEND: return PerformSignExtendCombine(N, DCI.DAG);
4373   case ISD::INTRINSIC_WO_CHAIN:
4374     return PerformIntrinsicCombine(N, DCI.DAG);
4375   case AArch64ISD::NEON_VDUPLANE:
4376     return CombineVLDDUP(N, DCI);
4377   case AArch64ISD::NEON_LD2DUP:
4378   case AArch64ISD::NEON_LD3DUP:
4379   case AArch64ISD::NEON_LD4DUP:
4380     return CombineBaseUpdate(N, DCI);
4381   case ISD::INTRINSIC_VOID:
4382   case ISD::INTRINSIC_W_CHAIN:
4383     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
4384     case Intrinsic::arm_neon_vld1:
4385     case Intrinsic::arm_neon_vld2:
4386     case Intrinsic::arm_neon_vld3:
4387     case Intrinsic::arm_neon_vld4:
4388     case Intrinsic::arm_neon_vst1:
4389     case Intrinsic::arm_neon_vst2:
4390     case Intrinsic::arm_neon_vst3:
4391     case Intrinsic::arm_neon_vst4:
4392     case Intrinsic::arm_neon_vld2lane:
4393     case Intrinsic::arm_neon_vld3lane:
4394     case Intrinsic::arm_neon_vld4lane:
4395     case Intrinsic::aarch64_neon_vld1x2:
4396     case Intrinsic::aarch64_neon_vld1x3:
4397     case Intrinsic::aarch64_neon_vld1x4:
4398     case Intrinsic::aarch64_neon_vst1x2:
4399     case Intrinsic::aarch64_neon_vst1x3:
4400     case Intrinsic::aarch64_neon_vst1x4:
4401     case Intrinsic::arm_neon_vst2lane:
4402     case Intrinsic::arm_neon_vst3lane:
4403     case Intrinsic::arm_neon_vst4lane:
4404       return CombineBaseUpdate(N, DCI);
4405     default:
4406       break;
4407     }
4408   }
4409   return SDValue();
4410 }
4411
4412 bool
4413 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
4414   VT = VT.getScalarType();
4415
4416   if (!VT.isSimple())
4417     return false;
4418
4419   switch (VT.getSimpleVT().SimpleTy) {
4420   case MVT::f16:
4421   case MVT::f32:
4422   case MVT::f64:
4423     return true;
4424   case MVT::f128:
4425     return false;
4426   default:
4427     break;
4428   }
4429
4430   return false;
4431 }
4432
4433 bool AArch64TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
4434                                                           unsigned AddrSpace,
4435                                                           bool *Fast) const {
4436   const AArch64Subtarget *Subtarget = getSubtarget();
4437   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
4438   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
4439
4440   switch (VT.getSimpleVT().SimpleTy) {
4441   default:
4442     return false;
4443   // Scalar types
4444   case MVT::i8:  case MVT::i16:
4445   case MVT::i32: case MVT::i64:
4446   case MVT::f32: case MVT::f64: {
4447     // Unaligned access can use (for example) LRDB, LRDH, LDRW
4448     if (AllowsUnaligned) {
4449       if (Fast)
4450         *Fast = true;
4451       return true;
4452     }
4453     return false;
4454   }
4455   // 64-bit vector types
4456   case MVT::v8i8:  case MVT::v4i16:
4457   case MVT::v2i32: case MVT::v1i64:
4458   case MVT::v2f32: case MVT::v1f64:
4459   // 128-bit vector types
4460   case MVT::v16i8: case MVT::v8i16:
4461   case MVT::v4i32: case MVT::v2i64:
4462   case MVT::v4f32: case MVT::v2f64: {
4463     // For any little-endian targets with neon, we can support unaligned
4464     // load/store of V registers using ld1/st1.
4465     // A big-endian target may also explicitly support unaligned accesses
4466     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
4467       if (Fast)
4468         *Fast = true;
4469       return true;
4470     }
4471     return false;
4472   }
4473   }
4474 }
4475
4476 // Check whether a shuffle_vector could be presented as concat_vector.
4477 bool AArch64TargetLowering::isConcatVector(SDValue Op, SelectionDAG &DAG,
4478                                            SDValue V0, SDValue V1,
4479                                            const int *Mask,
4480                                            SDValue &Res) const {
4481   SDLoc DL(Op);
4482   EVT VT = Op.getValueType();
4483   if (VT.getSizeInBits() != 128)
4484     return false;
4485   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4486       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4487     return false;
4488
4489   unsigned NumElts = VT.getVectorNumElements();
4490   bool isContactVector = true;
4491   bool splitV0 = false;
4492   if (V0.getValueType().getSizeInBits() == 128)
4493     splitV0 = true;
4494
4495   for (int I = 0, E = NumElts / 2; I != E; I++) {
4496     if (Mask[I] != I) {
4497       isContactVector = false;
4498       break;
4499     }
4500   }
4501
4502   if (isContactVector) {
4503     int offset = NumElts / 2;
4504     for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4505       if (Mask[I] != I + splitV0 * offset) {
4506         isContactVector = false;
4507         break;
4508       }
4509     }
4510   }
4511
4512   if (isContactVector) {
4513     EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4514                                   NumElts / 2);
4515     if (splitV0) {
4516       V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4517                        DAG.getConstant(0, MVT::i64));
4518     }
4519     if (V1.getValueType().getSizeInBits() == 128) {
4520       V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4521                        DAG.getConstant(0, MVT::i64));
4522     }
4523     Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4524     return true;
4525   }
4526   return false;
4527 }
4528
4529 // Check whether a Build Vector could be presented as Shuffle Vector.
4530 // This Shuffle Vector maybe not legalized, so the length of its operand and
4531 // the length of result may not equal.
4532 bool AArch64TargetLowering::isKnownShuffleVector(SDValue Op, SelectionDAG &DAG,
4533                                                  SDValue &V0, SDValue &V1,
4534                                                  int *Mask) const {
4535   SDLoc DL(Op);
4536   EVT VT = Op.getValueType();
4537   unsigned NumElts = VT.getVectorNumElements();
4538   unsigned V0NumElts = 0;
4539
4540   // Check if all elements are extracted from less than 3 vectors.
4541   for (unsigned i = 0; i < NumElts; ++i) {
4542     SDValue Elt = Op.getOperand(i);
4543     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4544         Elt.getOperand(0).getValueType().getVectorElementType() !=
4545             VT.getVectorElementType())
4546       return false;
4547
4548     if (!V0.getNode()) {
4549       V0 = Elt.getOperand(0);
4550       V0NumElts = V0.getValueType().getVectorNumElements();
4551     }
4552     if (Elt.getOperand(0) == V0) {
4553       Mask[i] = (cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue());
4554       continue;
4555     } else if (!V1.getNode()) {
4556       V1 = Elt.getOperand(0);
4557     }
4558     if (Elt.getOperand(0) == V1) {
4559       unsigned Lane = cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue();
4560       Mask[i] = (Lane + V0NumElts);
4561       continue;
4562     } else {
4563       return false;
4564     }
4565   }
4566   return true;
4567 }
4568
4569 // LowerShiftRightParts - Lower SRL_PARTS and SRA_PARTS, which returns two
4570 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4571 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4572                                                 SelectionDAG &DAG) const {
4573   assert(Op.getNumOperands() == 3 && "Not a quad-shift!");
4574   EVT VT = Op.getValueType();
4575   unsigned VTBits = VT.getSizeInBits();
4576   SDLoc dl(Op);
4577   SDValue ShOpLo = Op.getOperand(0);
4578   SDValue ShOpHi = Op.getOperand(1);
4579   SDValue ShAmt  = Op.getOperand(2);
4580   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4581
4582   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4583   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4584                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
4585   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4586   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4587                                    DAG.getConstant(VTBits, MVT::i64));
4588   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4589   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4590   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4591   SDValue Tmp3 = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4592
4593   SDValue A64cc;
4594   SDValue CmpOp = getSelectableIntSetCC(ExtraShAmt,
4595                                         DAG.getConstant(0, MVT::i64),
4596                                         ISD::SETGE, A64cc,
4597                                         DAG, dl);
4598
4599   SDValue Hi = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
4600                            DAG.getConstant(0, Tmp3.getValueType()), Tmp3,
4601                            A64cc);
4602   SDValue Lo = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
4603                            TrueVal, FalseVal, A64cc);
4604
4605   SDValue Ops[2] = { Lo, Hi };
4606   return DAG.getMergeValues(Ops, dl);
4607 }
4608
4609 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4610 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4611 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4612                                                SelectionDAG &DAG) const {
4613   assert(Op.getNumOperands() == 3 && "Not a quad-shift!");
4614   EVT VT = Op.getValueType();
4615   unsigned VTBits = VT.getSizeInBits();
4616   SDLoc dl(Op);
4617   SDValue ShOpLo = Op.getOperand(0);
4618   SDValue ShOpHi = Op.getOperand(1);
4619   SDValue ShAmt  = Op.getOperand(2);
4620
4621   assert(Op.getOpcode() == ISD::SHL_PARTS);
4622   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4623                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
4624   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4625   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4626                                    DAG.getConstant(VTBits, MVT::i64));
4627   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4628   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4629   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4630   SDValue Tmp4 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4631
4632   SDValue A64cc;
4633   SDValue CmpOp = getSelectableIntSetCC(ExtraShAmt,
4634                                         DAG.getConstant(0, MVT::i64),
4635                                         ISD::SETGE, A64cc,
4636                                         DAG, dl);
4637
4638   SDValue Lo = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
4639                            DAG.getConstant(0, Tmp4.getValueType()), Tmp4,
4640                            A64cc);
4641   SDValue Hi = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
4642                            Tmp3, FalseVal, A64cc);
4643
4644   SDValue Ops[2] = { Lo, Hi };
4645   return DAG.getMergeValues(Ops, dl);
4646 }
4647
4648 // If this is a case we can't handle, return null and let the default
4649 // expansion code take care of it.
4650 SDValue
4651 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4652                                          const AArch64Subtarget *ST) const {
4653
4654   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4655   SDLoc DL(Op);
4656   EVT VT = Op.getValueType();
4657
4658   APInt SplatBits, SplatUndef;
4659   unsigned SplatBitSize;
4660   bool HasAnyUndefs;
4661
4662   unsigned UseNeonMov = VT.getSizeInBits() >= 64;
4663
4664   // Note we favor lowering MOVI over MVNI.
4665   // This has implications on the definition of patterns in TableGen to select
4666   // BIC immediate instructions but not ORR immediate instructions.
4667   // If this lowering order is changed, TableGen patterns for BIC immediate and
4668   // ORR immediate instructions have to be updated.
4669   if (UseNeonMov &&
4670       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4671     if (SplatBitSize <= 64) {
4672       // First attempt to use vector immediate-form MOVI
4673       EVT NeonMovVT;
4674       unsigned Imm = 0;
4675       unsigned OpCmode = 0;
4676
4677       if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
4678                             SplatBitSize, DAG, VT.is128BitVector(),
4679                             Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
4680         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4681         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4682
4683         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4684           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
4685                                         ImmVal, OpCmodeVal);
4686           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4687         }
4688       }
4689
4690       // Then attempt to use vector immediate-form MVNI
4691       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4692       if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
4693                             DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
4694                             Imm, OpCmode)) {
4695         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4696         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4697         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4698           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
4699                                         ImmVal, OpCmodeVal);
4700           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4701         }
4702       }
4703
4704       // Attempt to use vector immediate-form FMOV
4705       if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
4706           (VT == MVT::v2f64 && SplatBitSize == 64)) {
4707         APFloat RealVal(
4708             SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
4709             SplatBits);
4710         uint32_t ImmVal;
4711         if (A64Imms::isFPImm(RealVal, ImmVal)) {
4712           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4713           return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
4714         }
4715       }
4716     }
4717   }
4718
4719   unsigned NumElts = VT.getVectorNumElements();
4720   bool isOnlyLowElement = true;
4721   bool usesOnlyOneValue = true;
4722   bool hasDominantValue = false;
4723   bool isConstant = true;
4724
4725   // Map of the number of times a particular SDValue appears in the
4726   // element list.
4727   DenseMap<SDValue, unsigned> ValueCounts;
4728   SDValue Value;
4729   for (unsigned i = 0; i < NumElts; ++i) {
4730     SDValue V = Op.getOperand(i);
4731     if (V.getOpcode() == ISD::UNDEF)
4732       continue;
4733     if (i > 0)
4734       isOnlyLowElement = false;
4735     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4736       isConstant = false;
4737
4738     ValueCounts.insert(std::make_pair(V, 0));
4739     unsigned &Count = ValueCounts[V];
4740
4741     // Is this value dominant? (takes up more than half of the lanes)
4742     if (++Count > (NumElts / 2)) {
4743       hasDominantValue = true;
4744       Value = V;
4745     }
4746   }
4747   if (ValueCounts.size() != 1)
4748     usesOnlyOneValue = false;
4749   if (!Value.getNode() && ValueCounts.size() > 0)
4750     Value = ValueCounts.begin()->first;
4751
4752   if (ValueCounts.size() == 0)
4753     return DAG.getUNDEF(VT);
4754
4755   if (isOnlyLowElement)
4756     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4757
4758   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4759   if (hasDominantValue && EltSize <= 64) {
4760     // Use VDUP for non-constant splats.
4761     if (!isConstant) {
4762       SDValue N;
4763
4764       // If we are DUPing a value that comes directly from a vector, we could
4765       // just use DUPLANE. We can only do this if the lane being extracted
4766       // is at a constant index, as the DUP from lane instructions only have
4767       // constant-index forms.
4768       //
4769       // If there is a TRUNCATE between EXTRACT_VECTOR_ELT and DUP, we can
4770       // remove TRUNCATE for DUPLANE by apdating the source vector to
4771       // appropriate vector type and lane index.
4772       //
4773       // FIXME: for now we have v1i8, v1i16, v1i32 legal vector types, if they
4774       // are not legal any more, no need to check the type size in bits should
4775       // be large than 64.
4776       SDValue V = Value;
4777       if (Value->getOpcode() == ISD::TRUNCATE)
4778         V = Value->getOperand(0);
4779       if (V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4780           isa<ConstantSDNode>(V->getOperand(1)) &&
4781           V->getOperand(0).getValueType().getSizeInBits() >= 64) {
4782
4783         // If the element size of source vector is larger than DUPLANE
4784         // element size, we can do transformation by,
4785         // 1) bitcasting source register to smaller element vector
4786         // 2) mutiplying the lane index by SrcEltSize/ResEltSize
4787         // For example, we can lower
4788         //     "v8i16 vdup_lane(v4i32, 1)"
4789         // to be
4790         //     "v8i16 vdup_lane(v8i16 bitcast(v4i32), 2)".
4791         SDValue SrcVec = V->getOperand(0);
4792         unsigned SrcEltSize =
4793             SrcVec.getValueType().getVectorElementType().getSizeInBits();
4794         unsigned ResEltSize = VT.getVectorElementType().getSizeInBits();
4795         if (SrcEltSize > ResEltSize) {
4796           assert((SrcEltSize % ResEltSize == 0) && "Invalid element size");
4797           SDValue BitCast;
4798           unsigned SrcSize = SrcVec.getValueType().getSizeInBits();
4799           unsigned ResSize = VT.getSizeInBits();
4800
4801           if (SrcSize > ResSize) {
4802             assert((SrcSize % ResSize == 0) && "Invalid vector size");
4803             EVT CastVT =
4804                 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4805                                  SrcSize / ResEltSize);
4806             BitCast = DAG.getNode(ISD::BITCAST, DL, CastVT, SrcVec);
4807           } else {
4808             assert((SrcSize == ResSize) && "Invalid vector size of source vec");
4809             BitCast = DAG.getNode(ISD::BITCAST, DL, VT, SrcVec);
4810           }
4811
4812           unsigned LaneIdx = V->getConstantOperandVal(1);
4813           SDValue Lane =
4814               DAG.getConstant((SrcEltSize / ResEltSize) * LaneIdx, MVT::i64);
4815           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, BitCast, Lane);
4816         } else {
4817           assert((SrcEltSize == ResEltSize) &&
4818                  "Invalid element size of source vec");
4819           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, V->getOperand(0),
4820                           V->getOperand(1));
4821         }
4822       } else
4823         N = DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4824
4825       if (!usesOnlyOneValue) {
4826         // The dominant value was splatted as 'N', but we now have to insert
4827         // all differing elements.
4828         for (unsigned I = 0; I < NumElts; ++I) {
4829           if (Op.getOperand(I) == Value)
4830             continue;
4831           SmallVector<SDValue, 3> Ops;
4832           Ops.push_back(N);
4833           Ops.push_back(Op.getOperand(I));
4834           Ops.push_back(DAG.getConstant(I, MVT::i64));
4835           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Ops);
4836         }
4837       }
4838       return N;
4839     }
4840     if (usesOnlyOneValue && isConstant) {
4841       return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4842     }
4843   }
4844   // If all elements are constants and the case above didn't get hit, fall back
4845   // to the default expansion, which will generate a load from the constant
4846   // pool.
4847   if (isConstant)
4848     return SDValue();
4849
4850   // Try to lower this in lowering ShuffleVector way.
4851   SDValue V0, V1;
4852   int Mask[16];
4853   if (isKnownShuffleVector(Op, DAG, V0, V1, Mask)) {
4854     unsigned V0NumElts = V0.getValueType().getVectorNumElements();
4855     if (!V1.getNode() && V0NumElts == NumElts * 2) {
4856       V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4857                        DAG.getConstant(NumElts, MVT::i64));
4858       V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4859                        DAG.getConstant(0, MVT::i64));
4860       V0NumElts = V0.getValueType().getVectorNumElements();
4861     }
4862
4863     if (V1.getNode() && NumElts == V0NumElts &&
4864         V0NumElts == V1.getValueType().getVectorNumElements()) {
4865       SDValue Shuffle = DAG.getVectorShuffle(VT, DL, V0, V1, Mask);
4866       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
4867         return Shuffle;
4868       else
4869         return LowerVECTOR_SHUFFLE(Shuffle, DAG);
4870     } else {
4871       SDValue Res;
4872       if (isConcatVector(Op, DAG, V0, V1, Mask, Res))
4873         return Res;
4874     }
4875   }
4876
4877   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4878   // know the default expansion would otherwise fall back on something even
4879   // worse. For a vector with one or two non-undef values, that's
4880   // scalar_to_vector for the elements followed by a shuffle (provided the
4881   // shuffle is valid for the target) and materialization element by element
4882   // on the stack followed by a load for everything else.
4883   if (!isConstant && !usesOnlyOneValue) {
4884     SDValue Vec = DAG.getUNDEF(VT);
4885     for (unsigned i = 0 ; i < NumElts; ++i) {
4886       SDValue V = Op.getOperand(i);
4887       if (V.getOpcode() == ISD::UNDEF)
4888         continue;
4889       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
4890       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, LaneIdx);
4891     }
4892     return Vec;
4893   }
4894   return SDValue();
4895 }
4896
4897 /// isREVMask - Check if a vector shuffle corresponds to a REV
4898 /// instruction with the specified blocksize.  (The order of the elements
4899 /// within each block of the vector is reversed.)
4900 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4901   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4902          "Only possible block sizes for REV are: 16, 32, 64");
4903
4904   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4905   if (EltSz == 64)
4906     return false;
4907
4908   unsigned NumElts = VT.getVectorNumElements();
4909   unsigned BlockElts = M[0] + 1;
4910   // If the first shuffle index is UNDEF, be optimistic.
4911   if (M[0] < 0)
4912     BlockElts = BlockSize / EltSz;
4913
4914   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4915     return false;
4916
4917   for (unsigned i = 0; i < NumElts; ++i) {
4918     if (M[i] < 0)
4919       continue; // ignore UNDEF indices
4920     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4921       return false;
4922   }
4923
4924   return true;
4925 }
4926
4927 // isPermuteMask - Check whether the vector shuffle matches to UZP, ZIP and
4928 // TRN instruction.
4929 static unsigned isPermuteMask(ArrayRef<int> M, EVT VT, bool isV2undef) {
4930   unsigned NumElts = VT.getVectorNumElements();
4931   if (NumElts < 4)
4932     return 0;
4933
4934   bool ismatch = true;
4935
4936   // Check UZP1
4937   for (unsigned i = 0; i < NumElts; ++i) {
4938     unsigned answer = i * 2;
4939     if (isV2undef && answer >= NumElts)
4940       answer -= NumElts;
4941     if (M[i] != -1 && (unsigned)M[i] != answer) {
4942       ismatch = false;
4943       break;
4944     }
4945   }
4946   if (ismatch)
4947     return AArch64ISD::NEON_UZP1;
4948
4949   // Check UZP2
4950   ismatch = true;
4951   for (unsigned i = 0; i < NumElts; ++i) {
4952     unsigned answer = i * 2 + 1;
4953     if (isV2undef && answer >= NumElts)
4954       answer -= NumElts;
4955     if (M[i] != -1 && (unsigned)M[i] != answer) {
4956       ismatch = false;
4957       break;
4958     }
4959   }
4960   if (ismatch)
4961     return AArch64ISD::NEON_UZP2;
4962
4963   // Check ZIP1
4964   ismatch = true;
4965   for (unsigned i = 0; i < NumElts; ++i) {
4966     unsigned answer = i / 2 + NumElts * (i % 2);
4967     if (isV2undef && answer >= NumElts)
4968       answer -= NumElts;
4969     if (M[i] != -1 && (unsigned)M[i] != answer) {
4970       ismatch = false;
4971       break;
4972     }
4973   }
4974   if (ismatch)
4975     return AArch64ISD::NEON_ZIP1;
4976
4977   // Check ZIP2
4978   ismatch = true;
4979   for (unsigned i = 0; i < NumElts; ++i) {
4980     unsigned answer = (NumElts + i) / 2 + NumElts * (i % 2);
4981     if (isV2undef && answer >= NumElts)
4982       answer -= NumElts;
4983     if (M[i] != -1 && (unsigned)M[i] != answer) {
4984       ismatch = false;
4985       break;
4986     }
4987   }
4988   if (ismatch)
4989     return AArch64ISD::NEON_ZIP2;
4990
4991   // Check TRN1
4992   ismatch = true;
4993   for (unsigned i = 0; i < NumElts; ++i) {
4994     unsigned answer = i + (NumElts - 1) * (i % 2);
4995     if (isV2undef && answer >= NumElts)
4996       answer -= NumElts;
4997     if (M[i] != -1 && (unsigned)M[i] != answer) {
4998       ismatch = false;
4999       break;
5000     }
5001   }
5002   if (ismatch)
5003     return AArch64ISD::NEON_TRN1;
5004
5005   // Check TRN2
5006   ismatch = true;
5007   for (unsigned i = 0; i < NumElts; ++i) {
5008     unsigned answer = 1 + i + (NumElts - 1) * (i % 2);
5009     if (isV2undef && answer >= NumElts)
5010       answer -= NumElts;
5011     if (M[i] != -1 && (unsigned)M[i] != answer) {
5012       ismatch = false;
5013       break;
5014     }
5015   }
5016   if (ismatch)
5017     return AArch64ISD::NEON_TRN2;
5018
5019   return 0;
5020 }
5021
5022 SDValue
5023 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5024                                            SelectionDAG &DAG) const {
5025   SDValue V1 = Op.getOperand(0);
5026   SDValue V2 = Op.getOperand(1);
5027   SDLoc dl(Op);
5028   EVT VT = Op.getValueType();
5029   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5030
5031   // Convert shuffles that are directly supported on NEON to target-specific
5032   // DAG nodes, instead of keeping them as shuffles and matching them again
5033   // during code selection.  This is more efficient and avoids the possibility
5034   // of inconsistencies between legalization and selection.
5035   ArrayRef<int> ShuffleMask = SVN->getMask();
5036
5037   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5038   if (EltSize > 64)
5039     return SDValue();
5040
5041   if (isREVMask(ShuffleMask, VT, 64))
5042     return DAG.getNode(AArch64ISD::NEON_REV64, dl, VT, V1);
5043   if (isREVMask(ShuffleMask, VT, 32))
5044     return DAG.getNode(AArch64ISD::NEON_REV32, dl, VT, V1);
5045   if (isREVMask(ShuffleMask, VT, 16))
5046     return DAG.getNode(AArch64ISD::NEON_REV16, dl, VT, V1);
5047
5048   unsigned ISDNo;
5049   if (V2.getOpcode() == ISD::UNDEF)
5050     ISDNo = isPermuteMask(ShuffleMask, VT, true);
5051   else
5052     ISDNo = isPermuteMask(ShuffleMask, VT, false);
5053
5054   if (ISDNo) {
5055     if (V2.getOpcode() == ISD::UNDEF)
5056       return DAG.getNode(ISDNo, dl, VT, V1, V1);
5057     else
5058       return DAG.getNode(ISDNo, dl, VT, V1, V2);
5059   }
5060
5061   SDValue Res;
5062   if (isConcatVector(Op, DAG, V1, V2, &ShuffleMask[0], Res))
5063     return Res;
5064
5065   // If the element of shuffle mask are all the same constant, we can
5066   // transform it into either NEON_VDUP or NEON_VDUPLANE
5067   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5068     int Lane = SVN->getSplatIndex();
5069     // If this is undef splat, generate it via "just" vdup, if possible.
5070     if (Lane == -1) Lane = 0;
5071
5072     // Test if V1 is a SCALAR_TO_VECTOR.
5073     if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5074       return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT, V1.getOperand(0));
5075     }
5076     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR.
5077     if (V1.getOpcode() == ISD::BUILD_VECTOR) {
5078       bool IsScalarToVector = true;
5079       for (unsigned i = 0, e = V1.getNumOperands(); i != e; ++i)
5080         if (V1.getOperand(i).getOpcode() != ISD::UNDEF &&
5081             i != (unsigned)Lane) {
5082           IsScalarToVector = false;
5083           break;
5084         }
5085       if (IsScalarToVector)
5086         return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT,
5087                            V1.getOperand(Lane));
5088     }
5089
5090     // Test if V1 is a EXTRACT_SUBVECTOR.
5091     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5092       int ExtLane = cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5093       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1.getOperand(0),
5094                          DAG.getConstant(Lane + ExtLane, MVT::i64));
5095     }
5096     // Test if V1 is a CONCAT_VECTORS.
5097     if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
5098         V1.getOperand(1).getOpcode() == ISD::UNDEF) {
5099       SDValue Op0 = V1.getOperand(0);
5100       assert((unsigned)Lane < Op0.getValueType().getVectorNumElements() &&
5101              "Invalid vector lane access");
5102       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, Op0,
5103                          DAG.getConstant(Lane, MVT::i64));
5104     }
5105
5106     return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
5107                        DAG.getConstant(Lane, MVT::i64));
5108   }
5109
5110   int Length = ShuffleMask.size();
5111   int V1EltNum = V1.getValueType().getVectorNumElements();
5112
5113   // If the number of v1 elements is the same as the number of shuffle mask
5114   // element and the shuffle masks are sequential values, we can transform
5115   // it into NEON_VEXTRACT.
5116   if (V1EltNum == Length) {
5117     // Check if the shuffle mask is sequential.
5118     int SkipUndef = 0;
5119     while (ShuffleMask[SkipUndef] == -1) {
5120       SkipUndef++;
5121     }
5122     int CurMask = ShuffleMask[SkipUndef];
5123     if (CurMask >= SkipUndef) {
5124       bool IsSequential = true;
5125       for (int I = SkipUndef; I < Length; ++I) {
5126         if (ShuffleMask[I] != -1 && ShuffleMask[I] != CurMask) {
5127           IsSequential = false;
5128           break;
5129         }
5130         CurMask++;
5131       }
5132       if (IsSequential) {
5133         assert((EltSize % 8 == 0) && "Bitsize of vector element is incorrect");
5134         unsigned VecSize = EltSize * V1EltNum;
5135         unsigned Index = (EltSize / 8) * (ShuffleMask[SkipUndef] - SkipUndef);
5136         if (VecSize == 64 || VecSize == 128)
5137           return DAG.getNode(AArch64ISD::NEON_VEXTRACT, dl, VT, V1, V2,
5138                              DAG.getConstant(Index, MVT::i64));
5139       }
5140     }
5141   }
5142
5143   // For shuffle mask like "0, 1, 2, 3, 4, 5, 13, 7", try to generate insert
5144   // by element from V2 to V1 .
5145   // If shuffle mask is like "0, 1, 10, 11, 12, 13, 14, 15", V2 would be a
5146   // better choice to be inserted than V1 as less insert needed, so we count
5147   // element to be inserted for both V1 and V2, and select less one as insert
5148   // target.
5149
5150   // Collect elements need to be inserted and their index.
5151   SmallVector<int, 8> NV1Elt;
5152   SmallVector<int, 8> N1Index;
5153   SmallVector<int, 8> NV2Elt;
5154   SmallVector<int, 8> N2Index;
5155   for (int I = 0; I != Length; ++I) {
5156     if (ShuffleMask[I] != I) {
5157       NV1Elt.push_back(ShuffleMask[I]);
5158       N1Index.push_back(I);
5159     }
5160   }
5161   for (int I = 0; I != Length; ++I) {
5162     if (ShuffleMask[I] != (I + V1EltNum)) {
5163       NV2Elt.push_back(ShuffleMask[I]);
5164       N2Index.push_back(I);
5165     }
5166   }
5167
5168   // Decide which to be inserted. If all lanes mismatch, neither V1 nor V2
5169   // will be inserted.
5170   SDValue InsV = V1;
5171   SmallVector<int, 8> InsMasks = NV1Elt;
5172   SmallVector<int, 8> InsIndex = N1Index;
5173   if ((int)NV1Elt.size() != Length || (int)NV2Elt.size() != Length) {
5174     if (NV1Elt.size() > NV2Elt.size()) {
5175       InsV = V2;
5176       InsMasks = NV2Elt;
5177       InsIndex = N2Index;
5178     }
5179   } else {
5180     InsV = DAG.getNode(ISD::UNDEF, dl, VT);
5181   }
5182
5183   for (int I = 0, E = InsMasks.size(); I != E; ++I) {
5184     SDValue ExtV = V1;
5185     int Mask = InsMasks[I];
5186     if (Mask >= V1EltNum) {
5187       ExtV = V2;
5188       Mask -= V1EltNum;
5189     }
5190     // Any value type smaller than i32 is illegal in AArch64, and this lower
5191     // function is called after legalize pass, so we need to legalize
5192     // the result here.
5193     EVT EltVT;
5194     if (VT.getVectorElementType().isFloatingPoint())
5195       EltVT = (EltSize == 64) ? MVT::f64 : MVT::f32;
5196     else
5197       EltVT = (EltSize == 64) ? MVT::i64 : MVT::i32;
5198
5199     if (Mask >= 0) {
5200       ExtV = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ExtV,
5201                          DAG.getConstant(Mask, MVT::i64));
5202       InsV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, InsV, ExtV,
5203                          DAG.getConstant(InsIndex[I], MVT::i64));
5204     }
5205   }
5206   return InsV;
5207 }
5208
5209 AArch64TargetLowering::ConstraintType
5210 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
5211   if (Constraint.size() == 1) {
5212     switch (Constraint[0]) {
5213     default: break;
5214     case 'w': // An FP/SIMD vector register
5215       return C_RegisterClass;
5216     case 'I': // Constant that can be used with an ADD instruction
5217     case 'J': // Constant that can be used with a SUB instruction
5218     case 'K': // Constant that can be used with a 32-bit logical instruction
5219     case 'L': // Constant that can be used with a 64-bit logical instruction
5220     case 'M': // Constant that can be used as a 32-bit MOV immediate
5221     case 'N': // Constant that can be used as a 64-bit MOV immediate
5222     case 'Y': // Floating point constant zero
5223     case 'Z': // Integer constant zero
5224       return C_Other;
5225     case 'Q': // A memory reference with base register and no offset
5226       return C_Memory;
5227     case 'S': // A symbolic address
5228       return C_Other;
5229     }
5230   }
5231
5232   // FIXME: Ump, Utf, Usa, Ush
5233   // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
5234   //      whatever they may be
5235   // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
5236   // Usa: An absolute symbolic address
5237   // Ush: The high part (bits 32:12) of a pc-relative symbolic address
5238   assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
5239          && Constraint != "Ush" && "Unimplemented constraints");
5240
5241   return TargetLowering::getConstraintType(Constraint);
5242 }
5243
5244 TargetLowering::ConstraintWeight
5245 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
5246                                                 const char *Constraint) const {
5247
5248   llvm_unreachable("Constraint weight unimplemented");
5249 }
5250
5251 void
5252 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5253                                                     std::string &Constraint,
5254                                                     std::vector<SDValue> &Ops,
5255                                                     SelectionDAG &DAG) const {
5256   SDValue Result;
5257
5258   // Only length 1 constraints are C_Other.
5259   if (Constraint.size() != 1) return;
5260
5261   // Only C_Other constraints get lowered like this. That means constants for us
5262   // so return early if there's no hope the constraint can be lowered.
5263
5264   switch(Constraint[0]) {
5265   default: break;
5266   case 'I': case 'J': case 'K': case 'L':
5267   case 'M': case 'N': case 'Z': {
5268     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5269     if (!C)
5270       return;
5271
5272     uint64_t CVal = C->getZExtValue();
5273     uint32_t Bits;
5274
5275     switch (Constraint[0]) {
5276     default:
5277       // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
5278       // is a peculiarly useless SUB constraint.
5279       llvm_unreachable("Unimplemented C_Other constraint");
5280     case 'I':
5281       if (CVal <= 0xfff)
5282         break;
5283       return;
5284     case 'K':
5285       if (A64Imms::isLogicalImm(32, CVal, Bits))
5286         break;
5287       return;
5288     case 'L':
5289       if (A64Imms::isLogicalImm(64, CVal, Bits))
5290         break;
5291       return;
5292     case 'Z':
5293       if (CVal == 0)
5294         break;
5295       return;
5296     }
5297
5298     Result = DAG.getTargetConstant(CVal, Op.getValueType());
5299     break;
5300   }
5301   case 'S': {
5302     // An absolute symbolic address or label reference.
5303     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5304       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5305                                           GA->getValueType(0));
5306     } else if (const BlockAddressSDNode *BA
5307                  = dyn_cast<BlockAddressSDNode>(Op)) {
5308       Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
5309                                          BA->getValueType(0));
5310     } else if (const ExternalSymbolSDNode *ES
5311                  = dyn_cast<ExternalSymbolSDNode>(Op)) {
5312       Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
5313                                            ES->getValueType(0));
5314     } else
5315       return;
5316     break;
5317   }
5318   case 'Y':
5319     if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
5320       if (CFP->isExactlyValue(0.0)) {
5321         Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
5322         break;
5323       }
5324     }
5325     return;
5326   }
5327
5328   if (Result.getNode()) {
5329     Ops.push_back(Result);
5330     return;
5331   }
5332
5333   // It's an unknown constraint for us. Let generic code have a go.
5334   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5335 }
5336
5337 std::pair<unsigned, const TargetRegisterClass*>
5338 AArch64TargetLowering::getRegForInlineAsmConstraint(
5339                                                   const std::string &Constraint,
5340                                                   MVT VT) const {
5341   if (Constraint.size() == 1) {
5342     switch (Constraint[0]) {
5343     case 'r':
5344       if (VT.getSizeInBits() <= 32)
5345         return std::make_pair(0U, &AArch64::GPR32RegClass);
5346       else if (VT == MVT::i64)
5347         return std::make_pair(0U, &AArch64::GPR64RegClass);
5348       break;
5349     case 'w':
5350       if (VT == MVT::f16)
5351         return std::make_pair(0U, &AArch64::FPR16RegClass);
5352       else if (VT == MVT::f32)
5353         return std::make_pair(0U, &AArch64::FPR32RegClass);
5354       else if (VT.getSizeInBits() == 64)
5355         return std::make_pair(0U, &AArch64::FPR64RegClass);
5356       else if (VT.getSizeInBits() == 128)
5357         return std::make_pair(0U, &AArch64::FPR128RegClass);
5358       break;
5359     }
5360   }
5361
5362   // Use the default implementation in TargetLowering to convert the register
5363   // constraint into a member of a register class.
5364   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5365 }
5366
5367 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
5368 /// The associated MachineMemOperands record the alignment specified
5369 /// in the intrinsic calls.
5370 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5371                                                const CallInst &I,
5372                                                unsigned Intrinsic) const {
5373   switch (Intrinsic) {
5374   case Intrinsic::arm_neon_vld1:
5375   case Intrinsic::arm_neon_vld2:
5376   case Intrinsic::arm_neon_vld3:
5377   case Intrinsic::arm_neon_vld4:
5378   case Intrinsic::aarch64_neon_vld1x2:
5379   case Intrinsic::aarch64_neon_vld1x3:
5380   case Intrinsic::aarch64_neon_vld1x4:
5381   case Intrinsic::arm_neon_vld2lane:
5382   case Intrinsic::arm_neon_vld3lane:
5383   case Intrinsic::arm_neon_vld4lane: {
5384     Info.opc = ISD::INTRINSIC_W_CHAIN;
5385     // Conservatively set memVT to the entire set of vectors loaded.
5386     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5387     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5388     Info.ptrVal = I.getArgOperand(0);
5389     Info.offset = 0;
5390     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
5391     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
5392     Info.vol = false; // volatile loads with NEON intrinsics not supported
5393     Info.readMem = true;
5394     Info.writeMem = false;
5395     return true;
5396   }
5397   case Intrinsic::arm_neon_vst1:
5398   case Intrinsic::arm_neon_vst2:
5399   case Intrinsic::arm_neon_vst3:
5400   case Intrinsic::arm_neon_vst4:
5401   case Intrinsic::aarch64_neon_vst1x2:
5402   case Intrinsic::aarch64_neon_vst1x3:
5403   case Intrinsic::aarch64_neon_vst1x4:
5404   case Intrinsic::arm_neon_vst2lane:
5405   case Intrinsic::arm_neon_vst3lane:
5406   case Intrinsic::arm_neon_vst4lane: {
5407     Info.opc = ISD::INTRINSIC_VOID;
5408     // Conservatively set memVT to the entire set of vectors stored.
5409     unsigned NumElts = 0;
5410     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5411       Type *ArgTy = I.getArgOperand(ArgI)->getType();
5412       if (!ArgTy->isVectorTy())
5413         break;
5414       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5415     }
5416     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5417     Info.ptrVal = I.getArgOperand(0);
5418     Info.offset = 0;
5419     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
5420     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
5421     Info.vol = false; // volatile stores with NEON intrinsics not supported
5422     Info.readMem = false;
5423     Info.writeMem = true;
5424     return true;
5425   }
5426   default:
5427     break;
5428   }
5429
5430   return false;
5431 }
5432
5433 // Truncations from 64-bit GPR to 32-bit GPR is free.
5434 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5435   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5436     return false;
5437   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5438   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5439   if (NumBits1 <= NumBits2)
5440     return false;
5441   return true;
5442 }
5443
5444 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5445   if (!VT1.isInteger() || !VT2.isInteger())
5446     return false;
5447   unsigned NumBits1 = VT1.getSizeInBits();
5448   unsigned NumBits2 = VT2.getSizeInBits();
5449   if (NumBits1 <= NumBits2)
5450     return false;
5451   return true;
5452 }
5453
5454 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5455 // 64-bit GPR.
5456 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5457   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5458     return false;
5459   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5460   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5461   if (NumBits1 == 32 && NumBits2 == 64)
5462     return true;
5463   return false;
5464 }
5465
5466 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5467   if (!VT1.isInteger() || !VT2.isInteger())
5468     return false;
5469   unsigned NumBits1 = VT1.getSizeInBits();
5470   unsigned NumBits2 = VT2.getSizeInBits();
5471   if (NumBits1 == 32 && NumBits2 == 64)
5472     return true;
5473   return false;
5474 }
5475
5476 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5477   EVT VT1 = Val.getValueType();
5478   if (isZExtFree(VT1, VT2)) {
5479     return true;
5480   }
5481
5482   if (Val.getOpcode() != ISD::LOAD)
5483     return false;
5484
5485   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5486   return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5487           VT2.isInteger() && VT1.getSizeInBits() <= 32);
5488 }
5489
5490 // isLegalAddressingMode - Return true if the addressing mode represented
5491 /// by AM is legal for this target, for a load/store of the specified type.
5492 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5493                                                 Type *Ty) const {
5494   // AArch64 has five basic addressing modes:
5495   //  reg
5496   //  reg + 9-bit signed offset
5497   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
5498   //  reg1 + reg2
5499   //  reg + SIZE_IN_BYTES * reg
5500
5501   // No global is ever allowed as a base.
5502   if (AM.BaseGV)
5503     return false;
5504
5505   // No reg+reg+imm addressing.
5506   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5507     return false;
5508
5509   // check reg + imm case:
5510   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5511   uint64_t NumBytes = 0;
5512   if (Ty->isSized()) {
5513     uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5514     NumBytes = NumBits / 8;
5515     if (!isPowerOf2_64(NumBits))
5516       NumBytes = 0;
5517   }
5518
5519   if (!AM.Scale) {
5520     int64_t Offset = AM.BaseOffs;
5521
5522     // 9-bit signed offset
5523     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5524       return true;
5525
5526     // 12-bit unsigned offset
5527     unsigned shift = Log2_64(NumBytes);
5528     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5529         // Must be a multiple of NumBytes (NumBytes is a power of 2)
5530         (Offset >> shift) << shift == Offset)
5531       return true;
5532     return false;
5533   }
5534   if (!AM.Scale || AM.Scale == 1 ||
5535       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5536     return true;
5537   return false;
5538 }
5539
5540 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5541                                               Type *Ty) const {
5542   // Scaling factors are not free at all.
5543   // Operands                     | Rt Latency
5544   // -------------------------------------------
5545   // Rt, [Xn, Xm]                 | 4
5546   // -------------------------------------------
5547   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
5548   // Rt, [Xn, Wm, <extend> #imm]  |
5549   if (isLegalAddressingMode(AM, Ty))
5550     // Scale represents reg2 * scale, thus account for 1 if
5551     // it is not equal to 0 or 1.
5552     return AM.Scale != 0 && AM.Scale != 1;
5553   return -1;
5554 }
5555
5556 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
5557 /// be used for loads / stores from the global.
5558 unsigned AArch64TargetLowering::getMaximalGlobalOffset() const {
5559   return 4095;
5560 }
5561