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