Simplify creation of a bunch of ArrayRefs by using None, makeArrayRef or just letting...
[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 implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64PerfectShuffle.h"
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "AArch64TargetObjectFile.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetOptions.h"
34 using namespace llvm;
35
36 #define DEBUG_TYPE "aarch64-lower"
37
38 STATISTIC(NumTailCalls, "Number of tail calls");
39 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
40
41 namespace {
42 enum AlignMode {
43   StrictAlign,
44   NoStrictAlign
45 };
46 }
47
48 static cl::opt<AlignMode>
49 Align(cl::desc("Load/store alignment support"),
50       cl::Hidden, cl::init(NoStrictAlign),
51       cl::values(
52           clEnumValN(StrictAlign,   "aarch64-strict-align",
53                      "Disallow all unaligned memory accesses"),
54           clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
55                      "Allow unaligned memory accesses"),
56           clEnumValEnd));
57
58 // Place holder until extr generation is tested fully.
59 static cl::opt<bool>
60 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
61                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
62                           cl::init(true));
63
64 static cl::opt<bool>
65 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
66                          cl::desc("Allow AArch64 SLI/SRI formation"),
67                          cl::init(false));
68
69 //===----------------------------------------------------------------------===//
70 // AArch64 Lowering public interface.
71 //===----------------------------------------------------------------------===//
72 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
73   if (TT.isOSBinFormatMachO())
74     return new AArch64_MachoTargetObjectFile();
75
76   return new AArch64_ELFTargetObjectFile();
77 }
78
79 AArch64TargetLowering::AArch64TargetLowering(TargetMachine &TM)
80     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
81   Subtarget = &TM.getSubtarget<AArch64Subtarget>();
82
83   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
84   // we have to make something up. Arbitrarily, choose ZeroOrOne.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // When comparing vectors the result sets the different elements in the
87   // vector to all-one or all-zero.
88   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
89
90   // Set up the register classes.
91   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
92   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
93
94   if (Subtarget->hasFPARMv8()) {
95     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
96     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
97     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
98     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
99   }
100
101   if (Subtarget->hasNEON()) {
102     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
103     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
104     // Someone set us up the NEON.
105     addDRTypeForNEON(MVT::v2f32);
106     addDRTypeForNEON(MVT::v8i8);
107     addDRTypeForNEON(MVT::v4i16);
108     addDRTypeForNEON(MVT::v2i32);
109     addDRTypeForNEON(MVT::v1i64);
110     addDRTypeForNEON(MVT::v1f64);
111
112     addQRTypeForNEON(MVT::v4f32);
113     addQRTypeForNEON(MVT::v2f64);
114     addQRTypeForNEON(MVT::v16i8);
115     addQRTypeForNEON(MVT::v8i16);
116     addQRTypeForNEON(MVT::v4i32);
117     addQRTypeForNEON(MVT::v2i64);
118   }
119
120   // Compute derived properties from the register classes
121   computeRegisterProperties();
122
123   // Provide all sorts of operation actions
124   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
125   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
126   setOperationAction(ISD::SETCC, MVT::i32, Custom);
127   setOperationAction(ISD::SETCC, MVT::i64, Custom);
128   setOperationAction(ISD::SETCC, MVT::f32, Custom);
129   setOperationAction(ISD::SETCC, MVT::f64, Custom);
130   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
131   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
132   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
133   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
134   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
135   setOperationAction(ISD::SELECT, MVT::i32, Custom);
136   setOperationAction(ISD::SELECT, MVT::i64, Custom);
137   setOperationAction(ISD::SELECT, MVT::f32, Custom);
138   setOperationAction(ISD::SELECT, MVT::f64, Custom);
139   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
140   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
141   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
142   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
143   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
144   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
145
146   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
147   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
148   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
149
150   setOperationAction(ISD::FREM, MVT::f32, Expand);
151   setOperationAction(ISD::FREM, MVT::f64, Expand);
152   setOperationAction(ISD::FREM, MVT::f80, Expand);
153
154   // Custom lowering hooks are needed for XOR
155   // to fold it into CSINC/CSINV.
156   setOperationAction(ISD::XOR, MVT::i32, Custom);
157   setOperationAction(ISD::XOR, MVT::i64, Custom);
158
159   // Virtually no operation on f128 is legal, but LLVM can't expand them when
160   // there's a valid register class, so we need custom operations in most cases.
161   setOperationAction(ISD::FABS, MVT::f128, Expand);
162   setOperationAction(ISD::FADD, MVT::f128, Custom);
163   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
164   setOperationAction(ISD::FCOS, MVT::f128, Expand);
165   setOperationAction(ISD::FDIV, MVT::f128, Custom);
166   setOperationAction(ISD::FMA, MVT::f128, Expand);
167   setOperationAction(ISD::FMUL, MVT::f128, Custom);
168   setOperationAction(ISD::FNEG, MVT::f128, Expand);
169   setOperationAction(ISD::FPOW, MVT::f128, Expand);
170   setOperationAction(ISD::FREM, MVT::f128, Expand);
171   setOperationAction(ISD::FRINT, MVT::f128, Expand);
172   setOperationAction(ISD::FSIN, MVT::f128, Expand);
173   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
174   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
175   setOperationAction(ISD::FSUB, MVT::f128, Custom);
176   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
177   setOperationAction(ISD::SETCC, MVT::f128, Custom);
178   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
179   setOperationAction(ISD::SELECT, MVT::f128, Custom);
180   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
181   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
182
183   // Lowering for many of the conversions is actually specified by the non-f128
184   // type. The LowerXXX function will be trivial when f128 isn't involved.
185   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
186   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
187   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
188   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
189   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
190   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
191   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
192   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
193   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
194   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
195   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
196   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
197   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
198   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
199
200   // Variable arguments.
201   setOperationAction(ISD::VASTART, MVT::Other, Custom);
202   setOperationAction(ISD::VAARG, MVT::Other, Custom);
203   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
204   setOperationAction(ISD::VAEND, MVT::Other, Expand);
205
206   // Variable-sized objects.
207   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
208   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
209   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
210
211   // Exception handling.
212   // FIXME: These are guesses. Has this been defined yet?
213   setExceptionPointerRegister(AArch64::X0);
214   setExceptionSelectorRegister(AArch64::X1);
215
216   // Constant pool entries
217   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
218
219   // BlockAddress
220   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
221
222   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
223   setOperationAction(ISD::ADDC, MVT::i32, Custom);
224   setOperationAction(ISD::ADDE, MVT::i32, Custom);
225   setOperationAction(ISD::SUBC, MVT::i32, Custom);
226   setOperationAction(ISD::SUBE, MVT::i32, Custom);
227   setOperationAction(ISD::ADDC, MVT::i64, Custom);
228   setOperationAction(ISD::ADDE, MVT::i64, Custom);
229   setOperationAction(ISD::SUBC, MVT::i64, Custom);
230   setOperationAction(ISD::SUBE, MVT::i64, Custom);
231
232   // AArch64 lacks both left-rotate and popcount instructions.
233   setOperationAction(ISD::ROTL, MVT::i32, Expand);
234   setOperationAction(ISD::ROTL, MVT::i64, Expand);
235
236   // AArch64 doesn't have {U|S}MUL_LOHI.
237   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
238   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
239
240
241   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
242   // counterparts, which AArch64 supports directly.
243   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
244   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
245   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
246   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
247
248   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
249   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
250
251   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
252   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
253   setOperationAction(ISD::SREM, MVT::i32, Expand);
254   setOperationAction(ISD::SREM, MVT::i64, Expand);
255   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
256   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
257   setOperationAction(ISD::UREM, MVT::i32, Expand);
258   setOperationAction(ISD::UREM, MVT::i64, Expand);
259
260   // Custom lower Add/Sub/Mul with overflow.
261   setOperationAction(ISD::SADDO, MVT::i32, Custom);
262   setOperationAction(ISD::SADDO, MVT::i64, Custom);
263   setOperationAction(ISD::UADDO, MVT::i32, Custom);
264   setOperationAction(ISD::UADDO, MVT::i64, Custom);
265   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
266   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
267   setOperationAction(ISD::USUBO, MVT::i32, Custom);
268   setOperationAction(ISD::USUBO, MVT::i64, Custom);
269   setOperationAction(ISD::SMULO, MVT::i32, Custom);
270   setOperationAction(ISD::SMULO, MVT::i64, Custom);
271   setOperationAction(ISD::UMULO, MVT::i32, Custom);
272   setOperationAction(ISD::UMULO, MVT::i64, Custom);
273
274   setOperationAction(ISD::FSIN, MVT::f32, Expand);
275   setOperationAction(ISD::FSIN, MVT::f64, Expand);
276   setOperationAction(ISD::FCOS, MVT::f32, Expand);
277   setOperationAction(ISD::FCOS, MVT::f64, Expand);
278   setOperationAction(ISD::FPOW, MVT::f32, Expand);
279   setOperationAction(ISD::FPOW, MVT::f64, Expand);
280   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
281   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
282
283   // f16 is storage-only, so we promote operations to f32 if we know this is
284   // valid, and ignore them otherwise. The operations not mentioned here will
285   // fail to select, but this is not a major problem as no source language
286   // should be emitting native f16 operations yet.
287   setOperationAction(ISD::FADD, MVT::f16, Promote);
288   setOperationAction(ISD::FDIV, MVT::f16, Promote);
289   setOperationAction(ISD::FMUL, MVT::f16, Promote);
290   setOperationAction(ISD::FSUB, MVT::f16, Promote);
291
292   // AArch64 has implementations of a lot of rounding-like FP operations.
293   static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
294   for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
295     MVT Ty = RoundingTypes[I];
296     setOperationAction(ISD::FFLOOR, Ty, Legal);
297     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
298     setOperationAction(ISD::FCEIL, Ty, Legal);
299     setOperationAction(ISD::FRINT, Ty, Legal);
300     setOperationAction(ISD::FTRUNC, Ty, Legal);
301     setOperationAction(ISD::FROUND, Ty, Legal);
302   }
303
304   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
305
306   if (Subtarget->isTargetMachO()) {
307     // For iOS, we don't want to the normal expansion of a libcall to
308     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
309     // traffic.
310     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
311     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
312   } else {
313     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
314     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
315   }
316
317   // AArch64 does not have floating-point extending loads, i1 sign-extending
318   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
319   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
320   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
321   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
322   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
323   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
324   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
325   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
326   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
327   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
328   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
329   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
330   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
331
332   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
333   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
334
335   // Indexed loads and stores are supported.
336   for (unsigned im = (unsigned)ISD::PRE_INC;
337        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
338     setIndexedLoadAction(im, MVT::i8, Legal);
339     setIndexedLoadAction(im, MVT::i16, Legal);
340     setIndexedLoadAction(im, MVT::i32, Legal);
341     setIndexedLoadAction(im, MVT::i64, Legal);
342     setIndexedLoadAction(im, MVT::f64, Legal);
343     setIndexedLoadAction(im, MVT::f32, Legal);
344     setIndexedStoreAction(im, MVT::i8, Legal);
345     setIndexedStoreAction(im, MVT::i16, Legal);
346     setIndexedStoreAction(im, MVT::i32, Legal);
347     setIndexedStoreAction(im, MVT::i64, Legal);
348     setIndexedStoreAction(im, MVT::f64, Legal);
349     setIndexedStoreAction(im, MVT::f32, Legal);
350   }
351
352   // Trap.
353   setOperationAction(ISD::TRAP, MVT::Other, Legal);
354
355   // We combine OR nodes for bitfield operations.
356   setTargetDAGCombine(ISD::OR);
357
358   // Vector add and sub nodes may conceal a high-half opportunity.
359   // Also, try to fold ADD into CSINC/CSINV..
360   setTargetDAGCombine(ISD::ADD);
361   setTargetDAGCombine(ISD::SUB);
362
363   setTargetDAGCombine(ISD::XOR);
364   setTargetDAGCombine(ISD::SINT_TO_FP);
365   setTargetDAGCombine(ISD::UINT_TO_FP);
366
367   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
368
369   setTargetDAGCombine(ISD::ANY_EXTEND);
370   setTargetDAGCombine(ISD::ZERO_EXTEND);
371   setTargetDAGCombine(ISD::SIGN_EXTEND);
372   setTargetDAGCombine(ISD::BITCAST);
373   setTargetDAGCombine(ISD::CONCAT_VECTORS);
374   setTargetDAGCombine(ISD::STORE);
375
376   setTargetDAGCombine(ISD::MUL);
377
378   setTargetDAGCombine(ISD::SELECT);
379   setTargetDAGCombine(ISD::VSELECT);
380
381   setTargetDAGCombine(ISD::INTRINSIC_VOID);
382   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
383   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
384
385   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
386   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
387   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
388
389   setStackPointerRegisterToSaveRestore(AArch64::SP);
390
391   setSchedulingPreference(Sched::Hybrid);
392
393   // Enable TBZ/TBNZ
394   MaskAndBranchFoldingIsLegal = true;
395
396   setMinFunctionAlignment(2);
397
398   RequireStrictAlign = (Align == StrictAlign);
399
400   setHasExtractBitsInsn(true);
401
402   if (Subtarget->hasNEON()) {
403     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
404     // silliness like this:
405     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
406     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
407     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
408     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
409     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
410     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
411     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
412     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
413     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
414     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
415     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
416     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
417     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
418     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
419     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
420     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
421     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
422     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
423     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
424     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
425     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
426     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
427     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
428     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
429     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
430
431     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
432     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
433     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
434     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
435     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
436
437     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
438
439     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
440     // elements smaller than i32, so promote the input to i32 first.
441     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
442     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
443     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
444     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
445     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
446     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
447     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
448     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
449     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
450
451     // AArch64 doesn't have MUL.2d:
452     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
453     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
454     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
455     // Likewise, narrowing and extending vector loads/stores aren't handled
456     // directly.
457     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
458          VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
459
460       setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
461                          Expand);
462
463       setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
464       setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
465       setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
466       setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
467
468       setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
469
470       for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
471            InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
472         setTruncStoreAction((MVT::SimpleValueType)VT,
473                             (MVT::SimpleValueType)InnerVT, Expand);
474       setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
475       setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
476       setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
477     }
478
479     // AArch64 has implementations of a lot of rounding-like FP operations.
480     static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
481     for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
482       MVT Ty = RoundingVecTypes[I];
483       setOperationAction(ISD::FFLOOR, Ty, Legal);
484       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
485       setOperationAction(ISD::FCEIL, Ty, Legal);
486       setOperationAction(ISD::FRINT, Ty, Legal);
487       setOperationAction(ISD::FTRUNC, Ty, Legal);
488       setOperationAction(ISD::FROUND, Ty, Legal);
489     }
490   }
491
492   // Prefer likely predicted branches to selects on out-of-order cores.
493   if (Subtarget->isCortexA57())
494     PredictableSelectIsExpensive = true;
495 }
496
497 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
498   if (VT == MVT::v2f32) {
499     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
500     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
501
502     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
503     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
504   } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
505     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
506     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
507
508     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
509     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
510   }
511
512   // Mark vector float intrinsics as expand.
513   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
514     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
515     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
516     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
517     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
518     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
519     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
520     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
521     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
522     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
523   }
524
525   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
526   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
527   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
528   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
529   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
530   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
531   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
532   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
533   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
534   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
535   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
536   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
537
538   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
539   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
540   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
541   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
542
543   // CNT supports only B element sizes.
544   if (VT != MVT::v8i8 && VT != MVT::v16i8)
545     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
546
547   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
548   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
549   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
550   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
551   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
552
553   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
554   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
555
556   if (Subtarget->isLittleEndian()) {
557     for (unsigned im = (unsigned)ISD::PRE_INC;
558          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
559       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
560       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
561     }
562   }
563 }
564
565 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
566   addRegisterClass(VT, &AArch64::FPR64RegClass);
567   addTypeForNEON(VT, MVT::v2i32);
568 }
569
570 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
571   addRegisterClass(VT, &AArch64::FPR128RegClass);
572   addTypeForNEON(VT, MVT::v4i32);
573 }
574
575 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
576   if (!VT.isVector())
577     return MVT::i32;
578   return VT.changeVectorElementTypeToInteger();
579 }
580
581 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
582 /// Mask are known to be either zero or one and return them in the
583 /// KnownZero/KnownOne bitsets.
584 void AArch64TargetLowering::computeKnownBitsForTargetNode(
585     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
586     const SelectionDAG &DAG, unsigned Depth) const {
587   switch (Op.getOpcode()) {
588   default:
589     break;
590   case AArch64ISD::CSEL: {
591     APInt KnownZero2, KnownOne2;
592     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
593     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
594     KnownZero &= KnownZero2;
595     KnownOne &= KnownOne2;
596     break;
597   }
598   case ISD::INTRINSIC_W_CHAIN: {
599    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
600     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
601     switch (IntID) {
602     default: return;
603     case Intrinsic::aarch64_ldaxr:
604     case Intrinsic::aarch64_ldxr: {
605       unsigned BitWidth = KnownOne.getBitWidth();
606       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
607       unsigned MemBits = VT.getScalarType().getSizeInBits();
608       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
609       return;
610     }
611     }
612     break;
613   }
614   case ISD::INTRINSIC_WO_CHAIN:
615   case ISD::INTRINSIC_VOID: {
616     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
617     switch (IntNo) {
618     default:
619       break;
620     case Intrinsic::aarch64_neon_umaxv:
621     case Intrinsic::aarch64_neon_uminv: {
622       // Figure out the datatype of the vector operand. The UMINV instruction
623       // will zero extend the result, so we can mark as known zero all the
624       // bits larger than the element datatype. 32-bit or larget doesn't need
625       // this as those are legal types and will be handled by isel directly.
626       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
627       unsigned BitWidth = KnownZero.getBitWidth();
628       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
629         assert(BitWidth >= 8 && "Unexpected width!");
630         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
631         KnownZero |= Mask;
632       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
633         assert(BitWidth >= 16 && "Unexpected width!");
634         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
635         KnownZero |= Mask;
636       }
637       break;
638     } break;
639     }
640   }
641   }
642 }
643
644 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
645   return MVT::i64;
646 }
647
648 unsigned AArch64TargetLowering::getMaximalGlobalOffset() const {
649   // FIXME: On AArch64, this depends on the type.
650   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
651   // and the offset has to be a multiple of the related size in bytes.
652   return 4095;
653 }
654
655 FastISel *
656 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
657                                       const TargetLibraryInfo *libInfo) const {
658   return AArch64::createFastISel(funcInfo, libInfo);
659 }
660
661 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
662   switch (Opcode) {
663   default:
664     return nullptr;
665   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
666   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
667   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
668   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
669   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
670   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
671   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
672   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
673   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
674   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
675   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
676   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
677   case AArch64ISD::TLSDESC_CALL:      return "AArch64ISD::TLSDESC_CALL";
678   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
679   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
680   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
681   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
682   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
683   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
684   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
685   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
686   case AArch64ISD::FMIN:              return "AArch64ISD::FMIN";
687   case AArch64ISD::FMAX:              return "AArch64ISD::FMAX";
688   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
689   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
690   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
691   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
692   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
693   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
694   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
695   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
696   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
697   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
698   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
699   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
700   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
701   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
702   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
703   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
704   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
705   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
706   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
707   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
708   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
709   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
710   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
711   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
712   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
713   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
714   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
715   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
716   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
717   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
718   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
719   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
720   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
721   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
722   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
723   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
724   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
725   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
726   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
727   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
728   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
729   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
730   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
731   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
732   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
733   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
734   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
735   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
736   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
737   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
738   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
739   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
740   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
741   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
742   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
743   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
744   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
745   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
746   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
747   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
748   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
749   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
750   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
751   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
752   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
753   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
754   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
755   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
756   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
757   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
758   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
759   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
760   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
761   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
762   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
763   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
764   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
765   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
766   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
767   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
768   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
769   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
770   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
771   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
772   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
773   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
774   }
775 }
776
777 MachineBasicBlock *
778 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
779                                     MachineBasicBlock *MBB) const {
780   // We materialise the F128CSEL pseudo-instruction as some control flow and a
781   // phi node:
782
783   // OrigBB:
784   //     [... previous instrs leading to comparison ...]
785   //     b.ne TrueBB
786   //     b EndBB
787   // TrueBB:
788   //     ; Fallthrough
789   // EndBB:
790   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
791
792   const TargetInstrInfo *TII =
793       getTargetMachine().getSubtargetImpl()->getInstrInfo();
794   MachineFunction *MF = MBB->getParent();
795   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
796   DebugLoc DL = MI->getDebugLoc();
797   MachineFunction::iterator It = MBB;
798   ++It;
799
800   unsigned DestReg = MI->getOperand(0).getReg();
801   unsigned IfTrueReg = MI->getOperand(1).getReg();
802   unsigned IfFalseReg = MI->getOperand(2).getReg();
803   unsigned CondCode = MI->getOperand(3).getImm();
804   bool NZCVKilled = MI->getOperand(4).isKill();
805
806   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
807   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
808   MF->insert(It, TrueBB);
809   MF->insert(It, EndBB);
810
811   // Transfer rest of current basic-block to EndBB
812   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
813                 MBB->end());
814   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
815
816   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
817   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
818   MBB->addSuccessor(TrueBB);
819   MBB->addSuccessor(EndBB);
820
821   // TrueBB falls through to the end.
822   TrueBB->addSuccessor(EndBB);
823
824   if (!NZCVKilled) {
825     TrueBB->addLiveIn(AArch64::NZCV);
826     EndBB->addLiveIn(AArch64::NZCV);
827   }
828
829   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
830       .addReg(IfTrueReg)
831       .addMBB(TrueBB)
832       .addReg(IfFalseReg)
833       .addMBB(MBB);
834
835   MI->eraseFromParent();
836   return EndBB;
837 }
838
839 MachineBasicBlock *
840 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
841                                                  MachineBasicBlock *BB) const {
842   switch (MI->getOpcode()) {
843   default:
844 #ifndef NDEBUG
845     MI->dump();
846 #endif
847     llvm_unreachable("Unexpected instruction for custom inserter!");
848
849   case AArch64::F128CSEL:
850     return EmitF128CSEL(MI, BB);
851
852   case TargetOpcode::STACKMAP:
853   case TargetOpcode::PATCHPOINT:
854     return emitPatchPoint(MI, BB);
855   }
856 }
857
858 //===----------------------------------------------------------------------===//
859 // AArch64 Lowering private implementation.
860 //===----------------------------------------------------------------------===//
861
862 //===----------------------------------------------------------------------===//
863 // Lowering Code
864 //===----------------------------------------------------------------------===//
865
866 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
867 /// CC
868 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
869   switch (CC) {
870   default:
871     llvm_unreachable("Unknown condition code!");
872   case ISD::SETNE:
873     return AArch64CC::NE;
874   case ISD::SETEQ:
875     return AArch64CC::EQ;
876   case ISD::SETGT:
877     return AArch64CC::GT;
878   case ISD::SETGE:
879     return AArch64CC::GE;
880   case ISD::SETLT:
881     return AArch64CC::LT;
882   case ISD::SETLE:
883     return AArch64CC::LE;
884   case ISD::SETUGT:
885     return AArch64CC::HI;
886   case ISD::SETUGE:
887     return AArch64CC::HS;
888   case ISD::SETULT:
889     return AArch64CC::LO;
890   case ISD::SETULE:
891     return AArch64CC::LS;
892   }
893 }
894
895 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
896 static void changeFPCCToAArch64CC(ISD::CondCode CC,
897                                   AArch64CC::CondCode &CondCode,
898                                   AArch64CC::CondCode &CondCode2) {
899   CondCode2 = AArch64CC::AL;
900   switch (CC) {
901   default:
902     llvm_unreachable("Unknown FP condition!");
903   case ISD::SETEQ:
904   case ISD::SETOEQ:
905     CondCode = AArch64CC::EQ;
906     break;
907   case ISD::SETGT:
908   case ISD::SETOGT:
909     CondCode = AArch64CC::GT;
910     break;
911   case ISD::SETGE:
912   case ISD::SETOGE:
913     CondCode = AArch64CC::GE;
914     break;
915   case ISD::SETOLT:
916     CondCode = AArch64CC::MI;
917     break;
918   case ISD::SETOLE:
919     CondCode = AArch64CC::LS;
920     break;
921   case ISD::SETONE:
922     CondCode = AArch64CC::MI;
923     CondCode2 = AArch64CC::GT;
924     break;
925   case ISD::SETO:
926     CondCode = AArch64CC::VC;
927     break;
928   case ISD::SETUO:
929     CondCode = AArch64CC::VS;
930     break;
931   case ISD::SETUEQ:
932     CondCode = AArch64CC::EQ;
933     CondCode2 = AArch64CC::VS;
934     break;
935   case ISD::SETUGT:
936     CondCode = AArch64CC::HI;
937     break;
938   case ISD::SETUGE:
939     CondCode = AArch64CC::PL;
940     break;
941   case ISD::SETLT:
942   case ISD::SETULT:
943     CondCode = AArch64CC::LT;
944     break;
945   case ISD::SETLE:
946   case ISD::SETULE:
947     CondCode = AArch64CC::LE;
948     break;
949   case ISD::SETNE:
950   case ISD::SETUNE:
951     CondCode = AArch64CC::NE;
952     break;
953   }
954 }
955
956 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
957 /// CC usable with the vector instructions. Fewer operations are available
958 /// without a real NZCV register, so we have to use less efficient combinations
959 /// to get the same effect.
960 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
961                                         AArch64CC::CondCode &CondCode,
962                                         AArch64CC::CondCode &CondCode2,
963                                         bool &Invert) {
964   Invert = false;
965   switch (CC) {
966   default:
967     // Mostly the scalar mappings work fine.
968     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
969     break;
970   case ISD::SETUO:
971     Invert = true; // Fallthrough
972   case ISD::SETO:
973     CondCode = AArch64CC::MI;
974     CondCode2 = AArch64CC::GE;
975     break;
976   case ISD::SETUEQ:
977   case ISD::SETULT:
978   case ISD::SETULE:
979   case ISD::SETUGT:
980   case ISD::SETUGE:
981     // All of the compare-mask comparisons are ordered, but we can switch
982     // between the two by a double inversion. E.g. ULE == !OGT.
983     Invert = true;
984     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
985     break;
986   }
987 }
988
989 static bool isLegalArithImmed(uint64_t C) {
990   // Matches AArch64DAGToDAGISel::SelectArithImmed().
991   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
992 }
993
994 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
995                               SDLoc dl, SelectionDAG &DAG) {
996   EVT VT = LHS.getValueType();
997
998   if (VT.isFloatingPoint())
999     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1000
1001   // The CMP instruction is just an alias for SUBS, and representing it as
1002   // SUBS means that it's possible to get CSE with subtract operations.
1003   // A later phase can perform the optimization of setting the destination
1004   // register to WZR/XZR if it ends up being unused.
1005   unsigned Opcode = AArch64ISD::SUBS;
1006
1007   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1008       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1009       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1010     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1011     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1012     // can be set differently by this operation. It comes down to whether
1013     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1014     // everything is fine. If not then the optimization is wrong. Thus general
1015     // comparisons are only valid if op2 != 0.
1016
1017     // So, finally, the only LLVM-native comparisons that don't mention C and V
1018     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1019     // the absence of information about op2.
1020     Opcode = AArch64ISD::ADDS;
1021     RHS = RHS.getOperand(1);
1022   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1023              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1024              !isUnsignedIntSetCC(CC)) {
1025     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1026     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1027     // of the signed comparisons.
1028     Opcode = AArch64ISD::ANDS;
1029     RHS = LHS.getOperand(1);
1030     LHS = LHS.getOperand(0);
1031   }
1032
1033   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1034       .getValue(1);
1035 }
1036
1037 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1038                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1039   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1040     EVT VT = RHS.getValueType();
1041     uint64_t C = RHSC->getZExtValue();
1042     if (!isLegalArithImmed(C)) {
1043       // Constant does not fit, try adjusting it by one?
1044       switch (CC) {
1045       default:
1046         break;
1047       case ISD::SETLT:
1048       case ISD::SETGE:
1049         if ((VT == MVT::i32 && C != 0x80000000 &&
1050              isLegalArithImmed((uint32_t)(C - 1))) ||
1051             (VT == MVT::i64 && C != 0x80000000ULL &&
1052              isLegalArithImmed(C - 1ULL))) {
1053           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1054           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1055           RHS = DAG.getConstant(C, VT);
1056         }
1057         break;
1058       case ISD::SETULT:
1059       case ISD::SETUGE:
1060         if ((VT == MVT::i32 && C != 0 &&
1061              isLegalArithImmed((uint32_t)(C - 1))) ||
1062             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1063           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1064           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1065           RHS = DAG.getConstant(C, VT);
1066         }
1067         break;
1068       case ISD::SETLE:
1069       case ISD::SETGT:
1070         if ((VT == MVT::i32 && C != 0x7fffffff &&
1071              isLegalArithImmed((uint32_t)(C + 1))) ||
1072             (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1073              isLegalArithImmed(C + 1ULL))) {
1074           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1075           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1076           RHS = DAG.getConstant(C, VT);
1077         }
1078         break;
1079       case ISD::SETULE:
1080       case ISD::SETUGT:
1081         if ((VT == MVT::i32 && C != 0xffffffff &&
1082              isLegalArithImmed((uint32_t)(C + 1))) ||
1083             (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1084              isLegalArithImmed(C + 1ULL))) {
1085           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1086           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1087           RHS = DAG.getConstant(C, VT);
1088         }
1089         break;
1090       }
1091     }
1092   }
1093
1094   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1095   AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
1096   AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1097   return Cmp;
1098 }
1099
1100 static std::pair<SDValue, SDValue>
1101 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1102   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1103          "Unsupported value type");
1104   SDValue Value, Overflow;
1105   SDLoc DL(Op);
1106   SDValue LHS = Op.getOperand(0);
1107   SDValue RHS = Op.getOperand(1);
1108   unsigned Opc = 0;
1109   switch (Op.getOpcode()) {
1110   default:
1111     llvm_unreachable("Unknown overflow instruction!");
1112   case ISD::SADDO:
1113     Opc = AArch64ISD::ADDS;
1114     CC = AArch64CC::VS;
1115     break;
1116   case ISD::UADDO:
1117     Opc = AArch64ISD::ADDS;
1118     CC = AArch64CC::HS;
1119     break;
1120   case ISD::SSUBO:
1121     Opc = AArch64ISD::SUBS;
1122     CC = AArch64CC::VS;
1123     break;
1124   case ISD::USUBO:
1125     Opc = AArch64ISD::SUBS;
1126     CC = AArch64CC::LO;
1127     break;
1128   // Multiply needs a little bit extra work.
1129   case ISD::SMULO:
1130   case ISD::UMULO: {
1131     CC = AArch64CC::NE;
1132     bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1133     if (Op.getValueType() == MVT::i32) {
1134       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1135       // For a 32 bit multiply with overflow check we want the instruction
1136       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1137       // need to generate the following pattern:
1138       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1139       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1140       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1141       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1142       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1143                                 DAG.getConstant(0, MVT::i64));
1144       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1145       // operation. We need to clear out the upper 32 bits, because we used a
1146       // widening multiply that wrote all 64 bits. In the end this should be a
1147       // noop.
1148       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1149       if (IsSigned) {
1150         // The signed overflow check requires more than just a simple check for
1151         // any bit set in the upper 32 bits of the result. These bits could be
1152         // just the sign bits of a negative number. To perform the overflow
1153         // check we have to arithmetic shift right the 32nd bit of the result by
1154         // 31 bits. Then we compare the result to the upper 32 bits.
1155         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1156                                         DAG.getConstant(32, MVT::i64));
1157         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1158         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1159                                         DAG.getConstant(31, MVT::i64));
1160         // It is important that LowerBits is last, otherwise the arithmetic
1161         // shift will not be folded into the compare (SUBS).
1162         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1163         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1164                        .getValue(1);
1165       } else {
1166         // The overflow check for unsigned multiply is easy. We only need to
1167         // check if any of the upper 32 bits are set. This can be done with a
1168         // CMP (shifted register). For that we need to generate the following
1169         // pattern:
1170         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1171         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1172                                         DAG.getConstant(32, MVT::i64));
1173         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1174         Overflow =
1175             DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1176                         UpperBits).getValue(1);
1177       }
1178       break;
1179     }
1180     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1181     // For the 64 bit multiply
1182     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1183     if (IsSigned) {
1184       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1185       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1186                                       DAG.getConstant(63, MVT::i64));
1187       // It is important that LowerBits is last, otherwise the arithmetic
1188       // shift will not be folded into the compare (SUBS).
1189       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1190       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1191                      .getValue(1);
1192     } else {
1193       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1194       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1195       Overflow =
1196           DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1197                       UpperBits).getValue(1);
1198     }
1199     break;
1200   }
1201   } // switch (...)
1202
1203   if (Opc) {
1204     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1205
1206     // Emit the AArch64 operation with overflow check.
1207     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1208     Overflow = Value.getValue(1);
1209   }
1210   return std::make_pair(Value, Overflow);
1211 }
1212
1213 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1214                                              RTLIB::Libcall Call) const {
1215   SmallVector<SDValue, 2> Ops;
1216   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1217     Ops.push_back(Op.getOperand(i));
1218
1219   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1220                      SDLoc(Op)).first;
1221 }
1222
1223 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1224   SDValue Sel = Op.getOperand(0);
1225   SDValue Other = Op.getOperand(1);
1226
1227   // If neither operand is a SELECT_CC, give up.
1228   if (Sel.getOpcode() != ISD::SELECT_CC)
1229     std::swap(Sel, Other);
1230   if (Sel.getOpcode() != ISD::SELECT_CC)
1231     return Op;
1232
1233   // The folding we want to perform is:
1234   // (xor x, (select_cc a, b, cc, 0, -1) )
1235   //   -->
1236   // (csel x, (xor x, -1), cc ...)
1237   //
1238   // The latter will get matched to a CSINV instruction.
1239
1240   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1241   SDValue LHS = Sel.getOperand(0);
1242   SDValue RHS = Sel.getOperand(1);
1243   SDValue TVal = Sel.getOperand(2);
1244   SDValue FVal = Sel.getOperand(3);
1245   SDLoc dl(Sel);
1246
1247   // FIXME: This could be generalized to non-integer comparisons.
1248   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1249     return Op;
1250
1251   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1252   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1253
1254   // The the values aren't constants, this isn't the pattern we're looking for.
1255   if (!CFVal || !CTVal)
1256     return Op;
1257
1258   // We can commute the SELECT_CC by inverting the condition.  This
1259   // might be needed to make this fit into a CSINV pattern.
1260   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1261     std::swap(TVal, FVal);
1262     std::swap(CTVal, CFVal);
1263     CC = ISD::getSetCCInverse(CC, true);
1264   }
1265
1266   // If the constants line up, perform the transform!
1267   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1268     SDValue CCVal;
1269     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1270
1271     FVal = Other;
1272     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1273                        DAG.getConstant(-1ULL, Other.getValueType()));
1274
1275     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1276                        CCVal, Cmp);
1277   }
1278
1279   return Op;
1280 }
1281
1282 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1283   EVT VT = Op.getValueType();
1284
1285   // Let legalize expand this if it isn't a legal type yet.
1286   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1287     return SDValue();
1288
1289   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1290
1291   unsigned Opc;
1292   bool ExtraOp = false;
1293   switch (Op.getOpcode()) {
1294   default:
1295     llvm_unreachable("Invalid code");
1296   case ISD::ADDC:
1297     Opc = AArch64ISD::ADDS;
1298     break;
1299   case ISD::SUBC:
1300     Opc = AArch64ISD::SUBS;
1301     break;
1302   case ISD::ADDE:
1303     Opc = AArch64ISD::ADCS;
1304     ExtraOp = true;
1305     break;
1306   case ISD::SUBE:
1307     Opc = AArch64ISD::SBCS;
1308     ExtraOp = true;
1309     break;
1310   }
1311
1312   if (!ExtraOp)
1313     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1314   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1315                      Op.getOperand(2));
1316 }
1317
1318 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1319   // Let legalize expand this if it isn't a legal type yet.
1320   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1321     return SDValue();
1322
1323   AArch64CC::CondCode CC;
1324   // The actual operation that sets the overflow or carry flag.
1325   SDValue Value, Overflow;
1326   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1327
1328   // We use 0 and 1 as false and true values.
1329   SDValue TVal = DAG.getConstant(1, MVT::i32);
1330   SDValue FVal = DAG.getConstant(0, MVT::i32);
1331
1332   // We use an inverted condition, because the conditional select is inverted
1333   // too. This will allow it to be selected to a single instruction:
1334   // CSINC Wd, WZR, WZR, invert(cond).
1335   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1336   Overflow = DAG.getNode(AArch64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal,
1337                          CCVal, Overflow);
1338
1339   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1340   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1341 }
1342
1343 // Prefetch operands are:
1344 // 1: Address to prefetch
1345 // 2: bool isWrite
1346 // 3: int locality (0 = no locality ... 3 = extreme locality)
1347 // 4: bool isDataCache
1348 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1349   SDLoc DL(Op);
1350   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1351   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1352   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1353
1354   bool IsStream = !Locality;
1355   // When the locality number is set
1356   if (Locality) {
1357     // The front-end should have filtered out the out-of-range values
1358     assert(Locality <= 3 && "Prefetch locality out-of-range");
1359     // The locality degree is the opposite of the cache speed.
1360     // Put the number the other way around.
1361     // The encoding starts at 0 for level 1
1362     Locality = 3 - Locality;
1363   }
1364
1365   // built the mask value encoding the expected behavior.
1366   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1367                    (!IsData << 3) |     // IsDataCache bit
1368                    (Locality << 1) |    // Cache level bits
1369                    (unsigned)IsStream;  // Stream bit
1370   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1371                      DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1372 }
1373
1374 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1375                                               SelectionDAG &DAG) const {
1376   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1377
1378   RTLIB::Libcall LC;
1379   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1380
1381   return LowerF128Call(Op, DAG, LC);
1382 }
1383
1384 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1385                                              SelectionDAG &DAG) const {
1386   if (Op.getOperand(0).getValueType() != MVT::f128) {
1387     // It's legal except when f128 is involved
1388     return Op;
1389   }
1390
1391   RTLIB::Libcall LC;
1392   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1393
1394   // FP_ROUND node has a second operand indicating whether it is known to be
1395   // precise. That doesn't take part in the LibCall so we can't directly use
1396   // LowerF128Call.
1397   SDValue SrcVal = Op.getOperand(0);
1398   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1399                      /*isSigned*/ false, SDLoc(Op)).first;
1400 }
1401
1402 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1403   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1404   // Any additional optimization in this function should be recorded
1405   // in the cost tables.
1406   EVT InVT = Op.getOperand(0).getValueType();
1407   EVT VT = Op.getValueType();
1408
1409   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1410     SDLoc dl(Op);
1411     SDValue Cv =
1412         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1413                     Op.getOperand(0));
1414     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1415   }
1416
1417   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1418     SDLoc dl(Op);
1419     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1420     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1421   }
1422
1423   // Type changing conversions are illegal.
1424   return Op;
1425 }
1426
1427 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1428                                               SelectionDAG &DAG) const {
1429   if (Op.getOperand(0).getValueType().isVector())
1430     return LowerVectorFP_TO_INT(Op, DAG);
1431
1432   if (Op.getOperand(0).getValueType() != MVT::f128) {
1433     // It's legal except when f128 is involved
1434     return Op;
1435   }
1436
1437   RTLIB::Libcall LC;
1438   if (Op.getOpcode() == ISD::FP_TO_SINT)
1439     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1440   else
1441     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1442
1443   SmallVector<SDValue, 2> Ops;
1444   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1445     Ops.push_back(Op.getOperand(i));
1446
1447   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1448                      SDLoc(Op)).first;
1449 }
1450
1451 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1452   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1453   // Any additional optimization in this function should be recorded
1454   // in the cost tables.
1455   EVT VT = Op.getValueType();
1456   SDLoc dl(Op);
1457   SDValue In = Op.getOperand(0);
1458   EVT InVT = In.getValueType();
1459
1460   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1461     MVT CastVT =
1462         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1463                          InVT.getVectorNumElements());
1464     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1465     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0));
1466   }
1467
1468   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1469     unsigned CastOpc =
1470         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1471     EVT CastVT = VT.changeVectorElementTypeToInteger();
1472     In = DAG.getNode(CastOpc, dl, CastVT, In);
1473     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1474   }
1475
1476   return Op;
1477 }
1478
1479 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1480                                             SelectionDAG &DAG) const {
1481   if (Op.getValueType().isVector())
1482     return LowerVectorINT_TO_FP(Op, DAG);
1483
1484   // i128 conversions are libcalls.
1485   if (Op.getOperand(0).getValueType() == MVT::i128)
1486     return SDValue();
1487
1488   // Other conversions are legal, unless it's to the completely software-based
1489   // fp128.
1490   if (Op.getValueType() != MVT::f128)
1491     return Op;
1492
1493   RTLIB::Libcall LC;
1494   if (Op.getOpcode() == ISD::SINT_TO_FP)
1495     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1496   else
1497     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1498
1499   return LowerF128Call(Op, DAG, LC);
1500 }
1501
1502 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1503                                             SelectionDAG &DAG) const {
1504   // For iOS, we want to call an alternative entry point: __sincos_stret,
1505   // which returns the values in two S / D registers.
1506   SDLoc dl(Op);
1507   SDValue Arg = Op.getOperand(0);
1508   EVT ArgVT = Arg.getValueType();
1509   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1510
1511   ArgListTy Args;
1512   ArgListEntry Entry;
1513
1514   Entry.Node = Arg;
1515   Entry.Ty = ArgTy;
1516   Entry.isSExt = false;
1517   Entry.isZExt = false;
1518   Args.push_back(Entry);
1519
1520   const char *LibcallName =
1521       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1522   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1523
1524   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1525   TargetLowering::CallLoweringInfo CLI(DAG);
1526   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1527     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1528
1529   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1530   return CallResult.first;
1531 }
1532
1533 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1534   if (Op.getValueType() != MVT::f16)
1535     return SDValue();
1536
1537   assert(Op.getOperand(0).getValueType() == MVT::i16);
1538   SDLoc DL(Op);
1539
1540   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1541   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1542   return SDValue(
1543       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1544                          DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
1545       0);
1546 }
1547
1548
1549 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1550                                               SelectionDAG &DAG) const {
1551   switch (Op.getOpcode()) {
1552   default:
1553     llvm_unreachable("unimplemented operand");
1554     return SDValue();
1555   case ISD::BITCAST:
1556     return LowerBITCAST(Op, DAG);
1557   case ISD::GlobalAddress:
1558     return LowerGlobalAddress(Op, DAG);
1559   case ISD::GlobalTLSAddress:
1560     return LowerGlobalTLSAddress(Op, DAG);
1561   case ISD::SETCC:
1562     return LowerSETCC(Op, DAG);
1563   case ISD::BR_CC:
1564     return LowerBR_CC(Op, DAG);
1565   case ISD::SELECT:
1566     return LowerSELECT(Op, DAG);
1567   case ISD::SELECT_CC:
1568     return LowerSELECT_CC(Op, DAG);
1569   case ISD::JumpTable:
1570     return LowerJumpTable(Op, DAG);
1571   case ISD::ConstantPool:
1572     return LowerConstantPool(Op, DAG);
1573   case ISD::BlockAddress:
1574     return LowerBlockAddress(Op, DAG);
1575   case ISD::VASTART:
1576     return LowerVASTART(Op, DAG);
1577   case ISD::VACOPY:
1578     return LowerVACOPY(Op, DAG);
1579   case ISD::VAARG:
1580     return LowerVAARG(Op, DAG);
1581   case ISD::ADDC:
1582   case ISD::ADDE:
1583   case ISD::SUBC:
1584   case ISD::SUBE:
1585     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1586   case ISD::SADDO:
1587   case ISD::UADDO:
1588   case ISD::SSUBO:
1589   case ISD::USUBO:
1590   case ISD::SMULO:
1591   case ISD::UMULO:
1592     return LowerXALUO(Op, DAG);
1593   case ISD::FADD:
1594     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1595   case ISD::FSUB:
1596     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1597   case ISD::FMUL:
1598     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1599   case ISD::FDIV:
1600     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1601   case ISD::FP_ROUND:
1602     return LowerFP_ROUND(Op, DAG);
1603   case ISD::FP_EXTEND:
1604     return LowerFP_EXTEND(Op, DAG);
1605   case ISD::FRAMEADDR:
1606     return LowerFRAMEADDR(Op, DAG);
1607   case ISD::RETURNADDR:
1608     return LowerRETURNADDR(Op, DAG);
1609   case ISD::INSERT_VECTOR_ELT:
1610     return LowerINSERT_VECTOR_ELT(Op, DAG);
1611   case ISD::EXTRACT_VECTOR_ELT:
1612     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1613   case ISD::BUILD_VECTOR:
1614     return LowerBUILD_VECTOR(Op, DAG);
1615   case ISD::VECTOR_SHUFFLE:
1616     return LowerVECTOR_SHUFFLE(Op, DAG);
1617   case ISD::EXTRACT_SUBVECTOR:
1618     return LowerEXTRACT_SUBVECTOR(Op, DAG);
1619   case ISD::SRA:
1620   case ISD::SRL:
1621   case ISD::SHL:
1622     return LowerVectorSRA_SRL_SHL(Op, DAG);
1623   case ISD::SHL_PARTS:
1624     return LowerShiftLeftParts(Op, DAG);
1625   case ISD::SRL_PARTS:
1626   case ISD::SRA_PARTS:
1627     return LowerShiftRightParts(Op, DAG);
1628   case ISD::CTPOP:
1629     return LowerCTPOP(Op, DAG);
1630   case ISD::FCOPYSIGN:
1631     return LowerFCOPYSIGN(Op, DAG);
1632   case ISD::AND:
1633     return LowerVectorAND(Op, DAG);
1634   case ISD::OR:
1635     return LowerVectorOR(Op, DAG);
1636   case ISD::XOR:
1637     return LowerXOR(Op, DAG);
1638   case ISD::PREFETCH:
1639     return LowerPREFETCH(Op, DAG);
1640   case ISD::SINT_TO_FP:
1641   case ISD::UINT_TO_FP:
1642     return LowerINT_TO_FP(Op, DAG);
1643   case ISD::FP_TO_SINT:
1644   case ISD::FP_TO_UINT:
1645     return LowerFP_TO_INT(Op, DAG);
1646   case ISD::FSINCOS:
1647     return LowerFSINCOS(Op, DAG);
1648   }
1649 }
1650
1651 /// getFunctionAlignment - Return the Log2 alignment of this function.
1652 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
1653   return 2;
1654 }
1655
1656 //===----------------------------------------------------------------------===//
1657 //                      Calling Convention Implementation
1658 //===----------------------------------------------------------------------===//
1659
1660 #include "AArch64GenCallingConv.inc"
1661
1662 /// Selects the correct CCAssignFn for a the given CallingConvention
1663 /// value.
1664 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1665                                                      bool IsVarArg) const {
1666   switch (CC) {
1667   default:
1668     llvm_unreachable("Unsupported calling convention.");
1669   case CallingConv::WebKit_JS:
1670     return CC_AArch64_WebKit_JS;
1671   case CallingConv::C:
1672   case CallingConv::Fast:
1673     if (!Subtarget->isTargetDarwin())
1674       return CC_AArch64_AAPCS;
1675     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
1676   }
1677 }
1678
1679 SDValue AArch64TargetLowering::LowerFormalArguments(
1680     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1681     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1682     SmallVectorImpl<SDValue> &InVals) const {
1683   MachineFunction &MF = DAG.getMachineFunction();
1684   MachineFrameInfo *MFI = MF.getFrameInfo();
1685
1686   // Assign locations to all of the incoming arguments.
1687   SmallVector<CCValAssign, 16> ArgLocs;
1688   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1689                  *DAG.getContext());
1690
1691   // At this point, Ins[].VT may already be promoted to i32. To correctly
1692   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1693   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
1694   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1695   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1696   // LocVT.
1697   unsigned NumArgs = Ins.size();
1698   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1699   unsigned CurArgIdx = 0;
1700   for (unsigned i = 0; i != NumArgs; ++i) {
1701     MVT ValVT = Ins[i].VT;
1702     std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1703     CurArgIdx = Ins[i].OrigArgIndex;
1704
1705     // Get type of the original argument.
1706     EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1707     MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1708     // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1709     if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1710       ValVT = MVT::i8;
1711     else if (ActualMVT == MVT::i16)
1712       ValVT = MVT::i16;
1713
1714     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1715     bool Res =
1716         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1717     assert(!Res && "Call operand has unhandled type");
1718     (void)Res;
1719   }
1720   assert(ArgLocs.size() == Ins.size());
1721   SmallVector<SDValue, 16> ArgValues;
1722   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1723     CCValAssign &VA = ArgLocs[i];
1724
1725     if (Ins[i].Flags.isByVal()) {
1726       // Byval is used for HFAs in the PCS, but the system should work in a
1727       // non-compliant manner for larger structs.
1728       EVT PtrTy = getPointerTy();
1729       int Size = Ins[i].Flags.getByValSize();
1730       unsigned NumRegs = (Size + 7) / 8;
1731
1732       // FIXME: This works on big-endian for composite byvals, which are the common
1733       // case. It should also work for fundamental types too.
1734       unsigned FrameIdx =
1735         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1736       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1737       InVals.push_back(FrameIdxN);
1738
1739       continue;
1740     }
1741     
1742     if (VA.isRegLoc()) {
1743       // Arguments stored in registers.
1744       EVT RegVT = VA.getLocVT();
1745
1746       SDValue ArgValue;
1747       const TargetRegisterClass *RC;
1748
1749       if (RegVT == MVT::i32)
1750         RC = &AArch64::GPR32RegClass;
1751       else if (RegVT == MVT::i64)
1752         RC = &AArch64::GPR64RegClass;
1753       else if (RegVT == MVT::f16)
1754         RC = &AArch64::FPR16RegClass;
1755       else if (RegVT == MVT::f32)
1756         RC = &AArch64::FPR32RegClass;
1757       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1758         RC = &AArch64::FPR64RegClass;
1759       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1760         RC = &AArch64::FPR128RegClass;
1761       else
1762         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1763
1764       // Transform the arguments in physical registers into virtual ones.
1765       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1766       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1767
1768       // If this is an 8, 16 or 32-bit value, it is really passed promoted
1769       // to 64 bits.  Insert an assert[sz]ext to capture this, then
1770       // truncate to the right size.
1771       switch (VA.getLocInfo()) {
1772       default:
1773         llvm_unreachable("Unknown loc info!");
1774       case CCValAssign::Full:
1775         break;
1776       case CCValAssign::BCvt:
1777         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1778         break;
1779       case CCValAssign::AExt:
1780       case CCValAssign::SExt:
1781       case CCValAssign::ZExt:
1782         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
1783         // nodes after our lowering.
1784         assert(RegVT == Ins[i].VT && "incorrect register location selected");
1785         break;
1786       }
1787
1788       InVals.push_back(ArgValue);
1789
1790     } else { // VA.isRegLoc()
1791       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1792       unsigned ArgOffset = VA.getLocMemOffset();
1793       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
1794
1795       uint32_t BEAlign = 0;
1796       if (ArgSize < 8 && !Subtarget->isLittleEndian())
1797         BEAlign = 8 - ArgSize;
1798
1799       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
1800
1801       // Create load nodes to retrieve arguments from the stack.
1802       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1803       SDValue ArgValue;
1804
1805       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1806       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1807       MVT MemVT = VA.getValVT();
1808
1809       switch (VA.getLocInfo()) {
1810       default:
1811         break;
1812       case CCValAssign::BCvt:
1813         MemVT = VA.getLocVT();
1814         break;
1815       case CCValAssign::SExt:
1816         ExtType = ISD::SEXTLOAD;
1817         break;
1818       case CCValAssign::ZExt:
1819         ExtType = ISD::ZEXTLOAD;
1820         break;
1821       case CCValAssign::AExt:
1822         ExtType = ISD::EXTLOAD;
1823         break;
1824       }
1825
1826       ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
1827                                 MachinePointerInfo::getFixedStack(FI),
1828                                 MemVT, false, false, false, 0, nullptr);
1829
1830       InVals.push_back(ArgValue);
1831     }
1832   }
1833
1834   // varargs
1835   if (isVarArg) {
1836     if (!Subtarget->isTargetDarwin()) {
1837       // The AAPCS variadic function ABI is identical to the non-variadic
1838       // one. As a result there may be more arguments in registers and we should
1839       // save them for future reference.
1840       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1841     }
1842
1843     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1844     // This will point to the next argument passed via stack.
1845     unsigned StackOffset = CCInfo.getNextStackOffset();
1846     // We currently pass all varargs at 8-byte alignment.
1847     StackOffset = ((StackOffset + 7) & ~7);
1848     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1849   }
1850
1851   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1852   unsigned StackArgSize = CCInfo.getNextStackOffset();
1853   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1854   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1855     // This is a non-standard ABI so by fiat I say we're allowed to make full
1856     // use of the stack area to be popped, which must be aligned to 16 bytes in
1857     // any case:
1858     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1859
1860     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1861     // a multiple of 16.
1862     FuncInfo->setArgumentStackToRestore(StackArgSize);
1863
1864     // This realignment carries over to the available bytes below. Our own
1865     // callers will guarantee the space is free by giving an aligned value to
1866     // CALLSEQ_START.
1867   }
1868   // Even if we're not expected to free up the space, it's useful to know how
1869   // much is there while considering tail calls (because we can reuse it).
1870   FuncInfo->setBytesInStackArgArea(StackArgSize);
1871
1872   return Chain;
1873 }
1874
1875 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1876                                                 SelectionDAG &DAG, SDLoc DL,
1877                                                 SDValue &Chain) const {
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   MachineFrameInfo *MFI = MF.getFrameInfo();
1880   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1881
1882   SmallVector<SDValue, 8> MemOps;
1883
1884   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
1885                                           AArch64::X3, AArch64::X4, AArch64::X5,
1886                                           AArch64::X6, AArch64::X7 };
1887   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1888   unsigned FirstVariadicGPR =
1889       CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1890
1891   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1892   int GPRIdx = 0;
1893   if (GPRSaveSize != 0) {
1894     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1895
1896     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1897
1898     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1899       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
1900       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1901       SDValue Store =
1902           DAG.getStore(Val.getValue(1), DL, Val, FIN,
1903                        MachinePointerInfo::getStack(i * 8), false, false, 0);
1904       MemOps.push_back(Store);
1905       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1906                         DAG.getConstant(8, getPointerTy()));
1907     }
1908   }
1909   FuncInfo->setVarArgsGPRIndex(GPRIdx);
1910   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1911
1912   if (Subtarget->hasFPARMv8()) {
1913     static const MCPhysReg FPRArgRegs[] = {
1914         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
1915         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
1916     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1917     unsigned FirstVariadicFPR =
1918         CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1919
1920     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1921     int FPRIdx = 0;
1922     if (FPRSaveSize != 0) {
1923       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1924
1925       SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1926
1927       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1928         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
1929         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1930
1931         SDValue Store =
1932             DAG.getStore(Val.getValue(1), DL, Val, FIN,
1933                          MachinePointerInfo::getStack(i * 16), false, false, 0);
1934         MemOps.push_back(Store);
1935         FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1936                           DAG.getConstant(16, getPointerTy()));
1937       }
1938     }
1939     FuncInfo->setVarArgsFPRIndex(FPRIdx);
1940     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1941   }
1942
1943   if (!MemOps.empty()) {
1944     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1945   }
1946 }
1947
1948 /// LowerCallResult - Lower the result values of a call into the
1949 /// appropriate copies out of appropriate physical registers.
1950 SDValue AArch64TargetLowering::LowerCallResult(
1951     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1952     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1953     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1954     SDValue ThisVal) const {
1955   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
1956                           ? RetCC_AArch64_WebKit_JS
1957                           : RetCC_AArch64_AAPCS;
1958   // Assign locations to each value returned by this call.
1959   SmallVector<CCValAssign, 16> RVLocs;
1960   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1961                  *DAG.getContext());
1962   CCInfo.AnalyzeCallResult(Ins, RetCC);
1963
1964   // Copy all of the result registers out of their specified physreg.
1965   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1966     CCValAssign VA = RVLocs[i];
1967
1968     // Pass 'this' value directly from the argument to return value, to avoid
1969     // reg unit interference
1970     if (i == 0 && isThisReturn) {
1971       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1972              "unexpected return calling convention register assignment");
1973       InVals.push_back(ThisVal);
1974       continue;
1975     }
1976
1977     SDValue Val =
1978         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1979     Chain = Val.getValue(1);
1980     InFlag = Val.getValue(2);
1981
1982     switch (VA.getLocInfo()) {
1983     default:
1984       llvm_unreachable("Unknown loc info!");
1985     case CCValAssign::Full:
1986       break;
1987     case CCValAssign::BCvt:
1988       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1989       break;
1990     }
1991
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
1999     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2000     bool isCalleeStructRet, bool isCallerStructRet,
2001     const SmallVectorImpl<ISD::OutputArg> &Outs,
2002     const SmallVectorImpl<SDValue> &OutVals,
2003     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2004   // For CallingConv::C this function knows whether the ABI needs
2005   // changing. That's not true for other conventions so they will have to opt in
2006   // manually.
2007   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2008     return false;
2009
2010   const MachineFunction &MF = DAG.getMachineFunction();
2011   const Function *CallerF = MF.getFunction();
2012   CallingConv::ID CallerCC = CallerF->getCallingConv();
2013   bool CCMatch = CallerCC == CalleeCC;
2014
2015   // Byval parameters hand the function a pointer directly into the stack area
2016   // we want to reuse during a tail call. Working around this *is* possible (see
2017   // X86) but less efficient and uglier in LowerCall.
2018   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2019                                     e = CallerF->arg_end();
2020        i != e; ++i)
2021     if (i->hasByValAttr())
2022       return false;
2023
2024   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2025     if (IsTailCallConvention(CalleeCC) && CCMatch)
2026       return true;
2027     return false;
2028   }
2029
2030   // Externally-defined functions with weak linkage should not be
2031   // tail-called on AArch64 when the OS does not support dynamic
2032   // pre-emption of symbols, as the AAELF spec requires normal calls
2033   // to undefined weak functions to be replaced with a NOP or jump to the
2034   // next instruction. The behaviour of branch instructions in this
2035   // situation (as used for tail calls) is implementation-defined, so we
2036   // cannot rely on the linker replacing the tail call with a return.
2037   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2038     const GlobalValue *GV = G->getGlobal();
2039     if (GV->hasExternalWeakLinkage())
2040       return false;
2041   }
2042
2043   // Now we search for cases where we can use a tail call without changing the
2044   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2045   // concept.
2046
2047   // I want anyone implementing a new calling convention to think long and hard
2048   // about this assert.
2049   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2050          "Unexpected variadic calling convention");
2051
2052   if (isVarArg && !Outs.empty()) {
2053     // At least two cases here: if caller is fastcc then we can't have any
2054     // memory arguments (we'd be expected to clean up the stack afterwards). If
2055     // caller is C then we could potentially use its argument area.
2056
2057     // FIXME: for now we take the most conservative of these in both cases:
2058     // disallow all variadic memory operands.
2059     SmallVector<CCValAssign, 16> ArgLocs;
2060     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2061                    *DAG.getContext());
2062
2063     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2064     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2065       if (!ArgLocs[i].isRegLoc())
2066         return false;
2067   }
2068
2069   // If the calling conventions do not match, then we'd better make sure the
2070   // results are returned in the same way as what the caller expects.
2071   if (!CCMatch) {
2072     SmallVector<CCValAssign, 16> RVLocs1;
2073     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2074                     *DAG.getContext());
2075     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2076
2077     SmallVector<CCValAssign, 16> RVLocs2;
2078     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2079                     *DAG.getContext());
2080     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2081
2082     if (RVLocs1.size() != RVLocs2.size())
2083       return false;
2084     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2085       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2086         return false;
2087       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2088         return false;
2089       if (RVLocs1[i].isRegLoc()) {
2090         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2091           return false;
2092       } else {
2093         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2094           return false;
2095       }
2096     }
2097   }
2098
2099   // Nothing more to check if the callee is taking no arguments
2100   if (Outs.empty())
2101     return true;
2102
2103   SmallVector<CCValAssign, 16> ArgLocs;
2104   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2105                  *DAG.getContext());
2106
2107   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2108
2109   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2110
2111   // If the stack arguments for this call would fit into our own save area then
2112   // the call can be made tail.
2113   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2114 }
2115
2116 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2117                                                    SelectionDAG &DAG,
2118                                                    MachineFrameInfo *MFI,
2119                                                    int ClobberedFI) const {
2120   SmallVector<SDValue, 8> ArgChains;
2121   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2122   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2123
2124   // Include the original chain at the beginning of the list. When this is
2125   // used by target LowerCall hooks, this helps legalize find the
2126   // CALLSEQ_BEGIN node.
2127   ArgChains.push_back(Chain);
2128
2129   // Add a chain value for each stack argument corresponding
2130   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2131                             UE = DAG.getEntryNode().getNode()->use_end();
2132        U != UE; ++U)
2133     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2134       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2135         if (FI->getIndex() < 0) {
2136           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2137           int64_t InLastByte = InFirstByte;
2138           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2139
2140           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2141               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2142             ArgChains.push_back(SDValue(L, 1));
2143         }
2144
2145   // Build a tokenfactor for all the chains.
2146   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2147 }
2148
2149 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2150                                                    bool TailCallOpt) const {
2151   return CallCC == CallingConv::Fast && TailCallOpt;
2152 }
2153
2154 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2155   return CallCC == CallingConv::Fast;
2156 }
2157
2158 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2159 /// and add input and output parameter nodes.
2160 SDValue
2161 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2162                                  SmallVectorImpl<SDValue> &InVals) const {
2163   SelectionDAG &DAG = CLI.DAG;
2164   SDLoc &DL = CLI.DL;
2165   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2166   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2167   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2168   SDValue Chain = CLI.Chain;
2169   SDValue Callee = CLI.Callee;
2170   bool &IsTailCall = CLI.IsTailCall;
2171   CallingConv::ID CallConv = CLI.CallConv;
2172   bool IsVarArg = CLI.IsVarArg;
2173
2174   MachineFunction &MF = DAG.getMachineFunction();
2175   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2176   bool IsThisReturn = false;
2177
2178   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2179   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2180   bool IsSibCall = false;
2181
2182   if (IsTailCall) {
2183     // Check if it's really possible to do a tail call.
2184     IsTailCall = isEligibleForTailCallOptimization(
2185         Callee, CallConv, IsVarArg, IsStructRet,
2186         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2187     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2188       report_fatal_error("failed to perform tail call elimination on a call "
2189                          "site marked musttail");
2190
2191     // A sibling call is one where we're under the usual C ABI and not planning
2192     // to change that but can still do a tail call:
2193     if (!TailCallOpt && IsTailCall)
2194       IsSibCall = true;
2195
2196     if (IsTailCall)
2197       ++NumTailCalls;
2198   }
2199
2200   // Analyze operands of the call, assigning locations to each operand.
2201   SmallVector<CCValAssign, 16> ArgLocs;
2202   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2203                  *DAG.getContext());
2204
2205   if (IsVarArg) {
2206     // Handle fixed and variable vector arguments differently.
2207     // Variable vector arguments always go into memory.
2208     unsigned NumArgs = Outs.size();
2209
2210     for (unsigned i = 0; i != NumArgs; ++i) {
2211       MVT ArgVT = Outs[i].VT;
2212       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2213       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2214                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2215       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2216       assert(!Res && "Call operand has unhandled type");
2217       (void)Res;
2218     }
2219   } else {
2220     // At this point, Outs[].VT may already be promoted to i32. To correctly
2221     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2222     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2223     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2224     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2225     // LocVT.
2226     unsigned NumArgs = Outs.size();
2227     for (unsigned i = 0; i != NumArgs; ++i) {
2228       MVT ValVT = Outs[i].VT;
2229       // Get type of the original argument.
2230       EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2231                                   /*AllowUnknown*/ true);
2232       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2233       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2234       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2235       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2236         ValVT = MVT::i8;
2237       else if (ActualMVT == MVT::i16)
2238         ValVT = MVT::i16;
2239
2240       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2241       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2242       assert(!Res && "Call operand has unhandled type");
2243       (void)Res;
2244     }
2245   }
2246
2247   // Get a count of how many bytes are to be pushed on the stack.
2248   unsigned NumBytes = CCInfo.getNextStackOffset();
2249
2250   if (IsSibCall) {
2251     // Since we're not changing the ABI to make this a tail call, the memory
2252     // operands are already available in the caller's incoming argument space.
2253     NumBytes = 0;
2254   }
2255
2256   // FPDiff is the byte offset of the call's argument area from the callee's.
2257   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2258   // by this amount for a tail call. In a sibling call it must be 0 because the
2259   // caller will deallocate the entire stack and the callee still expects its
2260   // arguments to begin at SP+0. Completely unused for non-tail calls.
2261   int FPDiff = 0;
2262
2263   if (IsTailCall && !IsSibCall) {
2264     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2265
2266     // Since callee will pop argument stack as a tail call, we must keep the
2267     // popped size 16-byte aligned.
2268     NumBytes = RoundUpToAlignment(NumBytes, 16);
2269
2270     // FPDiff will be negative if this tail call requires more space than we
2271     // would automatically have in our incoming argument space. Positive if we
2272     // can actually shrink the stack.
2273     FPDiff = NumReusableBytes - NumBytes;
2274
2275     // The stack pointer must be 16-byte aligned at all times it's used for a
2276     // memory operation, which in practice means at *all* times and in
2277     // particular across call boundaries. Therefore our own arguments started at
2278     // a 16-byte aligned SP and the delta applied for the tail call should
2279     // satisfy the same constraint.
2280     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2281   }
2282
2283   // Adjust the stack pointer for the new arguments...
2284   // These operations are automatically eliminated by the prolog/epilog pass
2285   if (!IsSibCall)
2286     Chain =
2287         DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2288
2289   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2290
2291   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2292   SmallVector<SDValue, 8> MemOpChains;
2293
2294   // Walk the register/memloc assignments, inserting copies/loads.
2295   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2296        ++i, ++realArgIdx) {
2297     CCValAssign &VA = ArgLocs[i];
2298     SDValue Arg = OutVals[realArgIdx];
2299     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2300
2301     // Promote the value if needed.
2302     switch (VA.getLocInfo()) {
2303     default:
2304       llvm_unreachable("Unknown loc info!");
2305     case CCValAssign::Full:
2306       break;
2307     case CCValAssign::SExt:
2308       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2309       break;
2310     case CCValAssign::ZExt:
2311       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2312       break;
2313     case CCValAssign::AExt:
2314       if (Outs[realArgIdx].ArgVT == MVT::i1) {
2315         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2316         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2317         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2318       }
2319       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2320       break;
2321     case CCValAssign::BCvt:
2322       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2323       break;
2324     case CCValAssign::FPExt:
2325       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2326       break;
2327     }
2328
2329     if (VA.isRegLoc()) {
2330       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2331         assert(VA.getLocVT() == MVT::i64 &&
2332                "unexpected calling convention register assignment");
2333         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2334                "unexpected use of 'returned'");
2335         IsThisReturn = true;
2336       }
2337       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2338     } else {
2339       assert(VA.isMemLoc());
2340
2341       SDValue DstAddr;
2342       MachinePointerInfo DstInfo;
2343
2344       // FIXME: This works on big-endian for composite byvals, which are the
2345       // common case. It should also work for fundamental types too.
2346       uint32_t BEAlign = 0;
2347       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2348                                         : VA.getValVT().getSizeInBits();
2349       OpSize = (OpSize + 7) / 8;
2350       if (!Subtarget->isLittleEndian() && !Flags.isByVal()) {
2351         if (OpSize < 8)
2352           BEAlign = 8 - OpSize;
2353       }
2354       unsigned LocMemOffset = VA.getLocMemOffset();
2355       int32_t Offset = LocMemOffset + BEAlign;
2356       SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2357       PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2358
2359       if (IsTailCall) {
2360         Offset = Offset + FPDiff;
2361         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2362
2363         DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2364         DstInfo = MachinePointerInfo::getFixedStack(FI);
2365
2366         // Make sure any stack arguments overlapping with where we're storing
2367         // are loaded before this eventual operation. Otherwise they'll be
2368         // clobbered.
2369         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2370       } else {
2371         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2372
2373         DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2374         DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2375       }
2376
2377       if (Outs[i].Flags.isByVal()) {
2378         SDValue SizeNode =
2379             DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2380         SDValue Cpy = DAG.getMemcpy(
2381             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2382             /*isVol = */ false,
2383             /*AlwaysInline = */ false, DstInfo, MachinePointerInfo());
2384
2385         MemOpChains.push_back(Cpy);
2386       } else {
2387         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2388         // promoted to a legal register type i32, we should truncate Arg back to
2389         // i1/i8/i16.
2390         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2391             VA.getValVT() == MVT::i16)
2392           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2393
2394         SDValue Store =
2395             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2396         MemOpChains.push_back(Store);
2397       }
2398     }
2399   }
2400
2401   if (!MemOpChains.empty())
2402     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2403
2404   // Build a sequence of copy-to-reg nodes chained together with token chain
2405   // and flag operands which copy the outgoing args into the appropriate regs.
2406   SDValue InFlag;
2407   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2408     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2409                              RegsToPass[i].second, InFlag);
2410     InFlag = Chain.getValue(1);
2411   }
2412
2413   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2414   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2415   // node so that legalize doesn't hack it.
2416   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2417       Subtarget->isTargetMachO()) {
2418     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2419       const GlobalValue *GV = G->getGlobal();
2420       bool InternalLinkage = GV->hasInternalLinkage();
2421       if (InternalLinkage)
2422         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2423       else {
2424         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2425                                             AArch64II::MO_GOT);
2426         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2427       }
2428     } else if (ExternalSymbolSDNode *S =
2429                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
2430       const char *Sym = S->getSymbol();
2431       Callee =
2432           DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2433       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2434     }
2435   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2436     const GlobalValue *GV = G->getGlobal();
2437     Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2438   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2439     const char *Sym = S->getSymbol();
2440     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2441   }
2442
2443   // We don't usually want to end the call-sequence here because we would tidy
2444   // the frame up *after* the call, however in the ABI-changing tail-call case
2445   // we've carefully laid out the parameters so that when sp is reset they'll be
2446   // in the correct location.
2447   if (IsTailCall && !IsSibCall) {
2448     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2449                                DAG.getIntPtrConstant(0, true), InFlag, DL);
2450     InFlag = Chain.getValue(1);
2451   }
2452
2453   std::vector<SDValue> Ops;
2454   Ops.push_back(Chain);
2455   Ops.push_back(Callee);
2456
2457   if (IsTailCall) {
2458     // Each tail call may have to adjust the stack by a different amount, so
2459     // this information must travel along with the operation for eventual
2460     // consumption by emitEpilogue.
2461     Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
2462   }
2463
2464   // Add argument registers to the end of the list so that they are known live
2465   // into the call.
2466   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2467     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2468                                   RegsToPass[i].second.getValueType()));
2469
2470   // Add a register mask operand representing the call-preserved registers.
2471   const uint32_t *Mask;
2472   const TargetRegisterInfo *TRI =
2473       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2474   const AArch64RegisterInfo *ARI =
2475       static_cast<const AArch64RegisterInfo *>(TRI);
2476   if (IsThisReturn) {
2477     // For 'this' returns, use the X0-preserving mask if applicable
2478     Mask = ARI->getThisReturnPreservedMask(CallConv);
2479     if (!Mask) {
2480       IsThisReturn = false;
2481       Mask = ARI->getCallPreservedMask(CallConv);
2482     }
2483   } else
2484     Mask = ARI->getCallPreservedMask(CallConv);
2485
2486   assert(Mask && "Missing call preserved mask for calling convention");
2487   Ops.push_back(DAG.getRegisterMask(Mask));
2488
2489   if (InFlag.getNode())
2490     Ops.push_back(InFlag);
2491
2492   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2493
2494   // If we're doing a tall call, use a TC_RETURN here rather than an
2495   // actual call instruction.
2496   if (IsTailCall)
2497     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2498
2499   // Returns a chain and a flag for retval copy to use.
2500   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2501   InFlag = Chain.getValue(1);
2502
2503   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2504                                 ? RoundUpToAlignment(NumBytes, 16)
2505                                 : 0;
2506
2507   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2508                              DAG.getIntPtrConstant(CalleePopBytes, true),
2509                              InFlag, DL);
2510   if (!Ins.empty())
2511     InFlag = Chain.getValue(1);
2512
2513   // Handle result values, copying them out of physregs into vregs that we
2514   // return.
2515   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2516                          InVals, IsThisReturn,
2517                          IsThisReturn ? OutVals[0] : SDValue());
2518 }
2519
2520 bool AArch64TargetLowering::CanLowerReturn(
2521     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2522     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2523   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2524                           ? RetCC_AArch64_WebKit_JS
2525                           : RetCC_AArch64_AAPCS;
2526   SmallVector<CCValAssign, 16> RVLocs;
2527   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2528   return CCInfo.CheckReturn(Outs, RetCC);
2529 }
2530
2531 SDValue
2532 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2533                                    bool isVarArg,
2534                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2535                                    const SmallVectorImpl<SDValue> &OutVals,
2536                                    SDLoc DL, SelectionDAG &DAG) const {
2537   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2538                           ? RetCC_AArch64_WebKit_JS
2539                           : RetCC_AArch64_AAPCS;
2540   SmallVector<CCValAssign, 16> RVLocs;
2541   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2542                  *DAG.getContext());
2543   CCInfo.AnalyzeReturn(Outs, RetCC);
2544
2545   // Copy the result values into the output registers.
2546   SDValue Flag;
2547   SmallVector<SDValue, 4> RetOps(1, Chain);
2548   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2549        ++i, ++realRVLocIdx) {
2550     CCValAssign &VA = RVLocs[i];
2551     assert(VA.isRegLoc() && "Can only return in registers!");
2552     SDValue Arg = OutVals[realRVLocIdx];
2553
2554     switch (VA.getLocInfo()) {
2555     default:
2556       llvm_unreachable("Unknown loc info!");
2557     case CCValAssign::Full:
2558       if (Outs[i].ArgVT == MVT::i1) {
2559         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2560         // value. This is strictly redundant on Darwin (which uses "zeroext
2561         // i1"), but will be optimised out before ISel.
2562         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2563         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2564       }
2565       break;
2566     case CCValAssign::BCvt:
2567       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2568       break;
2569     }
2570
2571     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2572     Flag = Chain.getValue(1);
2573     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2574   }
2575
2576   RetOps[0] = Chain; // Update chain.
2577
2578   // Add the flag if we have it.
2579   if (Flag.getNode())
2580     RetOps.push_back(Flag);
2581
2582   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2583 }
2584
2585 //===----------------------------------------------------------------------===//
2586 //  Other Lowering Code
2587 //===----------------------------------------------------------------------===//
2588
2589 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2590                                                   SelectionDAG &DAG) const {
2591   EVT PtrVT = getPointerTy();
2592   SDLoc DL(Op);
2593   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2594   unsigned char OpFlags =
2595       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2596
2597   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2598          "unexpected offset in global node");
2599
2600   // This also catched the large code model case for Darwin.
2601   if ((OpFlags & AArch64II::MO_GOT) != 0) {
2602     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2603     // FIXME: Once remat is capable of dealing with instructions with register
2604     // operands, expand this into two nodes instead of using a wrapper node.
2605     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2606   }
2607
2608   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2609     const unsigned char MO_NC = AArch64II::MO_NC;
2610     return DAG.getNode(
2611         AArch64ISD::WrapperLarge, DL, PtrVT,
2612         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
2613         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
2614         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
2615         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
2616   } else {
2617     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2618     // the only correct model on Darwin.
2619     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2620                                             OpFlags | AArch64II::MO_PAGE);
2621     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2622     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2623
2624     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2625     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2626   }
2627 }
2628
2629 /// \brief Convert a TLS address reference into the correct sequence of loads
2630 /// and calls to compute the variable's address (for Darwin, currently) and
2631 /// return an SDValue containing the final node.
2632
2633 /// Darwin only has one TLS scheme which must be capable of dealing with the
2634 /// fully general situation, in the worst case. This means:
2635 ///     + "extern __thread" declaration.
2636 ///     + Defined in a possibly unknown dynamic library.
2637 ///
2638 /// The general system is that each __thread variable has a [3 x i64] descriptor
2639 /// which contains information used by the runtime to calculate the address. The
2640 /// only part of this the compiler needs to know about is the first xword, which
2641 /// contains a function pointer that must be called with the address of the
2642 /// entire descriptor in "x0".
2643 ///
2644 /// Since this descriptor may be in a different unit, in general even the
2645 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2646 /// is:
2647 ///     adrp x0, _var@TLVPPAGE
2648 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
2649 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
2650 ///                                      ; the function pointer
2651 ///     blr x1                           ; Uses descriptor address in x0
2652 ///     ; Address of _var is now in x0.
2653 ///
2654 /// If the address of _var's descriptor *is* known to the linker, then it can
2655 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2656 /// a slight efficiency gain.
2657 SDValue
2658 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2659                                                    SelectionDAG &DAG) const {
2660   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2661
2662   SDLoc DL(Op);
2663   MVT PtrVT = getPointerTy();
2664   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2665
2666   SDValue TLVPAddr =
2667       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2668   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2669
2670   // The first entry in the descriptor is a function pointer that we must call
2671   // to obtain the address of the variable.
2672   SDValue Chain = DAG.getEntryNode();
2673   SDValue FuncTLVGet =
2674       DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2675                   false, true, true, 8);
2676   Chain = FuncTLVGet.getValue(1);
2677
2678   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2679   MFI->setAdjustsStack(true);
2680
2681   // TLS calls preserve all registers except those that absolutely must be
2682   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2683   // silly).
2684   const TargetRegisterInfo *TRI =
2685       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2686   const AArch64RegisterInfo *ARI =
2687       static_cast<const AArch64RegisterInfo *>(TRI);
2688   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2689
2690   // Finally, we can make the call. This is just a degenerate version of a
2691   // normal AArch64 call node: x0 takes the address of the descriptor, and
2692   // returns the address of the variable in this thread.
2693   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
2694   Chain =
2695       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2696                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
2697                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2698   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
2699 }
2700
2701 /// When accessing thread-local variables under either the general-dynamic or
2702 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2703 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2704 /// is a function pointer to carry out the resolution. This function takes the
2705 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2706 /// other registers (except LR, NZCV) are preserved.
2707 ///
2708 /// Thus, the ideal call sequence on AArch64 is:
2709 ///
2710 ///     adrp x0, :tlsdesc:thread_var
2711 ///     ldr x8, [x0, :tlsdesc_lo12:thread_var]
2712 ///     add x0, x0, :tlsdesc_lo12:thread_var
2713 ///     .tlsdesccall thread_var
2714 ///     blr x8
2715 ///     (TPIDR_EL0 offset now in x0).
2716 ///
2717 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2718 /// relocation to help the linker relax this sequence if it turns out to be too
2719 /// conservative.
2720 ///
2721 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2722 /// is harmless.
2723 SDValue AArch64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2724                                                    SDValue DescAddr, SDLoc DL,
2725                                                    SelectionDAG &DAG) const {
2726   EVT PtrVT = getPointerTy();
2727
2728   // The function we need to call is simply the first entry in the GOT for this
2729   // descriptor, load it in preparation.
2730   SDValue Func = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, SymAddr);
2731
2732   // TLS calls preserve all registers except those that absolutely must be
2733   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2734   // silly).
2735   const TargetRegisterInfo *TRI =
2736       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2737   const AArch64RegisterInfo *ARI =
2738       static_cast<const AArch64RegisterInfo *>(TRI);
2739   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2740
2741   // The function takes only one argument: the address of the descriptor itself
2742   // in X0.
2743   SDValue Glue, Chain;
2744   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2745   Glue = Chain.getValue(1);
2746
2747   // We're now ready to populate the argument list, as with a normal call:
2748   SmallVector<SDValue, 6> Ops;
2749   Ops.push_back(Chain);
2750   Ops.push_back(Func);
2751   Ops.push_back(SymAddr);
2752   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2753   Ops.push_back(DAG.getRegisterMask(Mask));
2754   Ops.push_back(Glue);
2755
2756   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2757   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2758   Glue = Chain.getValue(1);
2759
2760   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2761 }
2762
2763 SDValue
2764 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2765                                                 SelectionDAG &DAG) const {
2766   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2767   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2768          "ELF TLS only supported in small memory model");
2769   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2770
2771   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2772
2773   SDValue TPOff;
2774   EVT PtrVT = getPointerTy();
2775   SDLoc DL(Op);
2776   const GlobalValue *GV = GA->getGlobal();
2777
2778   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2779
2780   if (Model == TLSModel::LocalExec) {
2781     SDValue HiVar = DAG.getTargetGlobalAddress(
2782         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2783     SDValue LoVar = DAG.getTargetGlobalAddress(
2784         GV, DL, PtrVT, 0,
2785         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2786
2787     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2788                                        DAG.getTargetConstant(16, MVT::i32)),
2789                     0);
2790     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2791                                        DAG.getTargetConstant(0, MVT::i32)),
2792                     0);
2793   } else if (Model == TLSModel::InitialExec) {
2794     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2795     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
2796   } else if (Model == TLSModel::LocalDynamic) {
2797     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2798     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2799     // the beginning of the module's TLS region, followed by a DTPREL offset
2800     // calculation.
2801
2802     // These accesses will need deduplicating if there's more than one.
2803     AArch64FunctionInfo *MFI =
2804         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
2805     MFI->incNumLocalDynamicTLSAccesses();
2806
2807     // Accesses used in this sequence go via the TLS descriptor which lives in
2808     // the GOT. Prepare an address we can use to handle this.
2809     SDValue HiDesc = DAG.getTargetExternalSymbol(
2810         "_TLS_MODULE_BASE_", PtrVT, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2811     SDValue LoDesc = DAG.getTargetExternalSymbol(
2812         "_TLS_MODULE_BASE_", PtrVT,
2813         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2814
2815     // First argument to the descriptor call is the address of the descriptor
2816     // itself.
2817     SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2818     DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2819
2820     // The call needs a relocation too for linker relaxation. It doesn't make
2821     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2822     // the address.
2823     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2824                                                   AArch64II::MO_TLS);
2825
2826     // Now we can calculate the offset from TPIDR_EL0 to this module's
2827     // thread-local area.
2828     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2829
2830     // Now use :dtprel_whatever: operations to calculate this variable's offset
2831     // in its thread-storage area.
2832     SDValue HiVar = DAG.getTargetGlobalAddress(
2833         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2834     SDValue LoVar = DAG.getTargetGlobalAddress(
2835         GV, DL, MVT::i64, 0,
2836         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2837
2838     SDValue DTPOff =
2839         SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2840                                    DAG.getTargetConstant(16, MVT::i32)),
2841                 0);
2842     DTPOff =
2843         SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2844                                    DAG.getTargetConstant(0, MVT::i32)),
2845                 0);
2846
2847     TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2848   } else if (Model == TLSModel::GeneralDynamic) {
2849     // Accesses used in this sequence go via the TLS descriptor which lives in
2850     // the GOT. Prepare an address we can use to handle this.
2851     SDValue HiDesc = DAG.getTargetGlobalAddress(
2852         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2853     SDValue LoDesc = DAG.getTargetGlobalAddress(
2854         GV, DL, PtrVT, 0,
2855         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2856
2857     // First argument to the descriptor call is the address of the descriptor
2858     // itself.
2859     SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2860     DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2861
2862     // The call needs a relocation too for linker relaxation. It doesn't make
2863     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2864     // the address.
2865     SDValue SymAddr =
2866         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2867
2868     // Finally we can make a call to calculate the offset from tpidr_el0.
2869     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2870   } else
2871     llvm_unreachable("Unsupported ELF TLS access model");
2872
2873   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2874 }
2875
2876 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2877                                                      SelectionDAG &DAG) const {
2878   if (Subtarget->isTargetDarwin())
2879     return LowerDarwinGlobalTLSAddress(Op, DAG);
2880   else if (Subtarget->isTargetELF())
2881     return LowerELFGlobalTLSAddress(Op, DAG);
2882
2883   llvm_unreachable("Unexpected platform trying to use TLS");
2884 }
2885 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2886   SDValue Chain = Op.getOperand(0);
2887   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2888   SDValue LHS = Op.getOperand(2);
2889   SDValue RHS = Op.getOperand(3);
2890   SDValue Dest = Op.getOperand(4);
2891   SDLoc dl(Op);
2892
2893   // Handle f128 first, since lowering it will result in comparing the return
2894   // value of a libcall against zero, which is just what the rest of LowerBR_CC
2895   // is expecting to deal with.
2896   if (LHS.getValueType() == MVT::f128) {
2897     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2898
2899     // If softenSetCCOperands returned a scalar, we need to compare the result
2900     // against zero to select between true and false values.
2901     if (!RHS.getNode()) {
2902       RHS = DAG.getConstant(0, LHS.getValueType());
2903       CC = ISD::SETNE;
2904     }
2905   }
2906
2907   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2908   // instruction.
2909   unsigned Opc = LHS.getOpcode();
2910   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2911       cast<ConstantSDNode>(RHS)->isOne() &&
2912       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2913        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2914     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2915            "Unexpected condition code.");
2916     // Only lower legal XALUO ops.
2917     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2918       return SDValue();
2919
2920     // The actual operation with overflow check.
2921     AArch64CC::CondCode OFCC;
2922     SDValue Value, Overflow;
2923     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
2924
2925     if (CC == ISD::SETNE)
2926       OFCC = getInvertedCondCode(OFCC);
2927     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2928
2929     return DAG.getNode(AArch64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2930                        CCVal, Overflow);
2931   }
2932
2933   if (LHS.getValueType().isInteger()) {
2934     assert((LHS.getValueType() == RHS.getValueType()) &&
2935            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2936
2937     // If the RHS of the comparison is zero, we can potentially fold this
2938     // to a specialized branch.
2939     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2940     if (RHSC && RHSC->getZExtValue() == 0) {
2941       if (CC == ISD::SETEQ) {
2942         // See if we can use a TBZ to fold in an AND as well.
2943         // TBZ has a smaller branch displacement than CBZ.  If the offset is
2944         // out of bounds, a late MI-layer pass rewrites branches.
2945         // 403.gcc is an example that hits this case.
2946         if (LHS.getOpcode() == ISD::AND &&
2947             isa<ConstantSDNode>(LHS.getOperand(1)) &&
2948             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2949           SDValue Test = LHS.getOperand(0);
2950           uint64_t Mask = LHS.getConstantOperandVal(1);
2951           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
2952                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2953         }
2954
2955         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2956       } else if (CC == ISD::SETNE) {
2957         // See if we can use a TBZ to fold in an AND as well.
2958         // TBZ has a smaller branch displacement than CBZ.  If the offset is
2959         // out of bounds, a late MI-layer pass rewrites branches.
2960         // 403.gcc is an example that hits this case.
2961         if (LHS.getOpcode() == ISD::AND &&
2962             isa<ConstantSDNode>(LHS.getOperand(1)) &&
2963             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2964           SDValue Test = LHS.getOperand(0);
2965           uint64_t Mask = LHS.getConstantOperandVal(1);
2966           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2967                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2968         }
2969
2970         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2971       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
2972         // Don't combine AND since emitComparison converts the AND to an ANDS
2973         // (a.k.a. TST) and the test in the test bit and branch instruction
2974         // becomes redundant.  This would also increase register pressure.
2975         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2976         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
2977                            DAG.getConstant(Mask, MVT::i64), Dest);
2978       }
2979     }
2980     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
2981         LHS.getOpcode() != ISD::AND) {
2982       // Don't combine AND since emitComparison converts the AND to an ANDS
2983       // (a.k.a. TST) and the test in the test bit and branch instruction
2984       // becomes redundant.  This would also increase register pressure.
2985       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2986       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
2987                          DAG.getConstant(Mask, MVT::i64), Dest);
2988     }
2989
2990     SDValue CCVal;
2991     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2992     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2993                        Cmp);
2994   }
2995
2996   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2997
2998   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
2999   // clean.  Some of them require two branches to implement.
3000   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3001   AArch64CC::CondCode CC1, CC2;
3002   changeFPCCToAArch64CC(CC, CC1, CC2);
3003   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3004   SDValue BR1 =
3005       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3006   if (CC2 != AArch64CC::AL) {
3007     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3008     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3009                        Cmp);
3010   }
3011
3012   return BR1;
3013 }
3014
3015 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3016                                               SelectionDAG &DAG) const {
3017   EVT VT = Op.getValueType();
3018   SDLoc DL(Op);
3019
3020   SDValue In1 = Op.getOperand(0);
3021   SDValue In2 = Op.getOperand(1);
3022   EVT SrcVT = In2.getValueType();
3023   if (SrcVT != VT) {
3024     if (SrcVT == MVT::f32 && VT == MVT::f64)
3025       In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3026     else if (SrcVT == MVT::f64 && VT == MVT::f32)
3027       In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3028     else
3029       // FIXME: Src type is different, bail out for now. Can VT really be a
3030       // vector type?
3031       return SDValue();
3032   }
3033
3034   EVT VecVT;
3035   EVT EltVT;
3036   SDValue EltMask, VecVal1, VecVal2;
3037   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3038     EltVT = MVT::i32;
3039     VecVT = MVT::v4i32;
3040     EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3041
3042     if (!VT.isVector()) {
3043       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3044                                           DAG.getUNDEF(VecVT), In1);
3045       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3046                                           DAG.getUNDEF(VecVT), In2);
3047     } else {
3048       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3049       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3050     }
3051   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3052     EltVT = MVT::i64;
3053     VecVT = MVT::v2i64;
3054
3055     // We want to materialize a mask with the the high bit set, but the AdvSIMD
3056     // immediate moves cannot materialize that in a single instruction for
3057     // 64-bit elements. Instead, materialize zero and then negate it.
3058     EltMask = DAG.getConstant(0, EltVT);
3059
3060     if (!VT.isVector()) {
3061       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3062                                           DAG.getUNDEF(VecVT), In1);
3063       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3064                                           DAG.getUNDEF(VecVT), In2);
3065     } else {
3066       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3067       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3068     }
3069   } else {
3070     llvm_unreachable("Invalid type for copysign!");
3071   }
3072
3073   std::vector<SDValue> BuildVectorOps;
3074   for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3075     BuildVectorOps.push_back(EltMask);
3076
3077   SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
3078
3079   // If we couldn't materialize the mask above, then the mask vector will be
3080   // the zero vector, and we need to negate it here.
3081   if (VT == MVT::f64 || VT == MVT::v2f64) {
3082     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3083     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3084     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3085   }
3086
3087   SDValue Sel =
3088       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3089
3090   if (VT == MVT::f32)
3091     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3092   else if (VT == MVT::f64)
3093     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3094   else
3095     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3096 }
3097
3098 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3099   if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3100           AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3101     return SDValue();
3102
3103   // While there is no integer popcount instruction, it can
3104   // be more efficiently lowered to the following sequence that uses
3105   // AdvSIMD registers/instructions as long as the copies to/from
3106   // the AdvSIMD registers are cheap.
3107   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3108   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3109   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3110   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3111   SDValue Val = Op.getOperand(0);
3112   SDLoc DL(Op);
3113   EVT VT = Op.getValueType();
3114   SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3115
3116   SDValue VecVal;
3117   if (VT == MVT::i32) {
3118     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3119     VecVal = DAG.getTargetInsertSubreg(AArch64::ssub, DL, MVT::v8i8, ZeroVec,
3120                                        VecVal);
3121   } else {
3122     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3123   }
3124
3125   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3126   SDValue UaddLV = DAG.getNode(
3127       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3128       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, MVT::i32), CtPop);
3129
3130   if (VT == MVT::i64)
3131     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3132   return UaddLV;
3133 }
3134
3135 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3136
3137   if (Op.getValueType().isVector())
3138     return LowerVSETCC(Op, DAG);
3139
3140   SDValue LHS = Op.getOperand(0);
3141   SDValue RHS = Op.getOperand(1);
3142   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3143   SDLoc dl(Op);
3144
3145   // We chose ZeroOrOneBooleanContents, so use zero and one.
3146   EVT VT = Op.getValueType();
3147   SDValue TVal = DAG.getConstant(1, VT);
3148   SDValue FVal = DAG.getConstant(0, VT);
3149
3150   // Handle f128 first, since one possible outcome is a normal integer
3151   // comparison which gets picked up by the next if statement.
3152   if (LHS.getValueType() == MVT::f128) {
3153     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3154
3155     // If softenSetCCOperands returned a scalar, use it.
3156     if (!RHS.getNode()) {
3157       assert(LHS.getValueType() == Op.getValueType() &&
3158              "Unexpected setcc expansion!");
3159       return LHS;
3160     }
3161   }
3162
3163   if (LHS.getValueType().isInteger()) {
3164     SDValue CCVal;
3165     SDValue Cmp =
3166         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3167
3168     // Note that we inverted the condition above, so we reverse the order of
3169     // the true and false operands here.  This will allow the setcc to be
3170     // matched to a single CSINC instruction.
3171     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3172   }
3173
3174   // Now we know we're dealing with FP values.
3175   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3176
3177   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3178   // and do the comparison.
3179   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3180
3181   AArch64CC::CondCode CC1, CC2;
3182   changeFPCCToAArch64CC(CC, CC1, CC2);
3183   if (CC2 == AArch64CC::AL) {
3184     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3185     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3186
3187     // Note that we inverted the condition above, so we reverse the order of
3188     // the true and false operands here.  This will allow the setcc to be
3189     // matched to a single CSINC instruction.
3190     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3191   } else {
3192     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3193     // totally clean.  Some of them require two CSELs to implement.  As is in
3194     // this case, we emit the first CSEL and then emit a second using the output
3195     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3196
3197     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3198     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3199     SDValue CS1 =
3200         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3201
3202     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3203     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3204   }
3205 }
3206
3207 /// A SELECT_CC operation is really some kind of max or min if both values being
3208 /// compared are, in some sense, equal to the results in either case. However,
3209 /// it is permissible to compare f32 values and produce directly extended f64
3210 /// values.
3211 ///
3212 /// Extending the comparison operands would also be allowed, but is less likely
3213 /// to happen in practice since their use is right here. Note that truncate
3214 /// operations would *not* be semantically equivalent.
3215 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3216   if (Cmp == Result)
3217     return true;
3218
3219   ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3220   ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3221   if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3222       Result.getValueType() == MVT::f64) {
3223     bool Lossy;
3224     APFloat CmpVal = CCmp->getValueAPF();
3225     CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3226     return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3227   }
3228
3229   return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3230 }
3231
3232 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3233                                            SelectionDAG &DAG) const {
3234   SDValue CC = Op->getOperand(0);
3235   SDValue TVal = Op->getOperand(1);
3236   SDValue FVal = Op->getOperand(2);
3237   SDLoc DL(Op);
3238
3239   unsigned Opc = CC.getOpcode();
3240   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3241   // instruction.
3242   if (CC.getResNo() == 1 &&
3243       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3244        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3245     // Only lower legal XALUO ops.
3246     if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3247       return SDValue();
3248
3249     AArch64CC::CondCode OFCC;
3250     SDValue Value, Overflow;
3251     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CC.getValue(0), DAG);
3252     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3253
3254     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3255                        CCVal, Overflow);
3256   }
3257
3258   if (CC.getOpcode() == ISD::SETCC)
3259     return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3260                            cast<CondCodeSDNode>(CC.getOperand(2))->get());
3261   else
3262     return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3263                            FVal, ISD::SETNE);
3264 }
3265
3266 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3267                                               SelectionDAG &DAG) const {
3268   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3269   SDValue LHS = Op.getOperand(0);
3270   SDValue RHS = Op.getOperand(1);
3271   SDValue TVal = Op.getOperand(2);
3272   SDValue FVal = Op.getOperand(3);
3273   SDLoc dl(Op);
3274
3275   // Handle f128 first, because it will result in a comparison of some RTLIB
3276   // call result against zero.
3277   if (LHS.getValueType() == MVT::f128) {
3278     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3279
3280     // If softenSetCCOperands returned a scalar, we need to compare the result
3281     // against zero to select between true and false values.
3282     if (!RHS.getNode()) {
3283       RHS = DAG.getConstant(0, LHS.getValueType());
3284       CC = ISD::SETNE;
3285     }
3286   }
3287
3288   // Handle integers first.
3289   if (LHS.getValueType().isInteger()) {
3290     assert((LHS.getValueType() == RHS.getValueType()) &&
3291            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3292
3293     unsigned Opcode = AArch64ISD::CSEL;
3294
3295     // If both the TVal and the FVal are constants, see if we can swap them in
3296     // order to for a CSINV or CSINC out of them.
3297     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3298     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3299
3300     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3301       std::swap(TVal, FVal);
3302       std::swap(CTVal, CFVal);
3303       CC = ISD::getSetCCInverse(CC, true);
3304     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3305       std::swap(TVal, FVal);
3306       std::swap(CTVal, CFVal);
3307       CC = ISD::getSetCCInverse(CC, true);
3308     } else if (TVal.getOpcode() == ISD::XOR) {
3309       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3310       // with a CSINV rather than a CSEL.
3311       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3312
3313       if (CVal && CVal->isAllOnesValue()) {
3314         std::swap(TVal, FVal);
3315         std::swap(CTVal, CFVal);
3316         CC = ISD::getSetCCInverse(CC, true);
3317       }
3318     } else if (TVal.getOpcode() == ISD::SUB) {
3319       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3320       // that we can match with a CSNEG rather than a CSEL.
3321       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3322
3323       if (CVal && CVal->isNullValue()) {
3324         std::swap(TVal, FVal);
3325         std::swap(CTVal, CFVal);
3326         CC = ISD::getSetCCInverse(CC, true);
3327       }
3328     } else if (CTVal && CFVal) {
3329       const int64_t TrueVal = CTVal->getSExtValue();
3330       const int64_t FalseVal = CFVal->getSExtValue();
3331       bool Swap = false;
3332
3333       // If both TVal and FVal are constants, see if FVal is the
3334       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3335       // instead of a CSEL in that case.
3336       if (TrueVal == ~FalseVal) {
3337         Opcode = AArch64ISD::CSINV;
3338       } else if (TrueVal == -FalseVal) {
3339         Opcode = AArch64ISD::CSNEG;
3340       } else if (TVal.getValueType() == MVT::i32) {
3341         // If our operands are only 32-bit wide, make sure we use 32-bit
3342         // arithmetic for the check whether we can use CSINC. This ensures that
3343         // the addition in the check will wrap around properly in case there is
3344         // an overflow (which would not be the case if we do the check with
3345         // 64-bit arithmetic).
3346         const uint32_t TrueVal32 = CTVal->getZExtValue();
3347         const uint32_t FalseVal32 = CFVal->getZExtValue();
3348
3349         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3350           Opcode = AArch64ISD::CSINC;
3351
3352           if (TrueVal32 > FalseVal32) {
3353             Swap = true;
3354           }
3355         }
3356         // 64-bit check whether we can use CSINC.
3357       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3358         Opcode = AArch64ISD::CSINC;
3359
3360         if (TrueVal > FalseVal) {
3361           Swap = true;
3362         }
3363       }
3364
3365       // Swap TVal and FVal if necessary.
3366       if (Swap) {
3367         std::swap(TVal, FVal);
3368         std::swap(CTVal, CFVal);
3369         CC = ISD::getSetCCInverse(CC, true);
3370       }
3371
3372       if (Opcode != AArch64ISD::CSEL) {
3373         // Drop FVal since we can get its value by simply inverting/negating
3374         // TVal.
3375         FVal = TVal;
3376       }
3377     }
3378
3379     SDValue CCVal;
3380     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3381
3382     EVT VT = Op.getValueType();
3383     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3384   }
3385
3386   // Now we know we're dealing with FP values.
3387   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3388   assert(LHS.getValueType() == RHS.getValueType());
3389   EVT VT = Op.getValueType();
3390
3391   // Try to match this select into a max/min operation, which have dedicated
3392   // opcode in the instruction set.
3393   // FIXME: This is not correct in the presence of NaNs, so we only enable this
3394   // in no-NaNs mode.
3395   if (getTargetMachine().Options.NoNaNsFPMath) {
3396     SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3397     if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3398         selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3399       CC = ISD::getSetCCSwappedOperands(CC);
3400       std::swap(MinMaxLHS, MinMaxRHS);
3401     }
3402
3403     if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3404         selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3405       switch (CC) {
3406       default:
3407         break;
3408       case ISD::SETGT:
3409       case ISD::SETGE:
3410       case ISD::SETUGT:
3411       case ISD::SETUGE:
3412       case ISD::SETOGT:
3413       case ISD::SETOGE:
3414         return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3415         break;
3416       case ISD::SETLT:
3417       case ISD::SETLE:
3418       case ISD::SETULT:
3419       case ISD::SETULE:
3420       case ISD::SETOLT:
3421       case ISD::SETOLE:
3422         return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3423         break;
3424       }
3425     }
3426   }
3427
3428   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3429   // and do the comparison.
3430   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3431
3432   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3433   // clean.  Some of them require two CSELs to implement.
3434   AArch64CC::CondCode CC1, CC2;
3435   changeFPCCToAArch64CC(CC, CC1, CC2);
3436   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3437   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3438
3439   // If we need a second CSEL, emit it, using the output of the first as the
3440   // RHS.  We're effectively OR'ing the two CC's together.
3441   if (CC2 != AArch64CC::AL) {
3442     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3443     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3444   }
3445
3446   // Otherwise, return the output of the first CSEL.
3447   return CS1;
3448 }
3449
3450 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3451                                               SelectionDAG &DAG) const {
3452   // Jump table entries as PC relative offsets. No additional tweaking
3453   // is necessary here. Just get the address of the jump table.
3454   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3455   EVT PtrVT = getPointerTy();
3456   SDLoc DL(Op);
3457
3458   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3459       !Subtarget->isTargetMachO()) {
3460     const unsigned char MO_NC = AArch64II::MO_NC;
3461     return DAG.getNode(
3462         AArch64ISD::WrapperLarge, DL, PtrVT,
3463         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3464         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3465         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3466         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3467                                AArch64II::MO_G0 | MO_NC));
3468   }
3469
3470   SDValue Hi =
3471       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3472   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3473                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3474   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3475   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3476 }
3477
3478 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3479                                                  SelectionDAG &DAG) const {
3480   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3481   EVT PtrVT = getPointerTy();
3482   SDLoc DL(Op);
3483
3484   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3485     // Use the GOT for the large code model on iOS.
3486     if (Subtarget->isTargetMachO()) {
3487       SDValue GotAddr = DAG.getTargetConstantPool(
3488           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3489           AArch64II::MO_GOT);
3490       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3491     }
3492
3493     const unsigned char MO_NC = AArch64II::MO_NC;
3494     return DAG.getNode(
3495         AArch64ISD::WrapperLarge, DL, PtrVT,
3496         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3497                                   CP->getOffset(), AArch64II::MO_G3),
3498         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3499                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3500         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3501                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3502         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3503                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3504   } else {
3505     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3506     // ELF, the only valid one on Darwin.
3507     SDValue Hi =
3508         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3509                                   CP->getOffset(), AArch64II::MO_PAGE);
3510     SDValue Lo = DAG.getTargetConstantPool(
3511         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3512         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3513
3514     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3515     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3516   }
3517 }
3518
3519 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3520                                                SelectionDAG &DAG) const {
3521   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3522   EVT PtrVT = getPointerTy();
3523   SDLoc DL(Op);
3524   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3525       !Subtarget->isTargetMachO()) {
3526     const unsigned char MO_NC = AArch64II::MO_NC;
3527     return DAG.getNode(
3528         AArch64ISD::WrapperLarge, DL, PtrVT,
3529         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3530         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3531         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3532         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3533   } else {
3534     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3535     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3536                                                              AArch64II::MO_NC);
3537     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3538     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3539   }
3540 }
3541
3542 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3543                                                  SelectionDAG &DAG) const {
3544   AArch64FunctionInfo *FuncInfo =
3545       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3546
3547   SDLoc DL(Op);
3548   SDValue FR =
3549       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3550   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3551   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3552                       MachinePointerInfo(SV), false, false, 0);
3553 }
3554
3555 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3556                                                 SelectionDAG &DAG) const {
3557   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3558   // Standard, section B.3.
3559   MachineFunction &MF = DAG.getMachineFunction();
3560   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3561   SDLoc DL(Op);
3562
3563   SDValue Chain = Op.getOperand(0);
3564   SDValue VAList = Op.getOperand(1);
3565   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3566   SmallVector<SDValue, 4> MemOps;
3567
3568   // void *__stack at offset 0
3569   SDValue Stack =
3570       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3571   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3572                                 MachinePointerInfo(SV), false, false, 8));
3573
3574   // void *__gr_top at offset 8
3575   int GPRSize = FuncInfo->getVarArgsGPRSize();
3576   if (GPRSize > 0) {
3577     SDValue GRTop, GRTopAddr;
3578
3579     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3580                             DAG.getConstant(8, getPointerTy()));
3581
3582     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3583     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3584                         DAG.getConstant(GPRSize, getPointerTy()));
3585
3586     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3587                                   MachinePointerInfo(SV, 8), false, false, 8));
3588   }
3589
3590   // void *__vr_top at offset 16
3591   int FPRSize = FuncInfo->getVarArgsFPRSize();
3592   if (FPRSize > 0) {
3593     SDValue VRTop, VRTopAddr;
3594     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3595                             DAG.getConstant(16, getPointerTy()));
3596
3597     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3598     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3599                         DAG.getConstant(FPRSize, getPointerTy()));
3600
3601     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3602                                   MachinePointerInfo(SV, 16), false, false, 8));
3603   }
3604
3605   // int __gr_offs at offset 24
3606   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3607                                    DAG.getConstant(24, getPointerTy()));
3608   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3609                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
3610                                 false, 4));
3611
3612   // int __vr_offs at offset 28
3613   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3614                                    DAG.getConstant(28, getPointerTy()));
3615   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3616                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
3617                                 false, 4));
3618
3619   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3620 }
3621
3622 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3623                                             SelectionDAG &DAG) const {
3624   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3625                                      : LowerAAPCS_VASTART(Op, DAG);
3626 }
3627
3628 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3629                                            SelectionDAG &DAG) const {
3630   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3631   // pointer.
3632   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3633   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3634   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3635
3636   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3637                        Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3638                        8, false, false, MachinePointerInfo(DestSV),
3639                        MachinePointerInfo(SrcSV));
3640 }
3641
3642 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3643   assert(Subtarget->isTargetDarwin() &&
3644          "automatic va_arg instruction only works on Darwin");
3645
3646   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3647   EVT VT = Op.getValueType();
3648   SDLoc DL(Op);
3649   SDValue Chain = Op.getOperand(0);
3650   SDValue Addr = Op.getOperand(1);
3651   unsigned Align = Op.getConstantOperandVal(3);
3652
3653   SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3654                                MachinePointerInfo(V), false, false, false, 0);
3655   Chain = VAList.getValue(1);
3656
3657   if (Align > 8) {
3658     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3659     VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3660                          DAG.getConstant(Align - 1, getPointerTy()));
3661     VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3662                          DAG.getConstant(-(int64_t)Align, getPointerTy()));
3663   }
3664
3665   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3666   uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3667
3668   // Scalar integer and FP values smaller than 64 bits are implicitly extended
3669   // up to 64 bits.  At the very least, we have to increase the striding of the
3670   // vaargs list to match this, and for FP values we need to introduce
3671   // FP_ROUND nodes as well.
3672   if (VT.isInteger() && !VT.isVector())
3673     ArgSize = 8;
3674   bool NeedFPTrunc = false;
3675   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3676     ArgSize = 8;
3677     NeedFPTrunc = true;
3678   }
3679
3680   // Increment the pointer, VAList, to the next vaarg
3681   SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3682                                DAG.getConstant(ArgSize, getPointerTy()));
3683   // Store the incremented VAList to the legalized pointer
3684   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3685                                  false, false, 0);
3686
3687   // Load the actual argument out of the pointer VAList
3688   if (NeedFPTrunc) {
3689     // Load the value as an f64.
3690     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3691                                  MachinePointerInfo(), false, false, false, 0);
3692     // Round the value down to an f32.
3693     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3694                                    DAG.getIntPtrConstant(1));
3695     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3696     // Merge the rounded value with the chain output of the load.
3697     return DAG.getMergeValues(Ops, DL);
3698   }
3699
3700   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3701                      false, false, 0);
3702 }
3703
3704 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
3705                                               SelectionDAG &DAG) const {
3706   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3707   MFI->setFrameAddressIsTaken(true);
3708
3709   EVT VT = Op.getValueType();
3710   SDLoc DL(Op);
3711   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3712   SDValue FrameAddr =
3713       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
3714   while (Depth--)
3715     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3716                             MachinePointerInfo(), false, false, false, 0);
3717   return FrameAddr;
3718 }
3719
3720 // FIXME? Maybe this could be a TableGen attribute on some registers and
3721 // this table could be generated automatically from RegInfo.
3722 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
3723                                                   EVT VT) const {
3724   unsigned Reg = StringSwitch<unsigned>(RegName)
3725                        .Case("sp", AArch64::SP)
3726                        .Default(0);
3727   if (Reg)
3728     return Reg;
3729   report_fatal_error("Invalid register name global variable");
3730 }
3731
3732 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
3733                                                SelectionDAG &DAG) const {
3734   MachineFunction &MF = DAG.getMachineFunction();
3735   MachineFrameInfo *MFI = MF.getFrameInfo();
3736   MFI->setReturnAddressIsTaken(true);
3737
3738   EVT VT = Op.getValueType();
3739   SDLoc DL(Op);
3740   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3741   if (Depth) {
3742     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3743     SDValue Offset = DAG.getConstant(8, getPointerTy());
3744     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3745                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3746                        MachinePointerInfo(), false, false, false, 0);
3747   }
3748
3749   // Return LR, which contains the return address. Mark it an implicit live-in.
3750   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
3751   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3752 }
3753
3754 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3755 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3756 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
3757                                                     SelectionDAG &DAG) const {
3758   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3759   EVT VT = Op.getValueType();
3760   unsigned VTBits = VT.getSizeInBits();
3761   SDLoc dl(Op);
3762   SDValue ShOpLo = Op.getOperand(0);
3763   SDValue ShOpHi = Op.getOperand(1);
3764   SDValue ShAmt = Op.getOperand(2);
3765   SDValue ARMcc;
3766   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3767
3768   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3769
3770   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3771                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3772   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3773   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3774                                    DAG.getConstant(VTBits, MVT::i64));
3775   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3776
3777   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3778                                ISD::SETGE, dl, DAG);
3779   SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3780
3781   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3782   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3783   SDValue Lo =
3784       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3785
3786   // AArch64 shifts larger than the register width are wrapped rather than
3787   // clamped, so we can't just emit "hi >> x".
3788   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3789   SDValue TrueValHi = Opc == ISD::SRA
3790                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
3791                                         DAG.getConstant(VTBits - 1, MVT::i64))
3792                           : DAG.getConstant(0, VT);
3793   SDValue Hi =
3794       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3795
3796   SDValue Ops[2] = { Lo, Hi };
3797   return DAG.getMergeValues(Ops, dl);
3798 }
3799
3800 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3801 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3802 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
3803                                                  SelectionDAG &DAG) const {
3804   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3805   EVT VT = Op.getValueType();
3806   unsigned VTBits = VT.getSizeInBits();
3807   SDLoc dl(Op);
3808   SDValue ShOpLo = Op.getOperand(0);
3809   SDValue ShOpHi = Op.getOperand(1);
3810   SDValue ShAmt = Op.getOperand(2);
3811   SDValue ARMcc;
3812
3813   assert(Op.getOpcode() == ISD::SHL_PARTS);
3814   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3815                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3816   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3817   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3818                                    DAG.getConstant(VTBits, MVT::i64));
3819   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3820   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3821
3822   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3823
3824   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3825                                ISD::SETGE, dl, DAG);
3826   SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3827   SDValue Hi =
3828       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3829
3830   // AArch64 shifts of larger than register sizes are wrapped rather than
3831   // clamped, so we can't just emit "lo << a" if a is too big.
3832   SDValue TrueValLo = DAG.getConstant(0, VT);
3833   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3834   SDValue Lo =
3835       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3836
3837   SDValue Ops[2] = { Lo, Hi };
3838   return DAG.getMergeValues(Ops, dl);
3839 }
3840
3841 bool AArch64TargetLowering::isOffsetFoldingLegal(
3842     const GlobalAddressSDNode *GA) const {
3843   // The AArch64 target doesn't support folding offsets into global addresses.
3844   return false;
3845 }
3846
3847 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3848   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3849   // FIXME: We should be able to handle f128 as well with a clever lowering.
3850   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3851     return true;
3852
3853   if (VT == MVT::f64)
3854     return AArch64_AM::getFP64Imm(Imm) != -1;
3855   else if (VT == MVT::f32)
3856     return AArch64_AM::getFP32Imm(Imm) != -1;
3857   return false;
3858 }
3859
3860 //===----------------------------------------------------------------------===//
3861 //                          AArch64 Optimization Hooks
3862 //===----------------------------------------------------------------------===//
3863
3864 //===----------------------------------------------------------------------===//
3865 //                          AArch64 Inline Assembly Support
3866 //===----------------------------------------------------------------------===//
3867
3868 // Table of Constraints
3869 // TODO: This is the current set of constraints supported by ARM for the
3870 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3871 //
3872 // r - A general register
3873 // w - An FP/SIMD register of some size in the range v0-v31
3874 // x - An FP/SIMD register of some size in the range v0-v15
3875 // I - Constant that can be used with an ADD instruction
3876 // J - Constant that can be used with a SUB instruction
3877 // K - Constant that can be used with a 32-bit logical instruction
3878 // L - Constant that can be used with a 64-bit logical instruction
3879 // M - Constant that can be used as a 32-bit MOV immediate
3880 // N - Constant that can be used as a 64-bit MOV immediate
3881 // Q - A memory reference with base register and no offset
3882 // S - A symbolic address
3883 // Y - Floating point constant zero
3884 // Z - Integer constant zero
3885 //
3886 //   Note that general register operands will be output using their 64-bit x
3887 // register name, whatever the size of the variable, unless the asm operand
3888 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3889 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3890 // %q modifier.
3891
3892 /// getConstraintType - Given a constraint letter, return the type of
3893 /// constraint it is for this target.
3894 AArch64TargetLowering::ConstraintType
3895 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3896   if (Constraint.size() == 1) {
3897     switch (Constraint[0]) {
3898     default:
3899       break;
3900     case 'z':
3901       return C_Other;
3902     case 'x':
3903     case 'w':
3904       return C_RegisterClass;
3905     // An address with a single base register. Due to the way we
3906     // currently handle addresses it is the same as 'r'.
3907     case 'Q':
3908       return C_Memory;
3909     }
3910   }
3911   return TargetLowering::getConstraintType(Constraint);
3912 }
3913
3914 /// Examine constraint type and operand type and determine a weight value.
3915 /// This object must already have been set up with the operand type
3916 /// and the current alternative constraint selected.
3917 TargetLowering::ConstraintWeight
3918 AArch64TargetLowering::getSingleConstraintMatchWeight(
3919     AsmOperandInfo &info, const char *constraint) const {
3920   ConstraintWeight weight = CW_Invalid;
3921   Value *CallOperandVal = info.CallOperandVal;
3922   // If we don't have a value, we can't do a match,
3923   // but allow it at the lowest weight.
3924   if (!CallOperandVal)
3925     return CW_Default;
3926   Type *type = CallOperandVal->getType();
3927   // Look at the constraint type.
3928   switch (*constraint) {
3929   default:
3930     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3931     break;
3932   case 'x':
3933   case 'w':
3934     if (type->isFloatingPointTy() || type->isVectorTy())
3935       weight = CW_Register;
3936     break;
3937   case 'z':
3938     weight = CW_Constant;
3939     break;
3940   }
3941   return weight;
3942 }
3943
3944 std::pair<unsigned, const TargetRegisterClass *>
3945 AArch64TargetLowering::getRegForInlineAsmConstraint(
3946     const std::string &Constraint, MVT VT) const {
3947   if (Constraint.size() == 1) {
3948     switch (Constraint[0]) {
3949     case 'r':
3950       if (VT.getSizeInBits() == 64)
3951         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
3952       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
3953     case 'w':
3954       if (VT == MVT::f32)
3955         return std::make_pair(0U, &AArch64::FPR32RegClass);
3956       if (VT.getSizeInBits() == 64)
3957         return std::make_pair(0U, &AArch64::FPR64RegClass);
3958       if (VT.getSizeInBits() == 128)
3959         return std::make_pair(0U, &AArch64::FPR128RegClass);
3960       break;
3961     // The instructions that this constraint is designed for can
3962     // only take 128-bit registers so just use that regclass.
3963     case 'x':
3964       if (VT.getSizeInBits() == 128)
3965         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
3966       break;
3967     }
3968   }
3969   if (StringRef("{cc}").equals_lower(Constraint))
3970     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
3971
3972   // Use the default implementation in TargetLowering to convert the register
3973   // constraint into a member of a register class.
3974   std::pair<unsigned, const TargetRegisterClass *> Res;
3975   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3976
3977   // Not found as a standard register?
3978   if (!Res.second) {
3979     unsigned Size = Constraint.size();
3980     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3981         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3982       const std::string Reg =
3983           std::string(&Constraint[2], &Constraint[Size - 1]);
3984       int RegNo = atoi(Reg.c_str());
3985       if (RegNo >= 0 && RegNo <= 31) {
3986         // v0 - v31 are aliases of q0 - q31.
3987         // By default we'll emit v0-v31 for this unless there's a modifier where
3988         // we'll emit the correct register as well.
3989         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
3990         Res.second = &AArch64::FPR128RegClass;
3991       }
3992     }
3993   }
3994
3995   return Res;
3996 }
3997
3998 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3999 /// vector.  If it is invalid, don't add anything to Ops.
4000 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4001     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4002     SelectionDAG &DAG) const {
4003   SDValue Result;
4004
4005   // Currently only support length 1 constraints.
4006   if (Constraint.length() != 1)
4007     return;
4008
4009   char ConstraintLetter = Constraint[0];
4010   switch (ConstraintLetter) {
4011   default:
4012     break;
4013
4014   // This set of constraints deal with valid constants for various instructions.
4015   // Validate and return a target constant for them if we can.
4016   case 'z': {
4017     // 'z' maps to xzr or wzr so it needs an input of 0.
4018     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4019     if (!C || C->getZExtValue() != 0)
4020       return;
4021
4022     if (Op.getValueType() == MVT::i64)
4023       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4024     else
4025       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4026     break;
4027   }
4028
4029   case 'I':
4030   case 'J':
4031   case 'K':
4032   case 'L':
4033   case 'M':
4034   case 'N':
4035     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4036     if (!C)
4037       return;
4038
4039     // Grab the value and do some validation.
4040     uint64_t CVal = C->getZExtValue();
4041     switch (ConstraintLetter) {
4042     // The I constraint applies only to simple ADD or SUB immediate operands:
4043     // i.e. 0 to 4095 with optional shift by 12
4044     // The J constraint applies only to ADD or SUB immediates that would be
4045     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4046     // instruction [or vice versa], in other words -1 to -4095 with optional
4047     // left shift by 12.
4048     case 'I':
4049       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4050         break;
4051       return;
4052     case 'J': {
4053       uint64_t NVal = -C->getSExtValue();
4054       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4055         CVal = C->getSExtValue();
4056         break;
4057       }
4058       return;
4059     }
4060     // The K and L constraints apply *only* to logical immediates, including
4061     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4062     // been removed and MOV should be used). So these constraints have to
4063     // distinguish between bit patterns that are valid 32-bit or 64-bit
4064     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4065     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4066     // versa.
4067     case 'K':
4068       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4069         break;
4070       return;
4071     case 'L':
4072       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4073         break;
4074       return;
4075     // The M and N constraints are a superset of K and L respectively, for use
4076     // with the MOV (immediate) alias. As well as the logical immediates they
4077     // also match 32 or 64-bit immediates that can be loaded either using a
4078     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4079     // (M) or 64-bit 0x1234000000000000 (N) etc.
4080     // As a note some of this code is liberally stolen from the asm parser.
4081     case 'M': {
4082       if (!isUInt<32>(CVal))
4083         return;
4084       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4085         break;
4086       if ((CVal & 0xFFFF) == CVal)
4087         break;
4088       if ((CVal & 0xFFFF0000ULL) == CVal)
4089         break;
4090       uint64_t NCVal = ~(uint32_t)CVal;
4091       if ((NCVal & 0xFFFFULL) == NCVal)
4092         break;
4093       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4094         break;
4095       return;
4096     }
4097     case 'N': {
4098       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4099         break;
4100       if ((CVal & 0xFFFFULL) == CVal)
4101         break;
4102       if ((CVal & 0xFFFF0000ULL) == CVal)
4103         break;
4104       if ((CVal & 0xFFFF00000000ULL) == CVal)
4105         break;
4106       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4107         break;
4108       uint64_t NCVal = ~CVal;
4109       if ((NCVal & 0xFFFFULL) == NCVal)
4110         break;
4111       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4112         break;
4113       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4114         break;
4115       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4116         break;
4117       return;
4118     }
4119     default:
4120       return;
4121     }
4122
4123     // All assembler immediates are 64-bit integers.
4124     Result = DAG.getTargetConstant(CVal, MVT::i64);
4125     break;
4126   }
4127
4128   if (Result.getNode()) {
4129     Ops.push_back(Result);
4130     return;
4131   }
4132
4133   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4134 }
4135
4136 //===----------------------------------------------------------------------===//
4137 //                     AArch64 Advanced SIMD Support
4138 //===----------------------------------------------------------------------===//
4139
4140 /// WidenVector - Given a value in the V64 register class, produce the
4141 /// equivalent value in the V128 register class.
4142 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4143   EVT VT = V64Reg.getValueType();
4144   unsigned NarrowSize = VT.getVectorNumElements();
4145   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4146   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4147   SDLoc DL(V64Reg);
4148
4149   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4150                      V64Reg, DAG.getConstant(0, MVT::i32));
4151 }
4152
4153 /// getExtFactor - Determine the adjustment factor for the position when
4154 /// generating an "extract from vector registers" instruction.
4155 static unsigned getExtFactor(SDValue &V) {
4156   EVT EltType = V.getValueType().getVectorElementType();
4157   return EltType.getSizeInBits() / 8;
4158 }
4159
4160 /// NarrowVector - Given a value in the V128 register class, produce the
4161 /// equivalent value in the V64 register class.
4162 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4163   EVT VT = V128Reg.getValueType();
4164   unsigned WideSize = VT.getVectorNumElements();
4165   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4166   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4167   SDLoc DL(V128Reg);
4168
4169   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4170 }
4171
4172 // Gather data to see if the operation can be modelled as a
4173 // shuffle in combination with VEXTs.
4174 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4175                                                   SelectionDAG &DAG) const {
4176   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4177   SDLoc dl(Op);
4178   EVT VT = Op.getValueType();
4179   unsigned NumElts = VT.getVectorNumElements();
4180
4181   struct ShuffleSourceInfo {
4182     SDValue Vec;
4183     unsigned MinElt;
4184     unsigned MaxElt;
4185
4186     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4187     // be compatible with the shuffle we intend to construct. As a result
4188     // ShuffleVec will be some sliding window into the original Vec.
4189     SDValue ShuffleVec;
4190
4191     // Code should guarantee that element i in Vec starts at element "WindowBase
4192     // + i * WindowScale in ShuffleVec".
4193     int WindowBase;
4194     int WindowScale;
4195
4196     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4197     ShuffleSourceInfo(SDValue Vec)
4198         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4199           WindowScale(1) {}
4200   };
4201
4202   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4203   // node.
4204   SmallVector<ShuffleSourceInfo, 2> Sources;
4205   for (unsigned i = 0; i < NumElts; ++i) {
4206     SDValue V = Op.getOperand(i);
4207     if (V.getOpcode() == ISD::UNDEF)
4208       continue;
4209     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4210       // A shuffle can only come from building a vector from various
4211       // elements of other vectors.
4212       return SDValue();
4213     }
4214
4215     // Add this element source to the list if it's not already there.
4216     SDValue SourceVec = V.getOperand(0);
4217     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4218     if (Source == Sources.end())
4219       Sources.push_back(ShuffleSourceInfo(SourceVec));
4220
4221     // Update the minimum and maximum lane number seen.
4222     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4223     Source->MinElt = std::min(Source->MinElt, EltNo);
4224     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4225   }
4226
4227   // Currently only do something sane when at most two source vectors
4228   // are involved.
4229   if (Sources.size() > 2)
4230     return SDValue();
4231
4232   // Find out the smallest element size among result and two sources, and use
4233   // it as element size to build the shuffle_vector.
4234   EVT SmallestEltTy = VT.getVectorElementType();
4235   for (auto &Source : Sources) {
4236     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4237     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4238       SmallestEltTy = SrcEltTy;
4239     }
4240   }
4241   unsigned ResMultiplier =
4242       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4243   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4244   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4245
4246   // If the source vector is too wide or too narrow, we may nevertheless be able
4247   // to construct a compatible shuffle either by concatenating it with UNDEF or
4248   // extracting a suitable range of elements.
4249   for (auto &Src : Sources) {
4250     EVT SrcVT = Src.ShuffleVec.getValueType();
4251
4252     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4253       continue;
4254
4255     // This stage of the search produces a source with the same element type as
4256     // the original, but with a total width matching the BUILD_VECTOR output.
4257     EVT EltVT = SrcVT.getVectorElementType();
4258     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
4259                                   VT.getSizeInBits() / EltVT.getSizeInBits());
4260
4261     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4262       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4263       // We can pad out the smaller vector for free, so if it's part of a
4264       // shuffle...
4265       Src.ShuffleVec =
4266           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4267                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4268       continue;
4269     }
4270
4271     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4272
4273     if (Src.MaxElt - Src.MinElt >= NumElts) {
4274       // Span too large for a VEXT to cope
4275       return SDValue();
4276     }
4277
4278     if (Src.MinElt >= NumElts) {
4279       // The extraction can just take the second half
4280       Src.ShuffleVec =
4281           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4282                       DAG.getIntPtrConstant(NumElts));
4283       Src.WindowBase = -NumElts;
4284     } else if (Src.MaxElt < NumElts) {
4285       // The extraction can just take the first half
4286       Src.ShuffleVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4287                                    Src.ShuffleVec, DAG.getIntPtrConstant(0));
4288     } else {
4289       // An actual VEXT is needed
4290       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4291                                      Src.ShuffleVec, DAG.getIntPtrConstant(0));
4292       SDValue VEXTSrc2 =
4293           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4294                       DAG.getIntPtrConstant(NumElts));
4295       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4296
4297       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4298                                    VEXTSrc2, DAG.getConstant(Imm, MVT::i32));
4299       Src.WindowBase = -Src.MinElt;
4300     }
4301   }
4302
4303   // Another possible incompatibility occurs from the vector element types. We
4304   // can fix this by bitcasting the source vectors to the same type we intend
4305   // for the shuffle.
4306   for (auto &Src : Sources) {
4307     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4308     if (SrcEltTy == SmallestEltTy)
4309       continue;
4310     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4311     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4312     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4313     Src.WindowBase *= Src.WindowScale;
4314   }
4315
4316   // Final sanity check before we try to actually produce a shuffle.
4317   DEBUG(
4318     for (auto Src : Sources)
4319       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4320   );
4321
4322   // The stars all align, our next step is to produce the mask for the shuffle.
4323   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4324   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4325   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4326     SDValue Entry = Op.getOperand(i);
4327     if (Entry.getOpcode() == ISD::UNDEF)
4328       continue;
4329
4330     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4331     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4332
4333     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4334     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4335     // segment.
4336     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4337     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4338                                VT.getVectorElementType().getSizeInBits());
4339     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4340
4341     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4342     // starting at the appropriate offset.
4343     int *LaneMask = &Mask[i * ResMultiplier];
4344
4345     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4346     ExtractBase += NumElts * (Src - Sources.begin());
4347     for (int j = 0; j < LanesDefined; ++j)
4348       LaneMask[j] = ExtractBase + j;
4349   }
4350
4351   // Final check before we try to produce nonsense...
4352   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4353     return SDValue();
4354
4355   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4356   for (unsigned i = 0; i < Sources.size(); ++i)
4357     ShuffleOps[i] = Sources[i].ShuffleVec;
4358
4359   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4360                                          ShuffleOps[1], &Mask[0]);
4361   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4362 }
4363
4364 // check if an EXT instruction can handle the shuffle mask when the
4365 // vector sources of the shuffle are the same.
4366 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4367   unsigned NumElts = VT.getVectorNumElements();
4368
4369   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4370   if (M[0] < 0)
4371     return false;
4372
4373   Imm = M[0];
4374
4375   // If this is a VEXT shuffle, the immediate value is the index of the first
4376   // element.  The other shuffle indices must be the successive elements after
4377   // the first one.
4378   unsigned ExpectedElt = Imm;
4379   for (unsigned i = 1; i < NumElts; ++i) {
4380     // Increment the expected index.  If it wraps around, just follow it
4381     // back to index zero and keep going.
4382     ++ExpectedElt;
4383     if (ExpectedElt == NumElts)
4384       ExpectedElt = 0;
4385
4386     if (M[i] < 0)
4387       continue; // ignore UNDEF indices
4388     if (ExpectedElt != static_cast<unsigned>(M[i]))
4389       return false;
4390   }
4391
4392   return true;
4393 }
4394
4395 // check if an EXT instruction can handle the shuffle mask when the
4396 // vector sources of the shuffle are different.
4397 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4398                       unsigned &Imm) {
4399   // Look for the first non-undef element.
4400   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4401       [](int Elt) {return Elt >= 0;});
4402
4403   // Benefit form APInt to handle overflow when calculating expected element.
4404   unsigned NumElts = VT.getVectorNumElements();
4405   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4406   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4407   // The following shuffle indices must be the successive elements after the
4408   // first real element.
4409   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4410       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4411   if (FirstWrongElt != M.end())
4412     return false;
4413
4414   // The index of an EXT is the first element if it is not UNDEF.
4415   // Watch out for the beginning UNDEFs. The EXT index should be the expected
4416   // value of the first element.  E.g. 
4417   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4418   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4419   // ExpectedElt is the last mask index plus 1.
4420   Imm = ExpectedElt.getZExtValue();
4421
4422   // There are two difference cases requiring to reverse input vectors.
4423   // For example, for vector <4 x i32> we have the following cases,
4424   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4425   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4426   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4427   // to reverse two input vectors.
4428   if (Imm < NumElts)
4429     ReverseEXT = true;
4430   else
4431     Imm -= NumElts;
4432
4433   return true;
4434 }
4435
4436 /// isREVMask - Check if a vector shuffle corresponds to a REV
4437 /// instruction with the specified blocksize.  (The order of the elements
4438 /// within each block of the vector is reversed.)
4439 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4440   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4441          "Only possible block sizes for REV are: 16, 32, 64");
4442
4443   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4444   if (EltSz == 64)
4445     return false;
4446
4447   unsigned NumElts = VT.getVectorNumElements();
4448   unsigned BlockElts = M[0] + 1;
4449   // If the first shuffle index is UNDEF, be optimistic.
4450   if (M[0] < 0)
4451     BlockElts = BlockSize / EltSz;
4452
4453   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4454     return false;
4455
4456   for (unsigned i = 0; i < NumElts; ++i) {
4457     if (M[i] < 0)
4458       continue; // ignore UNDEF indices
4459     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4460       return false;
4461   }
4462
4463   return true;
4464 }
4465
4466 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4467   unsigned NumElts = VT.getVectorNumElements();
4468   WhichResult = (M[0] == 0 ? 0 : 1);
4469   unsigned Idx = WhichResult * NumElts / 2;
4470   for (unsigned i = 0; i != NumElts; i += 2) {
4471     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4472         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4473       return false;
4474     Idx += 1;
4475   }
4476
4477   return true;
4478 }
4479
4480 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4481   unsigned NumElts = VT.getVectorNumElements();
4482   WhichResult = (M[0] == 0 ? 0 : 1);
4483   for (unsigned i = 0; i != NumElts; ++i) {
4484     if (M[i] < 0)
4485       continue; // ignore UNDEF indices
4486     if ((unsigned)M[i] != 2 * i + WhichResult)
4487       return false;
4488   }
4489
4490   return true;
4491 }
4492
4493 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4494   unsigned NumElts = VT.getVectorNumElements();
4495   WhichResult = (M[0] == 0 ? 0 : 1);
4496   for (unsigned i = 0; i < NumElts; i += 2) {
4497     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4498         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4499       return false;
4500   }
4501   return true;
4502 }
4503
4504 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4505 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4506 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4507 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4508   unsigned NumElts = VT.getVectorNumElements();
4509   WhichResult = (M[0] == 0 ? 0 : 1);
4510   unsigned Idx = WhichResult * NumElts / 2;
4511   for (unsigned i = 0; i != NumElts; i += 2) {
4512     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4513         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4514       return false;
4515     Idx += 1;
4516   }
4517
4518   return true;
4519 }
4520
4521 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4522 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4523 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4524 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4525   unsigned Half = VT.getVectorNumElements() / 2;
4526   WhichResult = (M[0] == 0 ? 0 : 1);
4527   for (unsigned j = 0; j != 2; ++j) {
4528     unsigned Idx = WhichResult;
4529     for (unsigned i = 0; i != Half; ++i) {
4530       int MIdx = M[i + j * Half];
4531       if (MIdx >= 0 && (unsigned)MIdx != Idx)
4532         return false;
4533       Idx += 2;
4534     }
4535   }
4536
4537   return true;
4538 }
4539
4540 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4541 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4542 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4543 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4544   unsigned NumElts = VT.getVectorNumElements();
4545   WhichResult = (M[0] == 0 ? 0 : 1);
4546   for (unsigned i = 0; i < NumElts; i += 2) {
4547     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4548         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4549       return false;
4550   }
4551   return true;
4552 }
4553
4554 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4555                       bool &DstIsLeft, int &Anomaly) {
4556   if (M.size() != static_cast<size_t>(NumInputElements))
4557     return false;
4558
4559   int NumLHSMatch = 0, NumRHSMatch = 0;
4560   int LastLHSMismatch = -1, LastRHSMismatch = -1;
4561
4562   for (int i = 0; i < NumInputElements; ++i) {
4563     if (M[i] == -1) {
4564       ++NumLHSMatch;
4565       ++NumRHSMatch;
4566       continue;
4567     }
4568
4569     if (M[i] == i)
4570       ++NumLHSMatch;
4571     else
4572       LastLHSMismatch = i;
4573
4574     if (M[i] == i + NumInputElements)
4575       ++NumRHSMatch;
4576     else
4577       LastRHSMismatch = i;
4578   }
4579
4580   if (NumLHSMatch == NumInputElements - 1) {
4581     DstIsLeft = true;
4582     Anomaly = LastLHSMismatch;
4583     return true;
4584   } else if (NumRHSMatch == NumInputElements - 1) {
4585     DstIsLeft = false;
4586     Anomaly = LastRHSMismatch;
4587     return true;
4588   }
4589
4590   return false;
4591 }
4592
4593 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4594   if (VT.getSizeInBits() != 128)
4595     return false;
4596
4597   unsigned NumElts = VT.getVectorNumElements();
4598
4599   for (int I = 0, E = NumElts / 2; I != E; I++) {
4600     if (Mask[I] != I)
4601       return false;
4602   }
4603
4604   int Offset = NumElts / 2;
4605   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4606     if (Mask[I] != I + SplitLHS * Offset)
4607       return false;
4608   }
4609
4610   return true;
4611 }
4612
4613 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4614   SDLoc DL(Op);
4615   EVT VT = Op.getValueType();
4616   SDValue V0 = Op.getOperand(0);
4617   SDValue V1 = Op.getOperand(1);
4618   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4619
4620   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4621       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4622     return SDValue();
4623
4624   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4625
4626   if (!isConcatMask(Mask, VT, SplitV0))
4627     return SDValue();
4628
4629   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4630                                 VT.getVectorNumElements() / 2);
4631   if (SplitV0) {
4632     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4633                      DAG.getConstant(0, MVT::i64));
4634   }
4635   if (V1.getValueType().getSizeInBits() == 128) {
4636     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4637                      DAG.getConstant(0, MVT::i64));
4638   }
4639   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4640 }
4641
4642 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4643 /// the specified operations to build the shuffle.
4644 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4645                                       SDValue RHS, SelectionDAG &DAG,
4646                                       SDLoc dl) {
4647   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4648   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4649   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4650
4651   enum {
4652     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4653     OP_VREV,
4654     OP_VDUP0,
4655     OP_VDUP1,
4656     OP_VDUP2,
4657     OP_VDUP3,
4658     OP_VEXT1,
4659     OP_VEXT2,
4660     OP_VEXT3,
4661     OP_VUZPL, // VUZP, left result
4662     OP_VUZPR, // VUZP, right result
4663     OP_VZIPL, // VZIP, left result
4664     OP_VZIPR, // VZIP, right result
4665     OP_VTRNL, // VTRN, left result
4666     OP_VTRNR  // VTRN, right result
4667   };
4668
4669   if (OpNum == OP_COPY) {
4670     if (LHSID == (1 * 9 + 2) * 9 + 3)
4671       return LHS;
4672     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4673     return RHS;
4674   }
4675
4676   SDValue OpLHS, OpRHS;
4677   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4678   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4679   EVT VT = OpLHS.getValueType();
4680
4681   switch (OpNum) {
4682   default:
4683     llvm_unreachable("Unknown shuffle opcode!");
4684   case OP_VREV:
4685     // VREV divides the vector in half and swaps within the half.
4686     if (VT.getVectorElementType() == MVT::i32 ||
4687         VT.getVectorElementType() == MVT::f32)
4688       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
4689     // vrev <4 x i16> -> REV32
4690     if (VT.getVectorElementType() == MVT::i16)
4691       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
4692     // vrev <4 x i8> -> REV16
4693     assert(VT.getVectorElementType() == MVT::i8);
4694     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
4695   case OP_VDUP0:
4696   case OP_VDUP1:
4697   case OP_VDUP2:
4698   case OP_VDUP3: {
4699     EVT EltTy = VT.getVectorElementType();
4700     unsigned Opcode;
4701     if (EltTy == MVT::i8)
4702       Opcode = AArch64ISD::DUPLANE8;
4703     else if (EltTy == MVT::i16)
4704       Opcode = AArch64ISD::DUPLANE16;
4705     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4706       Opcode = AArch64ISD::DUPLANE32;
4707     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4708       Opcode = AArch64ISD::DUPLANE64;
4709     else
4710       llvm_unreachable("Invalid vector element type?");
4711
4712     if (VT.getSizeInBits() == 64)
4713       OpLHS = WidenVector(OpLHS, DAG);
4714     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4715     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4716   }
4717   case OP_VEXT1:
4718   case OP_VEXT2:
4719   case OP_VEXT3: {
4720     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4721     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
4722                        DAG.getConstant(Imm, MVT::i32));
4723   }
4724   case OP_VUZPL:
4725     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
4726                        OpRHS);
4727   case OP_VUZPR:
4728     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
4729                        OpRHS);
4730   case OP_VZIPL:
4731     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
4732                        OpRHS);
4733   case OP_VZIPR:
4734     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
4735                        OpRHS);
4736   case OP_VTRNL:
4737     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
4738                        OpRHS);
4739   case OP_VTRNR:
4740     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
4741                        OpRHS);
4742   }
4743 }
4744
4745 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4746                            SelectionDAG &DAG) {
4747   // Check to see if we can use the TBL instruction.
4748   SDValue V1 = Op.getOperand(0);
4749   SDValue V2 = Op.getOperand(1);
4750   SDLoc DL(Op);
4751
4752   EVT EltVT = Op.getValueType().getVectorElementType();
4753   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4754
4755   SmallVector<SDValue, 8> TBLMask;
4756   for (int Val : ShuffleMask) {
4757     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4758       unsigned Offset = Byte + Val * BytesPerElt;
4759       TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4760     }
4761   }
4762
4763   MVT IndexVT = MVT::v8i8;
4764   unsigned IndexLen = 8;
4765   if (Op.getValueType().getSizeInBits() == 128) {
4766     IndexVT = MVT::v16i8;
4767     IndexLen = 16;
4768   }
4769
4770   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4771   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4772
4773   SDValue Shuffle;
4774   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4775     if (IndexLen == 8)
4776       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4777     Shuffle = DAG.getNode(
4778         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4779         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4780         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4781                     makeArrayRef(TBLMask.data(), IndexLen)));
4782   } else {
4783     if (IndexLen == 8) {
4784       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4785       Shuffle = DAG.getNode(
4786           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4787           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4788           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4789                       makeArrayRef(TBLMask.data(), IndexLen)));
4790     } else {
4791       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4792       // cannot currently represent the register constraints on the input
4793       // table registers.
4794       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4795       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4796       //                               &TBLMask[0], IndexLen));
4797       Shuffle = DAG.getNode(
4798           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4799           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4800           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4801                       makeArrayRef(TBLMask.data(), IndexLen)));
4802     }
4803   }
4804   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4805 }
4806
4807 static unsigned getDUPLANEOp(EVT EltType) {
4808   if (EltType == MVT::i8)
4809     return AArch64ISD::DUPLANE8;
4810   if (EltType == MVT::i16)
4811     return AArch64ISD::DUPLANE16;
4812   if (EltType == MVT::i32 || EltType == MVT::f32)
4813     return AArch64ISD::DUPLANE32;
4814   if (EltType == MVT::i64 || EltType == MVT::f64)
4815     return AArch64ISD::DUPLANE64;
4816
4817   llvm_unreachable("Invalid vector element type?");
4818 }
4819
4820 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4821                                                    SelectionDAG &DAG) const {
4822   SDLoc dl(Op);
4823   EVT VT = Op.getValueType();
4824
4825   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4826
4827   // Convert shuffles that are directly supported on NEON to target-specific
4828   // DAG nodes, instead of keeping them as shuffles and matching them again
4829   // during code selection.  This is more efficient and avoids the possibility
4830   // of inconsistencies between legalization and selection.
4831   ArrayRef<int> ShuffleMask = SVN->getMask();
4832
4833   SDValue V1 = Op.getOperand(0);
4834   SDValue V2 = Op.getOperand(1);
4835
4836   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4837                                        V1.getValueType().getSimpleVT())) {
4838     int Lane = SVN->getSplatIndex();
4839     // If this is undef splat, generate it via "just" vdup, if possible.
4840     if (Lane == -1)
4841       Lane = 0;
4842
4843     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4844       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
4845                          V1.getOperand(0));
4846     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4847     // constant. If so, we can just reference the lane's definition directly.
4848     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4849         !isa<ConstantSDNode>(V1.getOperand(Lane)))
4850       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
4851
4852     // Otherwise, duplicate from the lane of the input vector.
4853     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4854
4855     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4856     // to make a vector of the same size as this SHUFFLE. We can ignore the
4857     // extract entirely, and canonicalise the concat using WidenVector.
4858     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4859       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4860       V1 = V1.getOperand(0);
4861     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4862       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4863       Lane -= Idx * VT.getVectorNumElements() / 2;
4864       V1 = WidenVector(V1.getOperand(Idx), DAG);
4865     } else if (VT.getSizeInBits() == 64)
4866       V1 = WidenVector(V1, DAG);
4867
4868     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4869   }
4870
4871   if (isREVMask(ShuffleMask, VT, 64))
4872     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
4873   if (isREVMask(ShuffleMask, VT, 32))
4874     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
4875   if (isREVMask(ShuffleMask, VT, 16))
4876     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
4877
4878   bool ReverseEXT = false;
4879   unsigned Imm;
4880   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4881     if (ReverseEXT)
4882       std::swap(V1, V2);
4883     Imm *= getExtFactor(V1);
4884     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
4885                        DAG.getConstant(Imm, MVT::i32));
4886   } else if (V2->getOpcode() == ISD::UNDEF &&
4887              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4888     Imm *= getExtFactor(V1);
4889     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
4890                        DAG.getConstant(Imm, MVT::i32));
4891   }
4892
4893   unsigned WhichResult;
4894   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4895     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4896     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4897   }
4898   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4899     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4900     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4901   }
4902   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4903     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4904     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4905   }
4906
4907   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4908     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4909     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4910   }
4911   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4912     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4913     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4914   }
4915   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4916     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4917     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4918   }
4919
4920   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4921   if (Concat.getNode())
4922     return Concat;
4923
4924   bool DstIsLeft;
4925   int Anomaly;
4926   int NumInputElements = V1.getValueType().getVectorNumElements();
4927   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4928     SDValue DstVec = DstIsLeft ? V1 : V2;
4929     SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4930
4931     SDValue SrcVec = V1;
4932     int SrcLane = ShuffleMask[Anomaly];
4933     if (SrcLane >= NumInputElements) {
4934       SrcVec = V2;
4935       SrcLane -= VT.getVectorNumElements();
4936     }
4937     SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4938
4939     EVT ScalarVT = VT.getVectorElementType();
4940     if (ScalarVT.getSizeInBits() < 32)
4941       ScalarVT = MVT::i32;
4942
4943     return DAG.getNode(
4944         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4945         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4946         DstLaneV);
4947   }
4948
4949   // If the shuffle is not directly supported and it has 4 elements, use
4950   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4951   unsigned NumElts = VT.getVectorNumElements();
4952   if (NumElts == 4) {
4953     unsigned PFIndexes[4];
4954     for (unsigned i = 0; i != 4; ++i) {
4955       if (ShuffleMask[i] < 0)
4956         PFIndexes[i] = 8;
4957       else
4958         PFIndexes[i] = ShuffleMask[i];
4959     }
4960
4961     // Compute the index in the perfect shuffle table.
4962     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4963                             PFIndexes[2] * 9 + PFIndexes[3];
4964     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4965     unsigned Cost = (PFEntry >> 30);
4966
4967     if (Cost <= 4)
4968       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4969   }
4970
4971   return GenerateTBL(Op, ShuffleMask, DAG);
4972 }
4973
4974 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4975                                APInt &UndefBits) {
4976   EVT VT = BVN->getValueType(0);
4977   APInt SplatBits, SplatUndef;
4978   unsigned SplatBitSize;
4979   bool HasAnyUndefs;
4980   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4981     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4982
4983     for (unsigned i = 0; i < NumSplats; ++i) {
4984       CnstBits <<= SplatBitSize;
4985       UndefBits <<= SplatBitSize;
4986       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4987       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4988     }
4989
4990     return true;
4991   }
4992
4993   return false;
4994 }
4995
4996 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
4997                                               SelectionDAG &DAG) const {
4998   BuildVectorSDNode *BVN =
4999       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5000   SDValue LHS = Op.getOperand(0);
5001   SDLoc dl(Op);
5002   EVT VT = Op.getValueType();
5003
5004   if (!BVN)
5005     return Op;
5006
5007   APInt CnstBits(VT.getSizeInBits(), 0);
5008   APInt UndefBits(VT.getSizeInBits(), 0);
5009   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5010     // We only have BIC vector immediate instruction, which is and-not.
5011     CnstBits = ~CnstBits;
5012
5013     // We make use of a little bit of goto ickiness in order to avoid having to
5014     // duplicate the immediate matching logic for the undef toggled case.
5015     bool SecondTry = false;
5016   AttemptModImm:
5017
5018     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5019       CnstBits = CnstBits.zextOrTrunc(64);
5020       uint64_t CnstVal = CnstBits.getZExtValue();
5021
5022       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5023         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5024         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5025         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5026                                   DAG.getConstant(CnstVal, MVT::i32),
5027                                   DAG.getConstant(0, MVT::i32));
5028         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5029       }
5030
5031       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5032         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5033         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5034         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5035                                   DAG.getConstant(CnstVal, MVT::i32),
5036                                   DAG.getConstant(8, MVT::i32));
5037         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5038       }
5039
5040       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5041         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5042         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5043         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5044                                   DAG.getConstant(CnstVal, MVT::i32),
5045                                   DAG.getConstant(16, MVT::i32));
5046         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5047       }
5048
5049       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5050         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5051         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5052         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5053                                   DAG.getConstant(CnstVal, MVT::i32),
5054                                   DAG.getConstant(24, MVT::i32));
5055         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5056       }
5057
5058       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5059         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5060         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5061         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5062                                   DAG.getConstant(CnstVal, MVT::i32),
5063                                   DAG.getConstant(0, MVT::i32));
5064         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5065       }
5066
5067       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5068         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5069         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5070         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5071                                   DAG.getConstant(CnstVal, MVT::i32),
5072                                   DAG.getConstant(8, MVT::i32));
5073         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5074       }
5075     }
5076
5077     if (SecondTry)
5078       goto FailedModImm;
5079     SecondTry = true;
5080     CnstBits = ~UndefBits;
5081     goto AttemptModImm;
5082   }
5083
5084 // We can always fall back to a non-immediate AND.
5085 FailedModImm:
5086   return Op;
5087 }
5088
5089 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5090 // consists of only the same constant int value, returned in reference arg
5091 // ConstVal
5092 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5093                                      uint64_t &ConstVal) {
5094   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5095   if (!Bvec)
5096     return false;
5097   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5098   if (!FirstElt)
5099     return false;
5100   EVT VT = Bvec->getValueType(0);
5101   unsigned NumElts = VT.getVectorNumElements();
5102   for (unsigned i = 1; i < NumElts; ++i)
5103     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5104       return false;
5105   ConstVal = FirstElt->getZExtValue();
5106   return true;
5107 }
5108
5109 static unsigned getIntrinsicID(const SDNode *N) {
5110   unsigned Opcode = N->getOpcode();
5111   switch (Opcode) {
5112   default:
5113     return Intrinsic::not_intrinsic;
5114   case ISD::INTRINSIC_WO_CHAIN: {
5115     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5116     if (IID < Intrinsic::num_intrinsics)
5117       return IID;
5118     return Intrinsic::not_intrinsic;
5119   }
5120   }
5121 }
5122
5123 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5124 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5125 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5126 // Also, logical shift right -> sri, with the same structure.
5127 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5128   EVT VT = N->getValueType(0);
5129
5130   if (!VT.isVector())
5131     return SDValue();
5132
5133   SDLoc DL(N);
5134
5135   // Is the first op an AND?
5136   const SDValue And = N->getOperand(0);
5137   if (And.getOpcode() != ISD::AND)
5138     return SDValue();
5139
5140   // Is the second op an shl or lshr?
5141   SDValue Shift = N->getOperand(1);
5142   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5143   // or AArch64ISD::VLSHR vector, #shift
5144   unsigned ShiftOpc = Shift.getOpcode();
5145   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5146     return SDValue();
5147   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5148
5149   // Is the shift amount constant?
5150   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5151   if (!C2node)
5152     return SDValue();
5153
5154   // Is the and mask vector all constant?
5155   uint64_t C1;
5156   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5157     return SDValue();
5158
5159   // Is C1 == ~C2, taking into account how much one can shift elements of a
5160   // particular size?
5161   uint64_t C2 = C2node->getZExtValue();
5162   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5163   if (C2 > ElemSizeInBits)
5164     return SDValue();
5165   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5166   if ((C1 & ElemMask) != (~C2 & ElemMask))
5167     return SDValue();
5168
5169   SDValue X = And.getOperand(0);
5170   SDValue Y = Shift.getOperand(0);
5171
5172   unsigned Intrin =
5173       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5174   SDValue ResultSLI =
5175       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5176                   DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5177
5178   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5179   DEBUG(N->dump(&DAG));
5180   DEBUG(dbgs() << "into: \n");
5181   DEBUG(ResultSLI->dump(&DAG));
5182
5183   ++NumShiftInserts;
5184   return ResultSLI;
5185 }
5186
5187 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5188                                              SelectionDAG &DAG) const {
5189   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5190   if (EnableAArch64SlrGeneration) {
5191     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5192     if (Res.getNode())
5193       return Res;
5194   }
5195
5196   BuildVectorSDNode *BVN =
5197       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5198   SDValue LHS = Op.getOperand(1);
5199   SDLoc dl(Op);
5200   EVT VT = Op.getValueType();
5201
5202   // OR commutes, so try swapping the operands.
5203   if (!BVN) {
5204     LHS = Op.getOperand(0);
5205     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5206   }
5207   if (!BVN)
5208     return Op;
5209
5210   APInt CnstBits(VT.getSizeInBits(), 0);
5211   APInt UndefBits(VT.getSizeInBits(), 0);
5212   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5213     // We make use of a little bit of goto ickiness in order to avoid having to
5214     // duplicate the immediate matching logic for the undef toggled case.
5215     bool SecondTry = false;
5216   AttemptModImm:
5217
5218     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5219       CnstBits = CnstBits.zextOrTrunc(64);
5220       uint64_t CnstVal = CnstBits.getZExtValue();
5221
5222       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5223         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5224         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5225         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5226                                   DAG.getConstant(CnstVal, MVT::i32),
5227                                   DAG.getConstant(0, MVT::i32));
5228         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5229       }
5230
5231       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5232         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5233         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5234         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5235                                   DAG.getConstant(CnstVal, MVT::i32),
5236                                   DAG.getConstant(8, MVT::i32));
5237         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5238       }
5239
5240       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5241         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5242         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5243         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5244                                   DAG.getConstant(CnstVal, MVT::i32),
5245                                   DAG.getConstant(16, MVT::i32));
5246         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5247       }
5248
5249       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5250         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5251         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5252         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5253                                   DAG.getConstant(CnstVal, MVT::i32),
5254                                   DAG.getConstant(24, MVT::i32));
5255         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5256       }
5257
5258       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5259         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5260         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5261         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5262                                   DAG.getConstant(CnstVal, MVT::i32),
5263                                   DAG.getConstant(0, MVT::i32));
5264         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5265       }
5266
5267       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5268         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5269         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5270         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5271                                   DAG.getConstant(CnstVal, MVT::i32),
5272                                   DAG.getConstant(8, MVT::i32));
5273         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5274       }
5275     }
5276
5277     if (SecondTry)
5278       goto FailedModImm;
5279     SecondTry = true;
5280     CnstBits = UndefBits;
5281     goto AttemptModImm;
5282   }
5283
5284 // We can always fall back to a non-immediate OR.
5285 FailedModImm:
5286   return Op;
5287 }
5288
5289 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5290 // be truncated to fit element width.
5291 static SDValue NormalizeBuildVector(SDValue Op,
5292                                     SelectionDAG &DAG) {
5293   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5294   SDLoc dl(Op);
5295   EVT VT = Op.getValueType();
5296   EVT EltTy= VT.getVectorElementType();
5297
5298   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5299     return Op;
5300
5301   SmallVector<SDValue, 16> Ops;
5302   for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5303     SDValue Lane = Op.getOperand(I);
5304     if (Lane.getOpcode() == ISD::Constant) {
5305       APInt LowBits(EltTy.getSizeInBits(),
5306                     cast<ConstantSDNode>(Lane)->getZExtValue());
5307       Lane = DAG.getConstant(LowBits.getZExtValue(), MVT::i32);
5308     }
5309     Ops.push_back(Lane);
5310   }
5311   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5312 }
5313
5314 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5315                                                  SelectionDAG &DAG) const {
5316   SDLoc dl(Op);
5317   EVT VT = Op.getValueType();
5318   Op = NormalizeBuildVector(Op, DAG);
5319   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5320
5321   APInt CnstBits(VT.getSizeInBits(), 0);
5322   APInt UndefBits(VT.getSizeInBits(), 0);
5323   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5324     // We make use of a little bit of goto ickiness in order to avoid having to
5325     // duplicate the immediate matching logic for the undef toggled case.
5326     bool SecondTry = false;
5327   AttemptModImm:
5328
5329     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5330       CnstBits = CnstBits.zextOrTrunc(64);
5331       uint64_t CnstVal = CnstBits.getZExtValue();
5332
5333       // Certain magic vector constants (used to express things like NOT
5334       // and NEG) are passed through unmodified.  This allows codegen patterns
5335       // for these operations to match.  Special-purpose patterns will lower
5336       // these immediates to MOVIs if it proves necessary.
5337       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5338         return Op;
5339
5340       // The many faces of MOVI...
5341       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5342         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5343         if (VT.getSizeInBits() == 128) {
5344           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5345                                     DAG.getConstant(CnstVal, MVT::i32));
5346           return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5347         }
5348
5349         // Support the V64 version via subregister insertion.
5350         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5351                                   DAG.getConstant(CnstVal, MVT::i32));
5352         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5353       }
5354
5355       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5356         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5357         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5358         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5359                                   DAG.getConstant(CnstVal, MVT::i32),
5360                                   DAG.getConstant(0, MVT::i32));
5361         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5362       }
5363
5364       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5365         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5366         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5367         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5368                                   DAG.getConstant(CnstVal, MVT::i32),
5369                                   DAG.getConstant(8, MVT::i32));
5370         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5371       }
5372
5373       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5374         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5375         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5376         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5377                                   DAG.getConstant(CnstVal, MVT::i32),
5378                                   DAG.getConstant(16, MVT::i32));
5379         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5380       }
5381
5382       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5383         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5384         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5385         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5386                                   DAG.getConstant(CnstVal, MVT::i32),
5387                                   DAG.getConstant(24, MVT::i32));
5388         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5389       }
5390
5391       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5392         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5393         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5394         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5395                                   DAG.getConstant(CnstVal, MVT::i32),
5396                                   DAG.getConstant(0, MVT::i32));
5397         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5398       }
5399
5400       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5401         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5402         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5403         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5404                                   DAG.getConstant(CnstVal, MVT::i32),
5405                                   DAG.getConstant(8, MVT::i32));
5406         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5407       }
5408
5409       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5410         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5411         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5412         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5413                                   DAG.getConstant(CnstVal, MVT::i32),
5414                                   DAG.getConstant(264, MVT::i32));
5415         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5416       }
5417
5418       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5419         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5420         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5421         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5422                                   DAG.getConstant(CnstVal, MVT::i32),
5423                                   DAG.getConstant(272, MVT::i32));
5424         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5425       }
5426
5427       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5428         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5429         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5430         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5431                                   DAG.getConstant(CnstVal, MVT::i32));
5432         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5433       }
5434
5435       // The few faces of FMOV...
5436       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5437         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5438         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5439         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5440                                   DAG.getConstant(CnstVal, MVT::i32));
5441         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5442       }
5443
5444       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5445           VT.getSizeInBits() == 128) {
5446         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5447         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5448                                   DAG.getConstant(CnstVal, MVT::i32));
5449         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5450       }
5451
5452       // The many faces of MVNI...
5453       CnstVal = ~CnstVal;
5454       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5455         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5456         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5457         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5458                                   DAG.getConstant(CnstVal, MVT::i32),
5459                                   DAG.getConstant(0, MVT::i32));
5460         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5461       }
5462
5463       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5464         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5465         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5466         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5467                                   DAG.getConstant(CnstVal, MVT::i32),
5468                                   DAG.getConstant(8, MVT::i32));
5469         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5470       }
5471
5472       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5473         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5474         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5475         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5476                                   DAG.getConstant(CnstVal, MVT::i32),
5477                                   DAG.getConstant(16, MVT::i32));
5478         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5479       }
5480
5481       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5482         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5483         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5484         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5485                                   DAG.getConstant(CnstVal, MVT::i32),
5486                                   DAG.getConstant(24, MVT::i32));
5487         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5488       }
5489
5490       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5491         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5492         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5493         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5494                                   DAG.getConstant(CnstVal, MVT::i32),
5495                                   DAG.getConstant(0, MVT::i32));
5496         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5497       }
5498
5499       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5500         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5501         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5502         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5503                                   DAG.getConstant(CnstVal, MVT::i32),
5504                                   DAG.getConstant(8, MVT::i32));
5505         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5506       }
5507
5508       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5509         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5510         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5511         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5512                                   DAG.getConstant(CnstVal, MVT::i32),
5513                                   DAG.getConstant(264, MVT::i32));
5514         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5515       }
5516
5517       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5518         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5519         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5520         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5521                                   DAG.getConstant(CnstVal, MVT::i32),
5522                                   DAG.getConstant(272, MVT::i32));
5523         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5524       }
5525     }
5526
5527     if (SecondTry)
5528       goto FailedModImm;
5529     SecondTry = true;
5530     CnstBits = UndefBits;
5531     goto AttemptModImm;
5532   }
5533 FailedModImm:
5534
5535   // Scan through the operands to find some interesting properties we can
5536   // exploit:
5537   //   1) If only one value is used, we can use a DUP, or
5538   //   2) if only the low element is not undef, we can just insert that, or
5539   //   3) if only one constant value is used (w/ some non-constant lanes),
5540   //      we can splat the constant value into the whole vector then fill
5541   //      in the non-constant lanes.
5542   //   4) FIXME: If different constant values are used, but we can intelligently
5543   //             select the values we'll be overwriting for the non-constant
5544   //             lanes such that we can directly materialize the vector
5545   //             some other way (MOVI, e.g.), we can be sneaky.
5546   unsigned NumElts = VT.getVectorNumElements();
5547   bool isOnlyLowElement = true;
5548   bool usesOnlyOneValue = true;
5549   bool usesOnlyOneConstantValue = true;
5550   bool isConstant = true;
5551   unsigned NumConstantLanes = 0;
5552   SDValue Value;
5553   SDValue ConstantValue;
5554   for (unsigned i = 0; i < NumElts; ++i) {
5555     SDValue V = Op.getOperand(i);
5556     if (V.getOpcode() == ISD::UNDEF)
5557       continue;
5558     if (i > 0)
5559       isOnlyLowElement = false;
5560     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5561       isConstant = false;
5562
5563     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5564       ++NumConstantLanes;
5565       if (!ConstantValue.getNode())
5566         ConstantValue = V;
5567       else if (ConstantValue != V)
5568         usesOnlyOneConstantValue = false;
5569     }
5570
5571     if (!Value.getNode())
5572       Value = V;
5573     else if (V != Value)
5574       usesOnlyOneValue = false;
5575   }
5576
5577   if (!Value.getNode())
5578     return DAG.getUNDEF(VT);
5579
5580   if (isOnlyLowElement)
5581     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5582
5583   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
5584   // i32 and try again.
5585   if (usesOnlyOneValue) {
5586     if (!isConstant) {
5587       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5588           Value.getValueType() != VT)
5589         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5590
5591       // This is actually a DUPLANExx operation, which keeps everything vectory.
5592
5593       // DUPLANE works on 128-bit vectors, widen it if necessary.
5594       SDValue Lane = Value.getOperand(1);
5595       Value = Value.getOperand(0);
5596       if (Value.getValueType().getSizeInBits() == 64)
5597         Value = WidenVector(Value, DAG);
5598
5599       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5600       return DAG.getNode(Opcode, dl, VT, Value, Lane);
5601     }
5602
5603     if (VT.getVectorElementType().isFloatingPoint()) {
5604       SmallVector<SDValue, 8> Ops;
5605       MVT NewType =
5606           (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5607       for (unsigned i = 0; i < NumElts; ++i)
5608         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5609       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5610       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5611       Val = LowerBUILD_VECTOR(Val, DAG);
5612       if (Val.getNode())
5613         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5614     }
5615   }
5616
5617   // If there was only one constant value used and for more than one lane,
5618   // start by splatting that value, then replace the non-constant lanes. This
5619   // is better than the default, which will perform a separate initialization
5620   // for each lane.
5621   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5622     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
5623     // Now insert the non-constant lanes.
5624     for (unsigned i = 0; i < NumElts; ++i) {
5625       SDValue V = Op.getOperand(i);
5626       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5627       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5628         // Note that type legalization likely mucked about with the VT of the
5629         // source operand, so we may have to convert it here before inserting.
5630         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5631       }
5632     }
5633     return Val;
5634   }
5635
5636   // If all elements are constants and the case above didn't get hit, fall back
5637   // to the default expansion, which will generate a load from the constant
5638   // pool.
5639   if (isConstant)
5640     return SDValue();
5641
5642   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5643   if (NumElts >= 4) {
5644     SDValue shuffle = ReconstructShuffle(Op, DAG);
5645     if (shuffle != SDValue())
5646       return shuffle;
5647   }
5648
5649   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5650   // know the default expansion would otherwise fall back on something even
5651   // worse. For a vector with one or two non-undef values, that's
5652   // scalar_to_vector for the elements followed by a shuffle (provided the
5653   // shuffle is valid for the target) and materialization element by element
5654   // on the stack followed by a load for everything else.
5655   if (!isConstant && !usesOnlyOneValue) {
5656     SDValue Vec = DAG.getUNDEF(VT);
5657     SDValue Op0 = Op.getOperand(0);
5658     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5659     unsigned i = 0;
5660     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5661     // a) Avoid a RMW dependency on the full vector register, and
5662     // b) Allow the register coalescer to fold away the copy if the
5663     //    value is already in an S or D register.
5664     if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5665       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
5666       MachineSDNode *N =
5667           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5668                              DAG.getTargetConstant(SubIdx, MVT::i32));
5669       Vec = SDValue(N, 0);
5670       ++i;
5671     }
5672     for (; i < NumElts; ++i) {
5673       SDValue V = Op.getOperand(i);
5674       if (V.getOpcode() == ISD::UNDEF)
5675         continue;
5676       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5677       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5678     }
5679     return Vec;
5680   }
5681
5682   // Just use the default expansion. We failed to find a better alternative.
5683   return SDValue();
5684 }
5685
5686 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5687                                                       SelectionDAG &DAG) const {
5688   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5689
5690   // Check for non-constant or out of range lane.
5691   EVT VT = Op.getOperand(0).getValueType();
5692   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
5693   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
5694     return SDValue();
5695
5696
5697   // Insertion/extraction are legal for V128 types.
5698   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5699       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5700     return Op;
5701
5702   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5703       VT != MVT::v1i64 && VT != MVT::v2f32)
5704     return SDValue();
5705
5706   // For V64 types, we perform insertion by expanding the value
5707   // to a V128 type and perform the insertion on that.
5708   SDLoc DL(Op);
5709   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5710   EVT WideTy = WideVec.getValueType();
5711
5712   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5713                              Op.getOperand(1), Op.getOperand(2));
5714   // Re-narrow the resultant vector.
5715   return NarrowVector(Node, DAG);
5716 }
5717
5718 SDValue
5719 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5720                                                SelectionDAG &DAG) const {
5721   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5722
5723   // Check for non-constant or out of range lane.
5724   EVT VT = Op.getOperand(0).getValueType();
5725   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5726   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
5727     return SDValue();
5728
5729
5730   // Insertion/extraction are legal for V128 types.
5731   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5732       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5733     return Op;
5734
5735   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5736       VT != MVT::v1i64 && VT != MVT::v2f32)
5737     return SDValue();
5738
5739   // For V64 types, we perform extraction by expanding the value
5740   // to a V128 type and perform the extraction on that.
5741   SDLoc DL(Op);
5742   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5743   EVT WideTy = WideVec.getValueType();
5744
5745   EVT ExtrTy = WideTy.getVectorElementType();
5746   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5747     ExtrTy = MVT::i32;
5748
5749   // For extractions, we just return the result directly.
5750   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5751                      Op.getOperand(1));
5752 }
5753
5754 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5755                                                       SelectionDAG &DAG) const {
5756   EVT VT = Op.getOperand(0).getValueType();
5757   SDLoc dl(Op);
5758   // Just in case...
5759   if (!VT.isVector())
5760     return SDValue();
5761
5762   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5763   if (!Cst)
5764     return SDValue();
5765   unsigned Val = Cst->getZExtValue();
5766
5767   unsigned Size = Op.getValueType().getSizeInBits();
5768   if (Val == 0) {
5769     switch (Size) {
5770     case 8:
5771       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
5772                                         Op.getOperand(0));
5773     case 16:
5774       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
5775                                         Op.getOperand(0));
5776     case 32:
5777       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
5778                                         Op.getOperand(0));
5779     case 64:
5780       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
5781                                         Op.getOperand(0));
5782     default:
5783       llvm_unreachable("Unexpected vector type in extract_subvector!");
5784     }
5785   }
5786   // If this is extracting the upper 64-bits of a 128-bit vector, we match
5787   // that directly.
5788   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5789     return Op;
5790
5791   return SDValue();
5792 }
5793
5794 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5795                                                EVT VT) const {
5796   if (VT.getVectorNumElements() == 4 &&
5797       (VT.is128BitVector() || VT.is64BitVector())) {
5798     unsigned PFIndexes[4];
5799     for (unsigned i = 0; i != 4; ++i) {
5800       if (M[i] < 0)
5801         PFIndexes[i] = 8;
5802       else
5803         PFIndexes[i] = M[i];
5804     }
5805
5806     // Compute the index in the perfect shuffle table.
5807     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5808                             PFIndexes[2] * 9 + PFIndexes[3];
5809     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5810     unsigned Cost = (PFEntry >> 30);
5811
5812     if (Cost <= 4)
5813       return true;
5814   }
5815
5816   bool DummyBool;
5817   int DummyInt;
5818   unsigned DummyUnsigned;
5819
5820   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5821           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5822           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5823           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5824           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5825           isZIPMask(M, VT, DummyUnsigned) ||
5826           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5827           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5828           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5829           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5830           isConcatMask(M, VT, VT.getSizeInBits() == 128));
5831 }
5832
5833 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5834 /// operand of a vector shift operation, where all the elements of the
5835 /// build_vector must have the same constant integer value.
5836 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5837   // Ignore bit_converts.
5838   while (Op.getOpcode() == ISD::BITCAST)
5839     Op = Op.getOperand(0);
5840   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5841   APInt SplatBits, SplatUndef;
5842   unsigned SplatBitSize;
5843   bool HasAnyUndefs;
5844   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5845                                     HasAnyUndefs, ElementBits) ||
5846       SplatBitSize > ElementBits)
5847     return false;
5848   Cnt = SplatBits.getSExtValue();
5849   return true;
5850 }
5851
5852 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5853 /// operand of a vector shift left operation.  That value must be in the range:
5854 ///   0 <= Value < ElementBits for a left shift; or
5855 ///   0 <= Value <= ElementBits for a long left shift.
5856 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5857   assert(VT.isVector() && "vector shift count is not a vector type");
5858   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5859   if (!getVShiftImm(Op, ElementBits, Cnt))
5860     return false;
5861   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5862 }
5863
5864 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5865 /// operand of a vector shift right operation.  For a shift opcode, the value
5866 /// is positive, but for an intrinsic the value count must be negative. The
5867 /// absolute value must be in the range:
5868 ///   1 <= |Value| <= ElementBits for a right shift; or
5869 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
5870 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5871                          int64_t &Cnt) {
5872   assert(VT.isVector() && "vector shift count is not a vector type");
5873   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5874   if (!getVShiftImm(Op, ElementBits, Cnt))
5875     return false;
5876   if (isIntrinsic)
5877     Cnt = -Cnt;
5878   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5879 }
5880
5881 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5882                                                       SelectionDAG &DAG) const {
5883   EVT VT = Op.getValueType();
5884   SDLoc DL(Op);
5885   int64_t Cnt;
5886
5887   if (!Op.getOperand(1).getValueType().isVector())
5888     return Op;
5889   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5890
5891   switch (Op.getOpcode()) {
5892   default:
5893     llvm_unreachable("unexpected shift opcode");
5894
5895   case ISD::SHL:
5896     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5897       return DAG.getNode(AArch64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5898                          DAG.getConstant(Cnt, MVT::i32));
5899     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5900                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, MVT::i32),
5901                        Op.getOperand(0), Op.getOperand(1));
5902   case ISD::SRA:
5903   case ISD::SRL:
5904     // Right shift immediate
5905     if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5906         Cnt < EltSize) {
5907       unsigned Opc =
5908           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
5909       return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5910                          DAG.getConstant(Cnt, MVT::i32));
5911     }
5912
5913     // Right shift register.  Note, there is not a shift right register
5914     // instruction, but the shift left register instruction takes a signed
5915     // value, where negative numbers specify a right shift.
5916     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
5917                                                 : Intrinsic::aarch64_neon_ushl;
5918     // negate the shift amount
5919     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
5920     SDValue NegShiftLeft =
5921         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5922                     DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5923     return NegShiftLeft;
5924   }
5925
5926   return SDValue();
5927 }
5928
5929 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5930                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
5931                                     SDLoc dl, SelectionDAG &DAG) {
5932   EVT SrcVT = LHS.getValueType();
5933
5934   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5935   APInt CnstBits(VT.getSizeInBits(), 0);
5936   APInt UndefBits(VT.getSizeInBits(), 0);
5937   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5938   bool IsZero = IsCnst && (CnstBits == 0);
5939
5940   if (SrcVT.getVectorElementType().isFloatingPoint()) {
5941     switch (CC) {
5942     default:
5943       return SDValue();
5944     case AArch64CC::NE: {
5945       SDValue Fcmeq;
5946       if (IsZero)
5947         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5948       else
5949         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5950       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
5951     }
5952     case AArch64CC::EQ:
5953       if (IsZero)
5954         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5955       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5956     case AArch64CC::GE:
5957       if (IsZero)
5958         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
5959       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
5960     case AArch64CC::GT:
5961       if (IsZero)
5962         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
5963       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
5964     case AArch64CC::LS:
5965       if (IsZero)
5966         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
5967       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
5968     case AArch64CC::LT:
5969       if (!NoNans)
5970         return SDValue();
5971     // If we ignore NaNs then we can use to the MI implementation.
5972     // Fallthrough.
5973     case AArch64CC::MI:
5974       if (IsZero)
5975         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
5976       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
5977     }
5978   }
5979
5980   switch (CC) {
5981   default:
5982     return SDValue();
5983   case AArch64CC::NE: {
5984     SDValue Cmeq;
5985     if (IsZero)
5986       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5987     else
5988       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5989     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
5990   }
5991   case AArch64CC::EQ:
5992     if (IsZero)
5993       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5994     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5995   case AArch64CC::GE:
5996     if (IsZero)
5997       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
5998     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
5999   case AArch64CC::GT:
6000     if (IsZero)
6001       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6002     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6003   case AArch64CC::LE:
6004     if (IsZero)
6005       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6006     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6007   case AArch64CC::LS:
6008     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6009   case AArch64CC::LO:
6010     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6011   case AArch64CC::LT:
6012     if (IsZero)
6013       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6014     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6015   case AArch64CC::HI:
6016     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6017   case AArch64CC::HS:
6018     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6019   }
6020 }
6021
6022 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6023                                            SelectionDAG &DAG) const {
6024   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6025   SDValue LHS = Op.getOperand(0);
6026   SDValue RHS = Op.getOperand(1);
6027   SDLoc dl(Op);
6028
6029   if (LHS.getValueType().getVectorElementType().isInteger()) {
6030     assert(LHS.getValueType() == RHS.getValueType());
6031     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6032     return EmitVectorComparison(LHS, RHS, AArch64CC, false, Op.getValueType(),
6033                                 dl, DAG);
6034   }
6035
6036   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6037          LHS.getValueType().getVectorElementType() == MVT::f64);
6038
6039   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6040   // clean.  Some of them require two branches to implement.
6041   AArch64CC::CondCode CC1, CC2;
6042   bool ShouldInvert;
6043   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6044
6045   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6046   SDValue Cmp =
6047       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
6048   if (!Cmp.getNode())
6049     return SDValue();
6050
6051   if (CC2 != AArch64CC::AL) {
6052     SDValue Cmp2 =
6053         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
6054     if (!Cmp2.getNode())
6055       return SDValue();
6056
6057     Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
6058   }
6059
6060   if (ShouldInvert)
6061     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6062
6063   return Cmp;
6064 }
6065
6066 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6067 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6068 /// specified in the intrinsic calls.
6069 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6070                                                const CallInst &I,
6071                                                unsigned Intrinsic) const {
6072   switch (Intrinsic) {
6073   case Intrinsic::aarch64_neon_ld2:
6074   case Intrinsic::aarch64_neon_ld3:
6075   case Intrinsic::aarch64_neon_ld4:
6076   case Intrinsic::aarch64_neon_ld1x2:
6077   case Intrinsic::aarch64_neon_ld1x3:
6078   case Intrinsic::aarch64_neon_ld1x4:
6079   case Intrinsic::aarch64_neon_ld2lane:
6080   case Intrinsic::aarch64_neon_ld3lane:
6081   case Intrinsic::aarch64_neon_ld4lane:
6082   case Intrinsic::aarch64_neon_ld2r:
6083   case Intrinsic::aarch64_neon_ld3r:
6084   case Intrinsic::aarch64_neon_ld4r: {
6085     Info.opc = ISD::INTRINSIC_W_CHAIN;
6086     // Conservatively set memVT to the entire set of vectors loaded.
6087     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6088     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6089     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6090     Info.offset = 0;
6091     Info.align = 0;
6092     Info.vol = false; // volatile loads with NEON intrinsics not supported
6093     Info.readMem = true;
6094     Info.writeMem = false;
6095     return true;
6096   }
6097   case Intrinsic::aarch64_neon_st2:
6098   case Intrinsic::aarch64_neon_st3:
6099   case Intrinsic::aarch64_neon_st4:
6100   case Intrinsic::aarch64_neon_st1x2:
6101   case Intrinsic::aarch64_neon_st1x3:
6102   case Intrinsic::aarch64_neon_st1x4:
6103   case Intrinsic::aarch64_neon_st2lane:
6104   case Intrinsic::aarch64_neon_st3lane:
6105   case Intrinsic::aarch64_neon_st4lane: {
6106     Info.opc = ISD::INTRINSIC_VOID;
6107     // Conservatively set memVT to the entire set of vectors stored.
6108     unsigned NumElts = 0;
6109     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6110       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6111       if (!ArgTy->isVectorTy())
6112         break;
6113       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6114     }
6115     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6116     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6117     Info.offset = 0;
6118     Info.align = 0;
6119     Info.vol = false; // volatile stores with NEON intrinsics not supported
6120     Info.readMem = false;
6121     Info.writeMem = true;
6122     return true;
6123   }
6124   case Intrinsic::aarch64_ldaxr:
6125   case Intrinsic::aarch64_ldxr: {
6126     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6127     Info.opc = ISD::INTRINSIC_W_CHAIN;
6128     Info.memVT = MVT::getVT(PtrTy->getElementType());
6129     Info.ptrVal = I.getArgOperand(0);
6130     Info.offset = 0;
6131     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6132     Info.vol = true;
6133     Info.readMem = true;
6134     Info.writeMem = false;
6135     return true;
6136   }
6137   case Intrinsic::aarch64_stlxr:
6138   case Intrinsic::aarch64_stxr: {
6139     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6140     Info.opc = ISD::INTRINSIC_W_CHAIN;
6141     Info.memVT = MVT::getVT(PtrTy->getElementType());
6142     Info.ptrVal = I.getArgOperand(1);
6143     Info.offset = 0;
6144     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6145     Info.vol = true;
6146     Info.readMem = false;
6147     Info.writeMem = true;
6148     return true;
6149   }
6150   case Intrinsic::aarch64_ldaxp:
6151   case Intrinsic::aarch64_ldxp: {
6152     Info.opc = ISD::INTRINSIC_W_CHAIN;
6153     Info.memVT = MVT::i128;
6154     Info.ptrVal = I.getArgOperand(0);
6155     Info.offset = 0;
6156     Info.align = 16;
6157     Info.vol = true;
6158     Info.readMem = true;
6159     Info.writeMem = false;
6160     return true;
6161   }
6162   case Intrinsic::aarch64_stlxp:
6163   case Intrinsic::aarch64_stxp: {
6164     Info.opc = ISD::INTRINSIC_W_CHAIN;
6165     Info.memVT = MVT::i128;
6166     Info.ptrVal = I.getArgOperand(2);
6167     Info.offset = 0;
6168     Info.align = 16;
6169     Info.vol = true;
6170     Info.readMem = false;
6171     Info.writeMem = true;
6172     return true;
6173   }
6174   default:
6175     break;
6176   }
6177
6178   return false;
6179 }
6180
6181 // Truncations from 64-bit GPR to 32-bit GPR is free.
6182 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6183   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6184     return false;
6185   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6186   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6187   return NumBits1 > NumBits2;
6188 }
6189 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6190   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6191     return false;
6192   unsigned NumBits1 = VT1.getSizeInBits();
6193   unsigned NumBits2 = VT2.getSizeInBits();
6194   return NumBits1 > NumBits2;
6195 }
6196
6197 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6198 // 64-bit GPR.
6199 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6200   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6201     return false;
6202   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6203   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6204   return NumBits1 == 32 && NumBits2 == 64;
6205 }
6206 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6207   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6208     return false;
6209   unsigned NumBits1 = VT1.getSizeInBits();
6210   unsigned NumBits2 = VT2.getSizeInBits();
6211   return NumBits1 == 32 && NumBits2 == 64;
6212 }
6213
6214 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6215   EVT VT1 = Val.getValueType();
6216   if (isZExtFree(VT1, VT2)) {
6217     return true;
6218   }
6219
6220   if (Val.getOpcode() != ISD::LOAD)
6221     return false;
6222
6223   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6224   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6225           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6226           VT1.getSizeInBits() <= 32);
6227 }
6228
6229 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6230                                           unsigned &RequiredAligment) const {
6231   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6232     return false;
6233   // Cyclone supports unaligned accesses.
6234   RequiredAligment = 0;
6235   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6236   return NumBits == 32 || NumBits == 64;
6237 }
6238
6239 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6240                                           unsigned &RequiredAligment) const {
6241   if (!LoadedType.isSimple() ||
6242       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6243     return false;
6244   // Cyclone supports unaligned accesses.
6245   RequiredAligment = 0;
6246   unsigned NumBits = LoadedType.getSizeInBits();
6247   return NumBits == 32 || NumBits == 64;
6248 }
6249
6250 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6251                        unsigned AlignCheck) {
6252   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6253           (DstAlign == 0 || DstAlign % AlignCheck == 0));
6254 }
6255
6256 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6257                                                unsigned SrcAlign, bool IsMemset,
6258                                                bool ZeroMemset,
6259                                                bool MemcpyStrSrc,
6260                                                MachineFunction &MF) const {
6261   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6262   // instruction to materialize the v2i64 zero and one store (with restrictive
6263   // addressing mode). Just do two i64 store of zero-registers.
6264   bool Fast;
6265   const Function *F = MF.getFunction();
6266   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6267       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6268                                        Attribute::NoImplicitFloat) &&
6269       (memOpAlign(SrcAlign, DstAlign, 16) ||
6270        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6271     return MVT::f128;
6272
6273   return Size >= 8 ? MVT::i64 : MVT::i32;
6274 }
6275
6276 // 12-bit optionally shifted immediates are legal for adds.
6277 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6278   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6279     return true;
6280   return false;
6281 }
6282
6283 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6284 // immediates is the same as for an add or a sub.
6285 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6286   if (Immed < 0)
6287     Immed *= -1;
6288   return isLegalAddImmediate(Immed);
6289 }
6290
6291 /// isLegalAddressingMode - Return true if the addressing mode represented
6292 /// by AM is legal for this target, for a load/store of the specified type.
6293 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6294                                                   Type *Ty) const {
6295   // AArch64 has five basic addressing modes:
6296   //  reg
6297   //  reg + 9-bit signed offset
6298   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
6299   //  reg1 + reg2
6300   //  reg + SIZE_IN_BYTES * reg
6301
6302   // No global is ever allowed as a base.
6303   if (AM.BaseGV)
6304     return false;
6305
6306   // No reg+reg+imm addressing.
6307   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6308     return false;
6309
6310   // check reg + imm case:
6311   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6312   uint64_t NumBytes = 0;
6313   if (Ty->isSized()) {
6314     uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6315     NumBytes = NumBits / 8;
6316     if (!isPowerOf2_64(NumBits))
6317       NumBytes = 0;
6318   }
6319
6320   if (!AM.Scale) {
6321     int64_t Offset = AM.BaseOffs;
6322
6323     // 9-bit signed offset
6324     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6325       return true;
6326
6327     // 12-bit unsigned offset
6328     unsigned shift = Log2_64(NumBytes);
6329     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6330         // Must be a multiple of NumBytes (NumBytes is a power of 2)
6331         (Offset >> shift) << shift == Offset)
6332       return true;
6333     return false;
6334   }
6335
6336   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6337
6338   if (!AM.Scale || AM.Scale == 1 ||
6339       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6340     return true;
6341   return false;
6342 }
6343
6344 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6345                                                 Type *Ty) const {
6346   // Scaling factors are not free at all.
6347   // Operands                     | Rt Latency
6348   // -------------------------------------------
6349   // Rt, [Xn, Xm]                 | 4
6350   // -------------------------------------------
6351   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
6352   // Rt, [Xn, Wm, <extend> #imm]  |
6353   if (isLegalAddressingMode(AM, Ty))
6354     // Scale represents reg2 * scale, thus account for 1 if
6355     // it is not equal to 0 or 1.
6356     return AM.Scale != 0 && AM.Scale != 1;
6357   return -1;
6358 }
6359
6360 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6361   VT = VT.getScalarType();
6362
6363   if (!VT.isSimple())
6364     return false;
6365
6366   switch (VT.getSimpleVT().SimpleTy) {
6367   case MVT::f32:
6368   case MVT::f64:
6369     return true;
6370   default:
6371     break;
6372   }
6373
6374   return false;
6375 }
6376
6377 const MCPhysReg *
6378 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6379   // LR is a callee-save register, but we must treat it as clobbered by any call
6380   // site. Hence we include LR in the scratch registers, which are in turn added
6381   // as implicit-defs for stackmaps and patchpoints.
6382   static const MCPhysReg ScratchRegs[] = {
6383     AArch64::X16, AArch64::X17, AArch64::LR, 0
6384   };
6385   return ScratchRegs;
6386 }
6387
6388 bool
6389 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6390   EVT VT = N->getValueType(0);
6391     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6392     // it with shift to let it be lowered to UBFX.
6393   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6394       isa<ConstantSDNode>(N->getOperand(1))) {
6395     uint64_t TruncMask = N->getConstantOperandVal(1);
6396     if (isMask_64(TruncMask) &&
6397       N->getOperand(0).getOpcode() == ISD::SRL &&
6398       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6399       return false;
6400   }
6401   return true;
6402 }
6403
6404 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6405                                                               Type *Ty) const {
6406   assert(Ty->isIntegerTy());
6407
6408   unsigned BitSize = Ty->getPrimitiveSizeInBits();
6409   if (BitSize == 0)
6410     return false;
6411
6412   int64_t Val = Imm.getSExtValue();
6413   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6414     return true;
6415
6416   if ((int64_t)Val < 0)
6417     Val = ~Val;
6418   if (BitSize == 32)
6419     Val &= (1LL << 32) - 1;
6420
6421   unsigned LZ = countLeadingZeros((uint64_t)Val);
6422   unsigned Shift = (63 - LZ) / 16;
6423   // MOVZ is free so return true for one or fewer MOVK.
6424   return (Shift < 3) ? true : false;
6425 }
6426
6427 // Generate SUBS and CSEL for integer abs.
6428 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6429   EVT VT = N->getValueType(0);
6430
6431   SDValue N0 = N->getOperand(0);
6432   SDValue N1 = N->getOperand(1);
6433   SDLoc DL(N);
6434
6435   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6436   // and change it to SUB and CSEL.
6437   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6438       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6439       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6440     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6441       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6442         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6443                                   N0.getOperand(0));
6444         // Generate SUBS & CSEL.
6445         SDValue Cmp =
6446             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6447                         N0.getOperand(0), DAG.getConstant(0, VT));
6448         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6449                            DAG.getConstant(AArch64CC::PL, MVT::i32),
6450                            SDValue(Cmp.getNode(), 1));
6451       }
6452   return SDValue();
6453 }
6454
6455 // performXorCombine - Attempts to handle integer ABS.
6456 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6457                                  TargetLowering::DAGCombinerInfo &DCI,
6458                                  const AArch64Subtarget *Subtarget) {
6459   if (DCI.isBeforeLegalizeOps())
6460     return SDValue();
6461
6462   return performIntegerAbsCombine(N, DAG);
6463 }
6464
6465 SDValue
6466 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6467                                      SelectionDAG &DAG,
6468                                      std::vector<SDNode *> *Created) const {
6469   // fold (sdiv X, pow2)
6470   EVT VT = N->getValueType(0);
6471   if ((VT != MVT::i32 && VT != MVT::i64) ||
6472       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6473     return SDValue();
6474
6475   SDLoc DL(N);
6476   SDValue N0 = N->getOperand(0);
6477   unsigned Lg2 = Divisor.countTrailingZeros();
6478   SDValue Zero = DAG.getConstant(0, VT);
6479   SDValue Pow2MinusOne = DAG.getConstant((1 << Lg2) - 1, VT);
6480
6481   // Add (N0 < 0) ? Pow2 - 1 : 0;
6482   SDValue CCVal;
6483   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6484   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6485   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6486
6487   if (Created) {
6488     Created->push_back(Cmp.getNode());
6489     Created->push_back(Add.getNode());
6490     Created->push_back(CSel.getNode());
6491   }
6492
6493   // Divide by pow2.
6494   SDValue SRA =
6495       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, MVT::i64));
6496
6497   // If we're dividing by a positive value, we're done.  Otherwise, we must
6498   // negate the result.
6499   if (Divisor.isNonNegative())
6500     return SRA;
6501
6502   if (Created)
6503     Created->push_back(SRA.getNode());
6504   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), SRA);
6505 }
6506
6507 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6508                                  TargetLowering::DAGCombinerInfo &DCI,
6509                                  const AArch64Subtarget *Subtarget) {
6510   if (DCI.isBeforeLegalizeOps())
6511     return SDValue();
6512
6513   // Multiplication of a power of two plus/minus one can be done more
6514   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6515   // future CPUs have a cheaper MADD instruction, this may need to be
6516   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6517   // 64-bit is 5 cycles, so this is always a win.
6518   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6519     APInt Value = C->getAPIntValue();
6520     EVT VT = N->getValueType(0);
6521     if (Value.isNonNegative()) {
6522       // (mul x, 2^N + 1) => (add (shl x, N), x)
6523       APInt VM1 = Value - 1;
6524       if (VM1.isPowerOf2()) {
6525         SDValue ShiftedVal =
6526             DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6527                         DAG.getConstant(VM1.logBase2(), MVT::i64));
6528         return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal,
6529                            N->getOperand(0));
6530       }
6531       // (mul x, 2^N - 1) => (sub (shl x, N), x)
6532       APInt VP1 = Value + 1;
6533       if (VP1.isPowerOf2()) {
6534         SDValue ShiftedVal =
6535             DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6536                         DAG.getConstant(VP1.logBase2(), MVT::i64));
6537         return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal,
6538                            N->getOperand(0));
6539       }
6540     } else {
6541       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6542       APInt VNM1 = -Value - 1;
6543       if (VNM1.isPowerOf2()) {
6544         SDValue ShiftedVal =
6545             DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6546                         DAG.getConstant(VNM1.logBase2(), MVT::i64));
6547         SDValue Add =
6548             DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6549         return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), Add);
6550       }
6551       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6552       APInt VNP1 = -Value + 1;
6553       if (VNP1.isPowerOf2()) {
6554         SDValue ShiftedVal =
6555             DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6556                         DAG.getConstant(VNP1.logBase2(), MVT::i64));
6557         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N->getOperand(0),
6558                            ShiftedVal);
6559       }
6560     }
6561   }
6562   return SDValue();
6563 }
6564
6565 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
6566                                                          SelectionDAG &DAG) {
6567   // Take advantage of vector comparisons producing 0 or -1 in each lane to
6568   // optimize away operation when it's from a constant.
6569   //
6570   // The general transformation is:
6571   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
6572   //       AND(VECTOR_CMP(x,y), constant2)
6573   //    constant2 = UNARYOP(constant)
6574
6575   // Early exit if this isn't a vector operation, the operand of the
6576   // unary operation isn't a bitwise AND, or if the sizes of the operations
6577   // aren't the same.
6578   EVT VT = N->getValueType(0);
6579   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
6580       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
6581       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
6582     return SDValue();
6583
6584   // Now check that the other operand of the AND is a constant. We could
6585   // make the transformation for non-constant splats as well, but it's unclear
6586   // that would be a benefit as it would not eliminate any operations, just
6587   // perform one more step in scalar code before moving to the vector unit.
6588   if (BuildVectorSDNode *BV =
6589           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
6590     // Bail out if the vector isn't a constant.
6591     if (!BV->isConstant())
6592       return SDValue();
6593
6594     // Everything checks out. Build up the new and improved node.
6595     SDLoc DL(N);
6596     EVT IntVT = BV->getValueType(0);
6597     // Create a new constant of the appropriate type for the transformed
6598     // DAG.
6599     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
6600     // The AND node needs bitcasts to/from an integer vector type around it.
6601     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
6602     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
6603                                  N->getOperand(0)->getOperand(0), MaskConst);
6604     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
6605     return Res;
6606   }
6607
6608   return SDValue();
6609 }
6610
6611 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6612   // First try to optimize away the conversion when it's conditionally from
6613   // a constant. Vectors only.
6614   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
6615   if (Res != SDValue())
6616     return Res;
6617
6618   EVT VT = N->getValueType(0);
6619   if (VT != MVT::f32 && VT != MVT::f64)
6620     return SDValue();
6621
6622   // Only optimize when the source and destination types have the same width.
6623   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6624     return SDValue();
6625
6626   // If the result of an integer load is only used by an integer-to-float
6627   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6628   // This eliminates an "integer-to-vector-move UOP and improve throughput.
6629   SDValue N0 = N->getOperand(0);
6630   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6631       // Do not change the width of a volatile load.
6632       !cast<LoadSDNode>(N0)->isVolatile()) {
6633     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6634     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6635                                LN0->getPointerInfo(), LN0->isVolatile(),
6636                                LN0->isNonTemporal(), LN0->isInvariant(),
6637                                LN0->getAlignment());
6638
6639     // Make sure successors of the original load stay after it by updating them
6640     // to use the new Chain.
6641     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6642
6643     unsigned Opcode =
6644         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
6645     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6646   }
6647
6648   return SDValue();
6649 }
6650
6651 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6652 /// searches for and classifies those shifts.
6653 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6654                          bool &FromHi) {
6655   if (N.getOpcode() == ISD::SHL)
6656     FromHi = false;
6657   else if (N.getOpcode() == ISD::SRL)
6658     FromHi = true;
6659   else
6660     return false;
6661
6662   if (!isa<ConstantSDNode>(N.getOperand(1)))
6663     return false;
6664
6665   ShiftAmount = N->getConstantOperandVal(1);
6666   Src = N->getOperand(0);
6667   return true;
6668 }
6669
6670 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6671 /// registers viewed as a high/low pair. This function looks for the pattern:
6672 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6673 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6674 /// independent.
6675 static SDValue tryCombineToEXTR(SDNode *N,
6676                                 TargetLowering::DAGCombinerInfo &DCI) {
6677   SelectionDAG &DAG = DCI.DAG;
6678   SDLoc DL(N);
6679   EVT VT = N->getValueType(0);
6680
6681   assert(N->getOpcode() == ISD::OR && "Unexpected root");
6682
6683   if (VT != MVT::i32 && VT != MVT::i64)
6684     return SDValue();
6685
6686   SDValue LHS;
6687   uint32_t ShiftLHS = 0;
6688   bool LHSFromHi = 0;
6689   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6690     return SDValue();
6691
6692   SDValue RHS;
6693   uint32_t ShiftRHS = 0;
6694   bool RHSFromHi = 0;
6695   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6696     return SDValue();
6697
6698   // If they're both trying to come from the high part of the register, they're
6699   // not really an EXTR.
6700   if (LHSFromHi == RHSFromHi)
6701     return SDValue();
6702
6703   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6704     return SDValue();
6705
6706   if (LHSFromHi) {
6707     std::swap(LHS, RHS);
6708     std::swap(ShiftLHS, ShiftRHS);
6709   }
6710
6711   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
6712                      DAG.getConstant(ShiftRHS, MVT::i64));
6713 }
6714
6715 static SDValue tryCombineToBSL(SDNode *N,
6716                                 TargetLowering::DAGCombinerInfo &DCI) {
6717   EVT VT = N->getValueType(0);
6718   SelectionDAG &DAG = DCI.DAG;
6719   SDLoc DL(N);
6720
6721   if (!VT.isVector())
6722     return SDValue();
6723
6724   SDValue N0 = N->getOperand(0);
6725   if (N0.getOpcode() != ISD::AND)
6726     return SDValue();
6727
6728   SDValue N1 = N->getOperand(1);
6729   if (N1.getOpcode() != ISD::AND)
6730     return SDValue();
6731
6732   // We only have to look for constant vectors here since the general, variable
6733   // case can be handled in TableGen.
6734   unsigned Bits = VT.getVectorElementType().getSizeInBits();
6735   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6736   for (int i = 1; i >= 0; --i)
6737     for (int j = 1; j >= 0; --j) {
6738       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6739       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6740       if (!BVN0 || !BVN1)
6741         continue;
6742
6743       bool FoundMatch = true;
6744       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6745         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6746         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6747         if (!CN0 || !CN1 ||
6748             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6749           FoundMatch = false;
6750           break;
6751         }
6752       }
6753
6754       if (FoundMatch)
6755         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6756                            N0->getOperand(1 - i), N1->getOperand(1 - j));
6757     }
6758
6759   return SDValue();
6760 }
6761
6762 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6763                                 const AArch64Subtarget *Subtarget) {
6764   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6765   if (!EnableAArch64ExtrGeneration)
6766     return SDValue();
6767   SelectionDAG &DAG = DCI.DAG;
6768   EVT VT = N->getValueType(0);
6769
6770   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6771     return SDValue();
6772
6773   SDValue Res = tryCombineToEXTR(N, DCI);
6774   if (Res.getNode())
6775     return Res;
6776
6777   Res = tryCombineToBSL(N, DCI);
6778   if (Res.getNode())
6779     return Res;
6780
6781   return SDValue();
6782 }
6783
6784 static SDValue performBitcastCombine(SDNode *N,
6785                                      TargetLowering::DAGCombinerInfo &DCI,
6786                                      SelectionDAG &DAG) {
6787   // Wait 'til after everything is legalized to try this. That way we have
6788   // legal vector types and such.
6789   if (DCI.isBeforeLegalizeOps())
6790     return SDValue();
6791
6792   // Remove extraneous bitcasts around an extract_subvector.
6793   // For example,
6794   //    (v4i16 (bitconvert
6795   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6796   //  becomes
6797   //    (extract_subvector ((v8i16 ...), (i64 4)))
6798
6799   // Only interested in 64-bit vectors as the ultimate result.
6800   EVT VT = N->getValueType(0);
6801   if (!VT.isVector())
6802     return SDValue();
6803   if (VT.getSimpleVT().getSizeInBits() != 64)
6804     return SDValue();
6805   // Is the operand an extract_subvector starting at the beginning or halfway
6806   // point of the vector? A low half may also come through as an
6807   // EXTRACT_SUBREG, so look for that, too.
6808   SDValue Op0 = N->getOperand(0);
6809   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6810       !(Op0->isMachineOpcode() &&
6811         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
6812     return SDValue();
6813   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6814   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6815     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6816       return SDValue();
6817   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
6818     if (idx != AArch64::dsub)
6819       return SDValue();
6820     // The dsub reference is equivalent to a lane zero subvector reference.
6821     idx = 0;
6822   }
6823   // Look through the bitcast of the input to the extract.
6824   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6825     return SDValue();
6826   SDValue Source = Op0->getOperand(0)->getOperand(0);
6827   // If the source type has twice the number of elements as our destination
6828   // type, we know this is an extract of the high or low half of the vector.
6829   EVT SVT = Source->getValueType(0);
6830   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6831     return SDValue();
6832
6833   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
6834
6835   // Create the simplified form to just extract the low or high half of the
6836   // vector directly rather than bothering with the bitcasts.
6837   SDLoc dl(N);
6838   unsigned NumElements = VT.getVectorNumElements();
6839   if (idx) {
6840     SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6841     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6842   } else {
6843     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, MVT::i32);
6844     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6845                                       Source, SubReg),
6846                    0);
6847   }
6848 }
6849
6850 static SDValue performConcatVectorsCombine(SDNode *N,
6851                                            TargetLowering::DAGCombinerInfo &DCI,
6852                                            SelectionDAG &DAG) {
6853   // Wait 'til after everything is legalized to try this. That way we have
6854   // legal vector types and such.
6855   if (DCI.isBeforeLegalizeOps())
6856     return SDValue();
6857
6858   SDLoc dl(N);
6859   EVT VT = N->getValueType(0);
6860
6861   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6862   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6863   // canonicalise to that.
6864   if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6865     assert(VT.getVectorElementType().getSizeInBits() == 64);
6866     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT,
6867                        WidenVector(N->getOperand(0), DAG),
6868                        DAG.getConstant(0, MVT::i64));
6869   }
6870
6871   // Canonicalise concat_vectors so that the right-hand vector has as few
6872   // bit-casts as possible before its real operation. The primary matching
6873   // destination for these operations will be the narrowing "2" instructions,
6874   // which depend on the operation being performed on this right-hand vector.
6875   // For example,
6876   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
6877   // becomes
6878   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6879
6880   SDValue Op1 = N->getOperand(1);
6881   if (Op1->getOpcode() != ISD::BITCAST)
6882     return SDValue();
6883   SDValue RHS = Op1->getOperand(0);
6884   MVT RHSTy = RHS.getValueType().getSimpleVT();
6885   // If the RHS is not a vector, this is not the pattern we're looking for.
6886   if (!RHSTy.isVector())
6887     return SDValue();
6888
6889   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
6890
6891   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6892                                   RHSTy.getVectorNumElements() * 2);
6893   return DAG.getNode(
6894       ISD::BITCAST, dl, VT,
6895       DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6896                   DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6897 }
6898
6899 static SDValue tryCombineFixedPointConvert(SDNode *N,
6900                                            TargetLowering::DAGCombinerInfo &DCI,
6901                                            SelectionDAG &DAG) {
6902   // Wait 'til after everything is legalized to try this. That way we have
6903   // legal vector types and such.
6904   if (DCI.isBeforeLegalizeOps())
6905     return SDValue();
6906   // Transform a scalar conversion of a value from a lane extract into a
6907   // lane extract of a vector conversion. E.g., from foo1 to foo2:
6908   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6909   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6910   //
6911   // The second form interacts better with instruction selection and the
6912   // register allocator to avoid cross-class register copies that aren't
6913   // coalescable due to a lane reference.
6914
6915   // Check the operand and see if it originates from a lane extract.
6916   SDValue Op1 = N->getOperand(1);
6917   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6918     // Yep, no additional predication needed. Perform the transform.
6919     SDValue IID = N->getOperand(0);
6920     SDValue Shift = N->getOperand(2);
6921     SDValue Vec = Op1.getOperand(0);
6922     SDValue Lane = Op1.getOperand(1);
6923     EVT ResTy = N->getValueType(0);
6924     EVT VecResTy;
6925     SDLoc DL(N);
6926
6927     // The vector width should be 128 bits by the time we get here, even
6928     // if it started as 64 bits (the extract_vector handling will have
6929     // done so).
6930     assert(Vec.getValueType().getSizeInBits() == 128 &&
6931            "unexpected vector size on extract_vector_elt!");
6932     if (Vec.getValueType() == MVT::v4i32)
6933       VecResTy = MVT::v4f32;
6934     else if (Vec.getValueType() == MVT::v2i64)
6935       VecResTy = MVT::v2f64;
6936     else
6937       llvm_unreachable("unexpected vector type!");
6938
6939     SDValue Convert =
6940         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6941     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6942   }
6943   return SDValue();
6944 }
6945
6946 // AArch64 high-vector "long" operations are formed by performing the non-high
6947 // version on an extract_subvector of each operand which gets the high half:
6948 //
6949 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6950 //
6951 // However, there are cases which don't have an extract_high explicitly, but
6952 // have another operation that can be made compatible with one for free. For
6953 // example:
6954 //
6955 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
6956 //
6957 // This routine does the actual conversion of such DUPs, once outer routines
6958 // have determined that everything else is in order.
6959 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6960   // We can handle most types of duplicate, but the lane ones have an extra
6961   // operand saying *which* lane, so we need to know.
6962   bool IsDUPLANE;
6963   switch (N.getOpcode()) {
6964   case AArch64ISD::DUP:
6965     IsDUPLANE = false;
6966     break;
6967   case AArch64ISD::DUPLANE8:
6968   case AArch64ISD::DUPLANE16:
6969   case AArch64ISD::DUPLANE32:
6970   case AArch64ISD::DUPLANE64:
6971     IsDUPLANE = true;
6972     break;
6973   default:
6974     return SDValue();
6975   }
6976
6977   MVT NarrowTy = N.getSimpleValueType();
6978   if (!NarrowTy.is64BitVector())
6979     return SDValue();
6980
6981   MVT ElementTy = NarrowTy.getVectorElementType();
6982   unsigned NumElems = NarrowTy.getVectorNumElements();
6983   MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6984
6985   SDValue NewDUP;
6986   if (IsDUPLANE)
6987     NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6988                          N.getOperand(1));
6989   else
6990     NewDUP = DAG.getNode(AArch64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6991
6992   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6993                      NewDUP, DAG.getConstant(NumElems, MVT::i64));
6994 }
6995
6996 static bool isEssentiallyExtractSubvector(SDValue N) {
6997   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6998     return true;
6999
7000   return N.getOpcode() == ISD::BITCAST &&
7001          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7002 }
7003
7004 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7005 struct GenericSetCCInfo {
7006   const SDValue *Opnd0;
7007   const SDValue *Opnd1;
7008   ISD::CondCode CC;
7009 };
7010
7011 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7012 struct AArch64SetCCInfo {
7013   const SDValue *Cmp;
7014   AArch64CC::CondCode CC;
7015 };
7016
7017 /// \brief Helper structure to keep track of SetCC information.
7018 union SetCCInfo {
7019   GenericSetCCInfo Generic;
7020   AArch64SetCCInfo AArch64;
7021 };
7022
7023 /// \brief Helper structure to be able to read SetCC information.  If set to
7024 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7025 /// GenericSetCCInfo.
7026 struct SetCCInfoAndKind {
7027   SetCCInfo Info;
7028   bool IsAArch64;
7029 };
7030
7031 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7032 /// an
7033 /// AArch64 lowered one.
7034 /// \p SetCCInfo is filled accordingly.
7035 /// \post SetCCInfo is meanginfull only when this function returns true.
7036 /// \return True when Op is a kind of SET_CC operation.
7037 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7038   // If this is a setcc, this is straight forward.
7039   if (Op.getOpcode() == ISD::SETCC) {
7040     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7041     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7042     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7043     SetCCInfo.IsAArch64 = false;
7044     return true;
7045   }
7046   // Otherwise, check if this is a matching csel instruction.
7047   // In other words:
7048   // - csel 1, 0, cc
7049   // - csel 0, 1, !cc
7050   if (Op.getOpcode() != AArch64ISD::CSEL)
7051     return false;
7052   // Set the information about the operands.
7053   // TODO: we want the operands of the Cmp not the csel
7054   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7055   SetCCInfo.IsAArch64 = true;
7056   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7057       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7058
7059   // Check that the operands matches the constraints:
7060   // (1) Both operands must be constants.
7061   // (2) One must be 1 and the other must be 0.
7062   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7063   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7064
7065   // Check (1).
7066   if (!TValue || !FValue)
7067     return false;
7068
7069   // Check (2).
7070   if (!TValue->isOne()) {
7071     // Update the comparison when we are interested in !cc.
7072     std::swap(TValue, FValue);
7073     SetCCInfo.Info.AArch64.CC =
7074         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7075   }
7076   return TValue->isOne() && FValue->isNullValue();
7077 }
7078
7079 // Returns true if Op is setcc or zext of setcc.
7080 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7081   if (isSetCC(Op, Info))
7082     return true;
7083   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7084     isSetCC(Op->getOperand(0), Info));
7085 }
7086
7087 // The folding we want to perform is:
7088 // (add x, [zext] (setcc cc ...) )
7089 //   -->
7090 // (csel x, (add x, 1), !cc ...)
7091 //
7092 // The latter will get matched to a CSINC instruction.
7093 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7094   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7095   SDValue LHS = Op->getOperand(0);
7096   SDValue RHS = Op->getOperand(1);
7097   SetCCInfoAndKind InfoAndKind;
7098
7099   // If neither operand is a SET_CC, give up.
7100   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7101     std::swap(LHS, RHS);
7102     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7103       return SDValue();
7104   }
7105
7106   // FIXME: This could be generatized to work for FP comparisons.
7107   EVT CmpVT = InfoAndKind.IsAArch64
7108                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7109                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
7110   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7111     return SDValue();
7112
7113   SDValue CCVal;
7114   SDValue Cmp;
7115   SDLoc dl(Op);
7116   if (InfoAndKind.IsAArch64) {
7117     CCVal = DAG.getConstant(
7118         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), MVT::i32);
7119     Cmp = *InfoAndKind.Info.AArch64.Cmp;
7120   } else
7121     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7122                       *InfoAndKind.Info.Generic.Opnd1,
7123                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7124                       CCVal, DAG, dl);
7125
7126   EVT VT = Op->getValueType(0);
7127   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
7128   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7129 }
7130
7131 // The basic add/sub long vector instructions have variants with "2" on the end
7132 // which act on the high-half of their inputs. They are normally matched by
7133 // patterns like:
7134 //
7135 // (add (zeroext (extract_high LHS)),
7136 //      (zeroext (extract_high RHS)))
7137 // -> uaddl2 vD, vN, vM
7138 //
7139 // However, if one of the extracts is something like a duplicate, this
7140 // instruction can still be used profitably. This function puts the DAG into a
7141 // more appropriate form for those patterns to trigger.
7142 static SDValue performAddSubLongCombine(SDNode *N,
7143                                         TargetLowering::DAGCombinerInfo &DCI,
7144                                         SelectionDAG &DAG) {
7145   if (DCI.isBeforeLegalizeOps())
7146     return SDValue();
7147
7148   MVT VT = N->getSimpleValueType(0);
7149   if (!VT.is128BitVector()) {
7150     if (N->getOpcode() == ISD::ADD)
7151       return performSetccAddFolding(N, DAG);
7152     return SDValue();
7153   }
7154
7155   // Make sure both branches are extended in the same way.
7156   SDValue LHS = N->getOperand(0);
7157   SDValue RHS = N->getOperand(1);
7158   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7159        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7160       LHS.getOpcode() != RHS.getOpcode())
7161     return SDValue();
7162
7163   unsigned ExtType = LHS.getOpcode();
7164
7165   // It's not worth doing if at least one of the inputs isn't already an
7166   // extract, but we don't know which it'll be so we have to try both.
7167   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7168     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7169     if (!RHS.getNode())
7170       return SDValue();
7171
7172     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7173   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7174     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7175     if (!LHS.getNode())
7176       return SDValue();
7177
7178     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7179   }
7180
7181   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7182 }
7183
7184 // Massage DAGs which we can use the high-half "long" operations on into
7185 // something isel will recognize better. E.g.
7186 //
7187 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7188 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
7189 //                     (extract_high (v2i64 (dup128 scalar)))))
7190 //
7191 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7192                                        TargetLowering::DAGCombinerInfo &DCI,
7193                                        SelectionDAG &DAG) {
7194   if (DCI.isBeforeLegalizeOps())
7195     return SDValue();
7196
7197   SDValue LHS = N->getOperand(1);
7198   SDValue RHS = N->getOperand(2);
7199   assert(LHS.getValueType().is64BitVector() &&
7200          RHS.getValueType().is64BitVector() &&
7201          "unexpected shape for long operation");
7202
7203   // Either node could be a DUP, but it's not worth doing both of them (you'd
7204   // just as well use the non-high version) so look for a corresponding extract
7205   // operation on the other "wing".
7206   if (isEssentiallyExtractSubvector(LHS)) {
7207     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7208     if (!RHS.getNode())
7209       return SDValue();
7210   } else if (isEssentiallyExtractSubvector(RHS)) {
7211     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7212     if (!LHS.getNode())
7213       return SDValue();
7214   }
7215
7216   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7217                      N->getOperand(0), LHS, RHS);
7218 }
7219
7220 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7221   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7222   unsigned ElemBits = ElemTy.getSizeInBits();
7223
7224   int64_t ShiftAmount;
7225   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7226     APInt SplatValue, SplatUndef;
7227     unsigned SplatBitSize;
7228     bool HasAnyUndefs;
7229     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7230                               HasAnyUndefs, ElemBits) ||
7231         SplatBitSize != ElemBits)
7232       return SDValue();
7233
7234     ShiftAmount = SplatValue.getSExtValue();
7235   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7236     ShiftAmount = CVN->getSExtValue();
7237   } else
7238     return SDValue();
7239
7240   unsigned Opcode;
7241   bool IsRightShift;
7242   switch (IID) {
7243   default:
7244     llvm_unreachable("Unknown shift intrinsic");
7245   case Intrinsic::aarch64_neon_sqshl:
7246     Opcode = AArch64ISD::SQSHL_I;
7247     IsRightShift = false;
7248     break;
7249   case Intrinsic::aarch64_neon_uqshl:
7250     Opcode = AArch64ISD::UQSHL_I;
7251     IsRightShift = false;
7252     break;
7253   case Intrinsic::aarch64_neon_srshl:
7254     Opcode = AArch64ISD::SRSHR_I;
7255     IsRightShift = true;
7256     break;
7257   case Intrinsic::aarch64_neon_urshl:
7258     Opcode = AArch64ISD::URSHR_I;
7259     IsRightShift = true;
7260     break;
7261   case Intrinsic::aarch64_neon_sqshlu:
7262     Opcode = AArch64ISD::SQSHLU_I;
7263     IsRightShift = false;
7264     break;
7265   }
7266
7267   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
7268     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7269                        DAG.getConstant(-ShiftAmount, MVT::i32));
7270   else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits)
7271     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7272                        DAG.getConstant(ShiftAmount, MVT::i32));
7273
7274   return SDValue();
7275 }
7276
7277 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7278 // the intrinsics must be legal and take an i32, this means there's almost
7279 // certainly going to be a zext in the DAG which we can eliminate.
7280 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7281   SDValue AndN = N->getOperand(2);
7282   if (AndN.getOpcode() != ISD::AND)
7283     return SDValue();
7284
7285   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7286   if (!CMask || CMask->getZExtValue() != Mask)
7287     return SDValue();
7288
7289   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7290                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7291 }
7292
7293 static SDValue performIntrinsicCombine(SDNode *N,
7294                                        TargetLowering::DAGCombinerInfo &DCI,
7295                                        const AArch64Subtarget *Subtarget) {
7296   SelectionDAG &DAG = DCI.DAG;
7297   unsigned IID = getIntrinsicID(N);
7298   switch (IID) {
7299   default:
7300     break;
7301   case Intrinsic::aarch64_neon_vcvtfxs2fp:
7302   case Intrinsic::aarch64_neon_vcvtfxu2fp:
7303     return tryCombineFixedPointConvert(N, DCI, DAG);
7304     break;
7305   case Intrinsic::aarch64_neon_fmax:
7306     return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7307                        N->getOperand(1), N->getOperand(2));
7308   case Intrinsic::aarch64_neon_fmin:
7309     return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7310                        N->getOperand(1), N->getOperand(2));
7311   case Intrinsic::aarch64_neon_smull:
7312   case Intrinsic::aarch64_neon_umull:
7313   case Intrinsic::aarch64_neon_pmull:
7314   case Intrinsic::aarch64_neon_sqdmull:
7315     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7316   case Intrinsic::aarch64_neon_sqshl:
7317   case Intrinsic::aarch64_neon_uqshl:
7318   case Intrinsic::aarch64_neon_sqshlu:
7319   case Intrinsic::aarch64_neon_srshl:
7320   case Intrinsic::aarch64_neon_urshl:
7321     return tryCombineShiftImm(IID, N, DAG);
7322   case Intrinsic::aarch64_crc32b:
7323   case Intrinsic::aarch64_crc32cb:
7324     return tryCombineCRC32(0xff, N, DAG);
7325   case Intrinsic::aarch64_crc32h:
7326   case Intrinsic::aarch64_crc32ch:
7327     return tryCombineCRC32(0xffff, N, DAG);
7328   }
7329   return SDValue();
7330 }
7331
7332 static SDValue performExtendCombine(SDNode *N,
7333                                     TargetLowering::DAGCombinerInfo &DCI,
7334                                     SelectionDAG &DAG) {
7335   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7336   // we can convert that DUP into another extract_high (of a bigger DUP), which
7337   // helps the backend to decide that an sabdl2 would be useful, saving a real
7338   // extract_high operation.
7339   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7340       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7341     SDNode *ABDNode = N->getOperand(0).getNode();
7342     unsigned IID = getIntrinsicID(ABDNode);
7343     if (IID == Intrinsic::aarch64_neon_sabd ||
7344         IID == Intrinsic::aarch64_neon_uabd) {
7345       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7346       if (!NewABD.getNode())
7347         return SDValue();
7348
7349       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7350                          NewABD);
7351     }
7352   }
7353
7354   // This is effectively a custom type legalization for AArch64.
7355   //
7356   // Type legalization will split an extend of a small, legal, type to a larger
7357   // illegal type by first splitting the destination type, often creating
7358   // illegal source types, which then get legalized in isel-confusing ways,
7359   // leading to really terrible codegen. E.g.,
7360   //   %result = v8i32 sext v8i8 %value
7361   // becomes
7362   //   %losrc = extract_subreg %value, ...
7363   //   %hisrc = extract_subreg %value, ...
7364   //   %lo = v4i32 sext v4i8 %losrc
7365   //   %hi = v4i32 sext v4i8 %hisrc
7366   // Things go rapidly downhill from there.
7367   //
7368   // For AArch64, the [sz]ext vector instructions can only go up one element
7369   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7370   // take two instructions.
7371   //
7372   // This implies that the most efficient way to do the extend from v8i8
7373   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7374   // the normal splitting to happen for the v8i16->v8i32.
7375
7376   // This is pre-legalization to catch some cases where the default
7377   // type legalization will create ill-tempered code.
7378   if (!DCI.isBeforeLegalizeOps())
7379     return SDValue();
7380
7381   // We're only interested in cleaning things up for non-legal vector types
7382   // here. If both the source and destination are legal, things will just
7383   // work naturally without any fiddling.
7384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7385   EVT ResVT = N->getValueType(0);
7386   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7387     return SDValue();
7388   // If the vector type isn't a simple VT, it's beyond the scope of what
7389   // we're  worried about here. Let legalization do its thing and hope for
7390   // the best.
7391   if (!ResVT.isSimple())
7392     return SDValue();
7393
7394   SDValue Src = N->getOperand(0);
7395   MVT SrcVT = Src->getValueType(0).getSimpleVT();
7396   // If the source VT is a 64-bit vector, we can play games and get the
7397   // better results we want.
7398   if (SrcVT.getSizeInBits() != 64)
7399     return SDValue();
7400
7401   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7402   unsigned ElementCount = SrcVT.getVectorNumElements();
7403   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7404   SDLoc DL(N);
7405   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7406
7407   // Now split the rest of the operation into two halves, each with a 64
7408   // bit source.
7409   EVT LoVT, HiVT;
7410   SDValue Lo, Hi;
7411   unsigned NumElements = ResVT.getVectorNumElements();
7412   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7413   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7414                                  ResVT.getVectorElementType(), NumElements / 2);
7415
7416   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7417                                LoVT.getVectorNumElements());
7418   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7419                    DAG.getIntPtrConstant(0));
7420   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7421                    DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7422   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7423   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7424
7425   // Now combine the parts back together so we still have a single result
7426   // like the combiner expects.
7427   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7428 }
7429
7430 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7431 /// value. The load store optimizer pass will merge them to store pair stores.
7432 /// This has better performance than a splat of the scalar followed by a split
7433 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7434 /// followed by an ext.b and two stores.
7435 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7436   SDValue StVal = St->getValue();
7437   EVT VT = StVal.getValueType();
7438
7439   // Don't replace floating point stores, they possibly won't be transformed to
7440   // stp because of the store pair suppress pass.
7441   if (VT.isFloatingPoint())
7442     return SDValue();
7443
7444   // Check for insert vector elements.
7445   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7446     return SDValue();
7447
7448   // We can express a splat as store pair(s) for 2 or 4 elements.
7449   unsigned NumVecElts = VT.getVectorNumElements();
7450   if (NumVecElts != 4 && NumVecElts != 2)
7451     return SDValue();
7452   SDValue SplatVal = StVal.getOperand(1);
7453   unsigned RemainInsertElts = NumVecElts - 1;
7454
7455   // Check that this is a splat.
7456   while (--RemainInsertElts) {
7457     SDValue NextInsertElt = StVal.getOperand(0);
7458     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7459       return SDValue();
7460     if (NextInsertElt.getOperand(1) != SplatVal)
7461       return SDValue();
7462     StVal = NextInsertElt;
7463   }
7464   unsigned OrigAlignment = St->getAlignment();
7465   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7466   unsigned Alignment = std::min(OrigAlignment, EltOffset);
7467
7468   // Create scalar stores. This is at least as good as the code sequence for a
7469   // split unaligned store wich is a dup.s, ext.b, and two stores.
7470   // Most of the time the three stores should be replaced by store pair
7471   // instructions (stp).
7472   SDLoc DL(St);
7473   SDValue BasePtr = St->getBasePtr();
7474   SDValue NewST1 =
7475       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7476                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7477
7478   unsigned Offset = EltOffset;
7479   while (--NumVecElts) {
7480     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7481                                     DAG.getConstant(Offset, MVT::i64));
7482     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7483                           St->getPointerInfo(), St->isVolatile(),
7484                           St->isNonTemporal(), Alignment);
7485     Offset += EltOffset;
7486   }
7487   return NewST1;
7488 }
7489
7490 static SDValue performSTORECombine(SDNode *N,
7491                                    TargetLowering::DAGCombinerInfo &DCI,
7492                                    SelectionDAG &DAG,
7493                                    const AArch64Subtarget *Subtarget) {
7494   if (!DCI.isBeforeLegalize())
7495     return SDValue();
7496
7497   StoreSDNode *S = cast<StoreSDNode>(N);
7498   if (S->isVolatile())
7499     return SDValue();
7500
7501   // Cyclone has bad performance on unaligned 16B stores when crossing line and
7502   // page boundries. We want to split such stores.
7503   if (!Subtarget->isCyclone())
7504     return SDValue();
7505
7506   // Don't split at Oz.
7507   MachineFunction &MF = DAG.getMachineFunction();
7508   bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7509       AttributeSet::FunctionIndex, Attribute::MinSize);
7510   if (IsMinSize)
7511     return SDValue();
7512
7513   SDValue StVal = S->getValue();
7514   EVT VT = StVal.getValueType();
7515
7516   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7517   // those up regresses performance on micro-benchmarks and olden/bh.
7518   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7519     return SDValue();
7520
7521   // Split unaligned 16B stores. They are terrible for performance.
7522   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7523   // extensions can use this to mark that it does not want splitting to happen
7524   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7525   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7526   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7527       S->getAlignment() <= 2)
7528     return SDValue();
7529
7530   // If we get a splat of a scalar convert this vector store to a store of
7531   // scalars. They will be merged into store pairs thereby removing two
7532   // instructions.
7533   SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7534   if (ReplacedSplat != SDValue())
7535     return ReplacedSplat;
7536
7537   SDLoc DL(S);
7538   unsigned NumElts = VT.getVectorNumElements() / 2;
7539   // Split VT into two.
7540   EVT HalfVT =
7541       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7542   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7543                                    DAG.getIntPtrConstant(0));
7544   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7545                                    DAG.getIntPtrConstant(NumElts));
7546   SDValue BasePtr = S->getBasePtr();
7547   SDValue NewST1 =
7548       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7549                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7550   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7551                                   DAG.getConstant(8, MVT::i64));
7552   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7553                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7554                       S->getAlignment());
7555 }
7556
7557 /// Target-specific DAG combine function for post-increment LD1 (lane) and
7558 /// post-increment LD1R.
7559 static SDValue performPostLD1Combine(SDNode *N,
7560                                      TargetLowering::DAGCombinerInfo &DCI,
7561                                      bool IsLaneOp) {
7562   if (DCI.isBeforeLegalizeOps())
7563     return SDValue();
7564
7565   SelectionDAG &DAG = DCI.DAG;
7566   EVT VT = N->getValueType(0);
7567
7568   unsigned LoadIdx = IsLaneOp ? 1 : 0;
7569   SDNode *LD = N->getOperand(LoadIdx).getNode();
7570   // If it is not LOAD, can not do such combine.
7571   if (LD->getOpcode() != ISD::LOAD)
7572     return SDValue();
7573
7574   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
7575   EVT MemVT = LoadSDN->getMemoryVT();
7576   // Check if memory operand is the same type as the vector element.
7577   if (MemVT != VT.getVectorElementType())
7578     return SDValue();
7579
7580   // Check if there are other uses. If so, do not combine as it will introduce
7581   // an extra load.
7582   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
7583        ++UI) {
7584     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
7585       continue;
7586     if (*UI != N)
7587       return SDValue();
7588   }
7589
7590   SDValue Addr = LD->getOperand(1);
7591   SDValue Vector = N->getOperand(0);
7592   // Search for a use of the address operand that is an increment.
7593   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
7594        Addr.getNode()->use_end(); UI != UE; ++UI) {
7595     SDNode *User = *UI;
7596     if (User->getOpcode() != ISD::ADD
7597         || UI.getUse().getResNo() != Addr.getResNo())
7598       continue;
7599
7600     // Check that the add is independent of the load.  Otherwise, folding it
7601     // would create a cycle.
7602     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
7603       continue;
7604     // Also check that add is not used in the vector operand.  This would also
7605     // create a cycle.
7606     if (User->isPredecessorOf(Vector.getNode()))
7607       continue;
7608
7609     // If the increment is a constant, it must match the memory ref size.
7610     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7611     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7612       uint32_t IncVal = CInc->getZExtValue();
7613       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
7614       if (IncVal != NumBytes)
7615         continue;
7616       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7617     }
7618
7619     SmallVector<SDValue, 8> Ops;
7620     Ops.push_back(LD->getOperand(0));  // Chain
7621     if (IsLaneOp) {
7622       Ops.push_back(Vector);           // The vector to be inserted
7623       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
7624     }
7625     Ops.push_back(Addr);
7626     Ops.push_back(Inc);
7627
7628     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
7629     SDVTList SDTys = DAG.getVTList(Tys);
7630     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
7631     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
7632                                            MemVT,
7633                                            LoadSDN->getMemOperand());
7634
7635     // Update the uses.
7636     std::vector<SDValue> NewResults;
7637     NewResults.push_back(SDValue(LD, 0));             // The result of load
7638     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
7639     DCI.CombineTo(LD, NewResults);
7640     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
7641     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
7642
7643     break;
7644   }
7645   return SDValue();
7646 }
7647
7648 /// Target-specific DAG combine function for NEON load/store intrinsics
7649 /// to merge base address updates.
7650 static SDValue performNEONPostLDSTCombine(SDNode *N,
7651                                           TargetLowering::DAGCombinerInfo &DCI,
7652                                           SelectionDAG &DAG) {
7653   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7654     return SDValue();
7655
7656   unsigned AddrOpIdx = N->getNumOperands() - 1;
7657   SDValue Addr = N->getOperand(AddrOpIdx);
7658
7659   // Search for a use of the address operand that is an increment.
7660   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7661        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7662     SDNode *User = *UI;
7663     if (User->getOpcode() != ISD::ADD ||
7664         UI.getUse().getResNo() != Addr.getResNo())
7665       continue;
7666
7667     // Check that the add is independent of the load/store.  Otherwise, folding
7668     // it would create a cycle.
7669     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7670       continue;
7671
7672     // Find the new opcode for the updating load/store.
7673     bool IsStore = false;
7674     bool IsLaneOp = false;
7675     bool IsDupOp = false;
7676     unsigned NewOpc = 0;
7677     unsigned NumVecs = 0;
7678     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7679     switch (IntNo) {
7680     default: llvm_unreachable("unexpected intrinsic for Neon base update");
7681     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
7682       NumVecs = 2; break;
7683     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
7684       NumVecs = 3; break;
7685     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
7686       NumVecs = 4; break;
7687     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
7688       NumVecs = 2; IsStore = true; break;
7689     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
7690       NumVecs = 3; IsStore = true; break;
7691     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
7692       NumVecs = 4; IsStore = true; break;
7693     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
7694       NumVecs = 2; break;
7695     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
7696       NumVecs = 3; break;
7697     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
7698       NumVecs = 4; break;
7699     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
7700       NumVecs = 2; IsStore = true; break;
7701     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
7702       NumVecs = 3; IsStore = true; break;
7703     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
7704       NumVecs = 4; IsStore = true; break;
7705     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
7706       NumVecs = 2; IsDupOp = true; break;
7707     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
7708       NumVecs = 3; IsDupOp = true; break;
7709     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
7710       NumVecs = 4; IsDupOp = true; break;
7711     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
7712       NumVecs = 2; IsLaneOp = true; break;
7713     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
7714       NumVecs = 3; IsLaneOp = true; break;
7715     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
7716       NumVecs = 4; IsLaneOp = true; break;
7717     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
7718       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
7719     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
7720       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
7721     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
7722       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
7723     }
7724
7725     EVT VecTy;
7726     if (IsStore)
7727       VecTy = N->getOperand(2).getValueType();
7728     else
7729       VecTy = N->getValueType(0);
7730
7731     // If the increment is a constant, it must match the memory ref size.
7732     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7733     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7734       uint32_t IncVal = CInc->getZExtValue();
7735       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7736       if (IsLaneOp || IsDupOp)
7737         NumBytes /= VecTy.getVectorNumElements();
7738       if (IncVal != NumBytes)
7739         continue;
7740       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7741     }
7742     SmallVector<SDValue, 8> Ops;
7743     Ops.push_back(N->getOperand(0)); // Incoming chain
7744     // Load lane and store have vector list as input.
7745     if (IsLaneOp || IsStore)
7746       for (unsigned i = 2; i < AddrOpIdx; ++i)
7747         Ops.push_back(N->getOperand(i));
7748     Ops.push_back(Addr); // Base register
7749     Ops.push_back(Inc);
7750
7751     // Return Types.
7752     EVT Tys[6];
7753     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
7754     unsigned n;
7755     for (n = 0; n < NumResultVecs; ++n)
7756       Tys[n] = VecTy;
7757     Tys[n++] = MVT::i64;  // Type of write back register
7758     Tys[n] = MVT::Other;  // Type of the chain
7759     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
7760
7761     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7762     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
7763                                            MemInt->getMemoryVT(),
7764                                            MemInt->getMemOperand());
7765
7766     // Update the uses.
7767     std::vector<SDValue> NewResults;
7768     for (unsigned i = 0; i < NumResultVecs; ++i) {
7769       NewResults.push_back(SDValue(UpdN.getNode(), i));
7770     }
7771     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
7772     DCI.CombineTo(N, NewResults);
7773     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7774
7775     break;
7776   }
7777   return SDValue();
7778 }
7779
7780 // Optimize compare with zero and branch.
7781 static SDValue performBRCONDCombine(SDNode *N,
7782                                     TargetLowering::DAGCombinerInfo &DCI,
7783                                     SelectionDAG &DAG) {
7784   SDValue Chain = N->getOperand(0);
7785   SDValue Dest = N->getOperand(1);
7786   SDValue CCVal = N->getOperand(2);
7787   SDValue Cmp = N->getOperand(3);
7788
7789   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7790   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7791   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
7792     return SDValue();
7793
7794   unsigned CmpOpc = Cmp.getOpcode();
7795   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
7796     return SDValue();
7797
7798   // Only attempt folding if there is only one use of the flag and no use of the
7799   // value.
7800   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7801     return SDValue();
7802
7803   SDValue LHS = Cmp.getOperand(0);
7804   SDValue RHS = Cmp.getOperand(1);
7805
7806   assert(LHS.getValueType() == RHS.getValueType() &&
7807          "Expected the value type to be the same for both operands!");
7808   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7809     return SDValue();
7810
7811   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7812     std::swap(LHS, RHS);
7813
7814   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7815     return SDValue();
7816
7817   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7818       LHS.getOpcode() == ISD::SRL)
7819     return SDValue();
7820
7821   // Fold the compare into the branch instruction.
7822   SDValue BR;
7823   if (CC == AArch64CC::EQ)
7824     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7825   else
7826     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7827
7828   // Do not add new nodes to DAG combiner worklist.
7829   DCI.CombineTo(N, BR, false);
7830
7831   return SDValue();
7832 }
7833
7834 // vselect (v1i1 setcc) ->
7835 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
7836 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7837 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7838 // such VSELECT.
7839 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7840   SDValue N0 = N->getOperand(0);
7841   EVT CCVT = N0.getValueType();
7842
7843   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7844       CCVT.getVectorElementType() != MVT::i1)
7845     return SDValue();
7846
7847   EVT ResVT = N->getValueType(0);
7848   EVT CmpVT = N0.getOperand(0).getValueType();
7849   // Only combine when the result type is of the same size as the compared
7850   // operands.
7851   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7852     return SDValue();
7853
7854   SDValue IfTrue = N->getOperand(1);
7855   SDValue IfFalse = N->getOperand(2);
7856   SDValue SetCC =
7857       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7858                    N0.getOperand(0), N0.getOperand(1),
7859                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
7860   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7861                      IfTrue, IfFalse);
7862 }
7863
7864 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
7865 /// the compare-mask instructions rather than going via NZCV, even if LHS and
7866 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
7867 /// with a vector one followed by a DUP shuffle on the result.
7868 static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
7869   SDValue N0 = N->getOperand(0);
7870   EVT ResVT = N->getValueType(0);
7871
7872   if (!N->getOperand(1).getValueType().isVector())
7873     return SDValue();
7874
7875   if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
7876     return SDValue();
7877
7878   SDLoc DL(N0);
7879
7880   EVT SrcVT = N0.getOperand(0).getValueType();
7881   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT,
7882                            ResVT.getSizeInBits() / SrcVT.getSizeInBits());
7883   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
7884
7885   // First perform a vector comparison, where lane 0 is the one we're interested
7886   // in.
7887   SDValue LHS =
7888       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
7889   SDValue RHS =
7890       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
7891   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
7892
7893   // Now duplicate the comparison mask we want across all other lanes.
7894   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
7895   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
7896   Mask = DAG.getNode(ISD::BITCAST, DL, ResVT.changeVectorElementTypeToInteger(),
7897                      Mask);
7898
7899   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
7900 }
7901
7902 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
7903                                                  DAGCombinerInfo &DCI) const {
7904   SelectionDAG &DAG = DCI.DAG;
7905   switch (N->getOpcode()) {
7906   default:
7907     break;
7908   case ISD::ADD:
7909   case ISD::SUB:
7910     return performAddSubLongCombine(N, DCI, DAG);
7911   case ISD::XOR:
7912     return performXorCombine(N, DAG, DCI, Subtarget);
7913   case ISD::MUL:
7914     return performMulCombine(N, DAG, DCI, Subtarget);
7915   case ISD::SINT_TO_FP:
7916   case ISD::UINT_TO_FP:
7917     return performIntToFpCombine(N, DAG);
7918   case ISD::OR:
7919     return performORCombine(N, DCI, Subtarget);
7920   case ISD::INTRINSIC_WO_CHAIN:
7921     return performIntrinsicCombine(N, DCI, Subtarget);
7922   case ISD::ANY_EXTEND:
7923   case ISD::ZERO_EXTEND:
7924   case ISD::SIGN_EXTEND:
7925     return performExtendCombine(N, DCI, DAG);
7926   case ISD::BITCAST:
7927     return performBitcastCombine(N, DCI, DAG);
7928   case ISD::CONCAT_VECTORS:
7929     return performConcatVectorsCombine(N, DCI, DAG);
7930   case ISD::SELECT:
7931     return performSelectCombine(N, DAG);
7932   case ISD::VSELECT:
7933     return performVSelectCombine(N, DCI.DAG);
7934   case ISD::STORE:
7935     return performSTORECombine(N, DCI, DAG, Subtarget);
7936   case AArch64ISD::BRCOND:
7937     return performBRCONDCombine(N, DCI, DAG);
7938   case AArch64ISD::DUP:
7939     return performPostLD1Combine(N, DCI, false);
7940   case ISD::INSERT_VECTOR_ELT:
7941     return performPostLD1Combine(N, DCI, true);
7942   case ISD::INTRINSIC_VOID:
7943   case ISD::INTRINSIC_W_CHAIN:
7944     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7945     case Intrinsic::aarch64_neon_ld2:
7946     case Intrinsic::aarch64_neon_ld3:
7947     case Intrinsic::aarch64_neon_ld4:
7948     case Intrinsic::aarch64_neon_ld1x2:
7949     case Intrinsic::aarch64_neon_ld1x3:
7950     case Intrinsic::aarch64_neon_ld1x4:
7951     case Intrinsic::aarch64_neon_ld2lane:
7952     case Intrinsic::aarch64_neon_ld3lane:
7953     case Intrinsic::aarch64_neon_ld4lane:
7954     case Intrinsic::aarch64_neon_ld2r:
7955     case Intrinsic::aarch64_neon_ld3r:
7956     case Intrinsic::aarch64_neon_ld4r:
7957     case Intrinsic::aarch64_neon_st2:
7958     case Intrinsic::aarch64_neon_st3:
7959     case Intrinsic::aarch64_neon_st4:
7960     case Intrinsic::aarch64_neon_st1x2:
7961     case Intrinsic::aarch64_neon_st1x3:
7962     case Intrinsic::aarch64_neon_st1x4:
7963     case Intrinsic::aarch64_neon_st2lane:
7964     case Intrinsic::aarch64_neon_st3lane:
7965     case Intrinsic::aarch64_neon_st4lane:
7966       return performNEONPostLDSTCombine(N, DCI, DAG);
7967     default:
7968       break;
7969     }
7970   }
7971   return SDValue();
7972 }
7973
7974 // Check if the return value is used as only a return value, as otherwise
7975 // we can't perform a tail-call. In particular, we need to check for
7976 // target ISD nodes that are returns and any other "odd" constructs
7977 // that the generic analysis code won't necessarily catch.
7978 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
7979                                                SDValue &Chain) const {
7980   if (N->getNumValues() != 1)
7981     return false;
7982   if (!N->hasNUsesOfValue(1, 0))
7983     return false;
7984
7985   SDValue TCChain = Chain;
7986   SDNode *Copy = *N->use_begin();
7987   if (Copy->getOpcode() == ISD::CopyToReg) {
7988     // If the copy has a glue operand, we conservatively assume it isn't safe to
7989     // perform a tail call.
7990     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7991         MVT::Glue)
7992       return false;
7993     TCChain = Copy->getOperand(0);
7994   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7995     return false;
7996
7997   bool HasRet = false;
7998   for (SDNode *Node : Copy->uses()) {
7999     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8000       return false;
8001     HasRet = true;
8002   }
8003
8004   if (!HasRet)
8005     return false;
8006
8007   Chain = TCChain;
8008   return true;
8009 }
8010
8011 // Return whether the an instruction can potentially be optimized to a tail
8012 // call. This will cause the optimizers to attempt to move, or duplicate,
8013 // return instructions to help enable tail call optimizations for this
8014 // instruction.
8015 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8016   if (!CI->isTailCall())
8017     return false;
8018
8019   return true;
8020 }
8021
8022 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8023                                                    SDValue &Offset,
8024                                                    ISD::MemIndexedMode &AM,
8025                                                    bool &IsInc,
8026                                                    SelectionDAG &DAG) const {
8027   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8028     return false;
8029
8030   Base = Op->getOperand(0);
8031   // All of the indexed addressing mode instructions take a signed
8032   // 9 bit immediate offset.
8033   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8034     int64_t RHSC = (int64_t)RHS->getZExtValue();
8035     if (RHSC >= 256 || RHSC <= -256)
8036       return false;
8037     IsInc = (Op->getOpcode() == ISD::ADD);
8038     Offset = Op->getOperand(1);
8039     return true;
8040   }
8041   return false;
8042 }
8043
8044 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8045                                                       SDValue &Offset,
8046                                                       ISD::MemIndexedMode &AM,
8047                                                       SelectionDAG &DAG) const {
8048   EVT VT;
8049   SDValue Ptr;
8050   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8051     VT = LD->getMemoryVT();
8052     Ptr = LD->getBasePtr();
8053   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8054     VT = ST->getMemoryVT();
8055     Ptr = ST->getBasePtr();
8056   } else
8057     return false;
8058
8059   bool IsInc;
8060   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8061     return false;
8062   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8063   return true;
8064 }
8065
8066 bool AArch64TargetLowering::getPostIndexedAddressParts(
8067     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8068     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8069   EVT VT;
8070   SDValue Ptr;
8071   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8072     VT = LD->getMemoryVT();
8073     Ptr = LD->getBasePtr();
8074   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8075     VT = ST->getMemoryVT();
8076     Ptr = ST->getBasePtr();
8077   } else
8078     return false;
8079
8080   bool IsInc;
8081   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8082     return false;
8083   // Post-indexing updates the base, so it's not a valid transform
8084   // if that's not the same as the load's pointer.
8085   if (Ptr != Base)
8086     return false;
8087   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8088   return true;
8089 }
8090
8091 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8092                                   SelectionDAG &DAG) {
8093   if (N->getValueType(0) != MVT::i16)
8094     return;
8095
8096   SDLoc DL(N);
8097   SDValue Op = N->getOperand(0);
8098   assert(Op.getValueType() == MVT::f16 &&
8099          "Inconsistent bitcast? Only 16-bit types should be i16 or f16");
8100   Op = SDValue(
8101       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8102                          DAG.getUNDEF(MVT::i32), Op,
8103                          DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
8104       0);
8105   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8106   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8107 }
8108
8109 void AArch64TargetLowering::ReplaceNodeResults(
8110     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8111   switch (N->getOpcode()) {
8112   default:
8113     llvm_unreachable("Don't know how to custom expand this");
8114   case ISD::BITCAST:
8115     ReplaceBITCASTResults(N, Results, DAG);
8116     return;
8117   case ISD::FP_TO_UINT:
8118   case ISD::FP_TO_SINT:
8119     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8120     // Let normal code take care of it by not adding anything to Results.
8121     return;
8122   }
8123 }
8124
8125 bool AArch64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
8126   // Loads and stores less than 128-bits are already atomic; ones above that
8127   // are doomed anyway, so defer to the default libcall and blame the OS when
8128   // things go wrong:
8129   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
8130     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
8131   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
8132     return LI->getType()->getPrimitiveSizeInBits() == 128;
8133
8134   // For the real atomic operations, we have ldxr/stxr up to 128 bits.
8135   return Inst->getType()->getPrimitiveSizeInBits() <= 128;
8136 }
8137
8138 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8139   return true;
8140 }
8141
8142 TargetLoweringBase::LegalizeTypeAction
8143 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8144   MVT SVT = VT.getSimpleVT();
8145   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
8146   // v4i16, v2i32 instead of to promote.
8147   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8148       || SVT == MVT::v1f32)
8149     return TypeWidenVector;
8150
8151   return TargetLoweringBase::getPreferredVectorAction(VT);
8152 }
8153
8154 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
8155                                              AtomicOrdering Ord) const {
8156   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8157   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
8158   bool IsAcquire = isAtLeastAcquire(Ord);
8159
8160   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
8161   // intrinsic must return {i64, i64} and we have to recombine them into a
8162   // single i128 here.
8163   if (ValTy->getPrimitiveSizeInBits() == 128) {
8164     Intrinsic::ID Int =
8165         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
8166     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
8167
8168     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8169     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
8170
8171     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
8172     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
8173     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
8174     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
8175     return Builder.CreateOr(
8176         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
8177   }
8178
8179   Type *Tys[] = { Addr->getType() };
8180   Intrinsic::ID Int =
8181       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
8182   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
8183
8184   return Builder.CreateTruncOrBitCast(
8185       Builder.CreateCall(Ldxr, Addr),
8186       cast<PointerType>(Addr->getType())->getElementType());
8187 }
8188
8189 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
8190                                                    Value *Val, Value *Addr,
8191                                                    AtomicOrdering Ord) const {
8192   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8193   bool IsRelease = isAtLeastRelease(Ord);
8194
8195   // Since the intrinsics must have legal type, the i128 intrinsics take two
8196   // parameters: "i64, i64". We must marshal Val into the appropriate form
8197   // before the call.
8198   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
8199     Intrinsic::ID Int =
8200         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
8201     Function *Stxr = Intrinsic::getDeclaration(M, Int);
8202     Type *Int64Ty = Type::getInt64Ty(M->getContext());
8203
8204     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
8205     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
8206     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8207     return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
8208   }
8209
8210   Intrinsic::ID Int =
8211       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
8212   Type *Tys[] = { Addr->getType() };
8213   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
8214
8215   return Builder.CreateCall2(
8216       Stxr, Builder.CreateZExtOrBitCast(
8217                 Val, Stxr->getFunctionType()->getParamType(0)),
8218       Addr);
8219 }