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