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