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