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