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