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