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