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