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