]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Merge ACPICA 20170728.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 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 AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/MachineValueType.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetInstrInfo.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88
89 using namespace llvm;
90
91 #define DEBUG_TYPE "aarch64-lower"
92
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99                            cl::desc("Allow AArch64 SLI/SRI formation"),
100                            cl::init(false));
101
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120                                              const AArch64Subtarget &STI)
121     : TargetLowering(TM), Subtarget(&STI) {
122   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123   // we have to make something up. Arbitrarily, choose ZeroOrOne.
124   setBooleanContents(ZeroOrOneBooleanContent);
125   // When comparing vectors the result sets the different elements in the
126   // vector to all-one or all-zero.
127   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129   // Set up the register classes.
130   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132
133   if (Subtarget->hasFPARMv8()) {
134     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138   }
139
140   if (Subtarget->hasNEON()) {
141     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143     // Someone set us up the NEON.
144     addDRTypeForNEON(MVT::v2f32);
145     addDRTypeForNEON(MVT::v8i8);
146     addDRTypeForNEON(MVT::v4i16);
147     addDRTypeForNEON(MVT::v2i32);
148     addDRTypeForNEON(MVT::v1i64);
149     addDRTypeForNEON(MVT::v1f64);
150     addDRTypeForNEON(MVT::v4f16);
151
152     addQRTypeForNEON(MVT::v4f32);
153     addQRTypeForNEON(MVT::v2f64);
154     addQRTypeForNEON(MVT::v16i8);
155     addQRTypeForNEON(MVT::v8i16);
156     addQRTypeForNEON(MVT::v4i32);
157     addQRTypeForNEON(MVT::v2i64);
158     addQRTypeForNEON(MVT::v8f16);
159   }
160
161   // Compute derived properties from the register classes
162   computeRegisterProperties(Subtarget->getRegisterInfo());
163
164   // Provide all sorts of operation actions
165   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167   setOperationAction(ISD::SETCC, MVT::i32, Custom);
168   setOperationAction(ISD::SETCC, MVT::i64, Custom);
169   setOperationAction(ISD::SETCC, MVT::f32, Custom);
170   setOperationAction(ISD::SETCC, MVT::f64, Custom);
171   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
173   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
176   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
177   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
178   setOperationAction(ISD::SELECT, MVT::i32, Custom);
179   setOperationAction(ISD::SELECT, MVT::i64, Custom);
180   setOperationAction(ISD::SELECT, MVT::f32, Custom);
181   setOperationAction(ISD::SELECT, MVT::f64, Custom);
182   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
183   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
184   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
188
189   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
190   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
191   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
192
193   setOperationAction(ISD::FREM, MVT::f32, Expand);
194   setOperationAction(ISD::FREM, MVT::f64, Expand);
195   setOperationAction(ISD::FREM, MVT::f80, Expand);
196
197   // Custom lowering hooks are needed for XOR
198   // to fold it into CSINC/CSINV.
199   setOperationAction(ISD::XOR, MVT::i32, Custom);
200   setOperationAction(ISD::XOR, MVT::i64, Custom);
201
202   // Virtually no operation on f128 is legal, but LLVM can't expand them when
203   // there's a valid register class, so we need custom operations in most cases.
204   setOperationAction(ISD::FABS, MVT::f128, Expand);
205   setOperationAction(ISD::FADD, MVT::f128, Custom);
206   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
207   setOperationAction(ISD::FCOS, MVT::f128, Expand);
208   setOperationAction(ISD::FDIV, MVT::f128, Custom);
209   setOperationAction(ISD::FMA, MVT::f128, Expand);
210   setOperationAction(ISD::FMUL, MVT::f128, Custom);
211   setOperationAction(ISD::FNEG, MVT::f128, Expand);
212   setOperationAction(ISD::FPOW, MVT::f128, Expand);
213   setOperationAction(ISD::FREM, MVT::f128, Expand);
214   setOperationAction(ISD::FRINT, MVT::f128, Expand);
215   setOperationAction(ISD::FSIN, MVT::f128, Expand);
216   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
217   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
218   setOperationAction(ISD::FSUB, MVT::f128, Custom);
219   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
220   setOperationAction(ISD::SETCC, MVT::f128, Custom);
221   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
222   setOperationAction(ISD::SELECT, MVT::f128, Custom);
223   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
224   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
225
226   // Lowering for many of the conversions is actually specified by the non-f128
227   // type. The LowerXXX function will be trivial when f128 isn't involved.
228   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
229   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
231   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
232   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
233   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
234   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
235   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
236   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
237   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
239   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
240   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
241   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
242
243   // Variable arguments.
244   setOperationAction(ISD::VASTART, MVT::Other, Custom);
245   setOperationAction(ISD::VAARG, MVT::Other, Custom);
246   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
247   setOperationAction(ISD::VAEND, MVT::Other, Expand);
248
249   // Variable-sized objects.
250   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
251   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
252   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
253
254   // Constant pool entries
255   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
256
257   // BlockAddress
258   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
259
260   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
261   setOperationAction(ISD::ADDC, MVT::i32, Custom);
262   setOperationAction(ISD::ADDE, MVT::i32, Custom);
263   setOperationAction(ISD::SUBC, MVT::i32, Custom);
264   setOperationAction(ISD::SUBE, MVT::i32, Custom);
265   setOperationAction(ISD::ADDC, MVT::i64, Custom);
266   setOperationAction(ISD::ADDE, MVT::i64, Custom);
267   setOperationAction(ISD::SUBC, MVT::i64, Custom);
268   setOperationAction(ISD::SUBE, MVT::i64, Custom);
269
270   // AArch64 lacks both left-rotate and popcount instructions.
271   setOperationAction(ISD::ROTL, MVT::i32, Expand);
272   setOperationAction(ISD::ROTL, MVT::i64, Expand);
273   for (MVT VT : MVT::vector_valuetypes()) {
274     setOperationAction(ISD::ROTL, VT, Expand);
275     setOperationAction(ISD::ROTR, VT, Expand);
276   }
277
278   // AArch64 doesn't have {U|S}MUL_LOHI.
279   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
280   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
281
282   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
283   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
284
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287   for (MVT VT : MVT::vector_valuetypes()) {
288     setOperationAction(ISD::SDIVREM, VT, Expand);
289     setOperationAction(ISD::UDIVREM, VT, Expand);
290   }
291   setOperationAction(ISD::SREM, MVT::i32, Expand);
292   setOperationAction(ISD::SREM, MVT::i64, Expand);
293   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
294   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
295   setOperationAction(ISD::UREM, MVT::i32, Expand);
296   setOperationAction(ISD::UREM, MVT::i64, Expand);
297
298   // Custom lower Add/Sub/Mul with overflow.
299   setOperationAction(ISD::SADDO, MVT::i32, Custom);
300   setOperationAction(ISD::SADDO, MVT::i64, Custom);
301   setOperationAction(ISD::UADDO, MVT::i32, Custom);
302   setOperationAction(ISD::UADDO, MVT::i64, Custom);
303   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
304   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
305   setOperationAction(ISD::USUBO, MVT::i32, Custom);
306   setOperationAction(ISD::USUBO, MVT::i64, Custom);
307   setOperationAction(ISD::SMULO, MVT::i32, Custom);
308   setOperationAction(ISD::SMULO, MVT::i64, Custom);
309   setOperationAction(ISD::UMULO, MVT::i32, Custom);
310   setOperationAction(ISD::UMULO, MVT::i64, Custom);
311
312   setOperationAction(ISD::FSIN, MVT::f32, Expand);
313   setOperationAction(ISD::FSIN, MVT::f64, Expand);
314   setOperationAction(ISD::FCOS, MVT::f32, Expand);
315   setOperationAction(ISD::FCOS, MVT::f64, Expand);
316   setOperationAction(ISD::FPOW, MVT::f32, Expand);
317   setOperationAction(ISD::FPOW, MVT::f64, Expand);
318   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
319   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
320
321   // f16 is a storage-only type, always promote it to f32.
322   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
323   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
324   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
325   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
326   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
327   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
328   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
329   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
330   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
331   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
332   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
333   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
334   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
335   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
336   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
337   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
338   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
339   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
340   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
341   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
342   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
343   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
344   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
345   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
346   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
347   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
348   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
349   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
350   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
351   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
352   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
353   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
354   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
355   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
356
357   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
358   // known to be safe.
359   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
360   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
361   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
362   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
363   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
364   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
365   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
366   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
367   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
368   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
369   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
370   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
371
372   // Expand all other v4f16 operations.
373   // FIXME: We could generate better code by promoting some operations to
374   // a pair of v4f32s
375   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
376   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
377   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
378   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
379   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
380   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
381   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
382   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
383   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
384   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
385   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
386   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
387   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
388   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
389   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
390   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
391   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
392   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
393   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
394   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
395   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
396   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
397   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
398   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
399   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
400
401
402   // v8f16 is also a storage-only type, so expand it.
403   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
404   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
405   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
406   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
407   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
408   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
409   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
410   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
411   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
412   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
413   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
414   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
415   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
416   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
417   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
418   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
419   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
420   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
421   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
422   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
423   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
424   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
425   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
426   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
427   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
428   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
429   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
430   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
431   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
432   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
433
434   // AArch64 has implementations of a lot of rounding-like FP operations.
435   for (MVT Ty : {MVT::f32, MVT::f64}) {
436     setOperationAction(ISD::FFLOOR, Ty, Legal);
437     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
438     setOperationAction(ISD::FCEIL, Ty, Legal);
439     setOperationAction(ISD::FRINT, Ty, Legal);
440     setOperationAction(ISD::FTRUNC, Ty, Legal);
441     setOperationAction(ISD::FROUND, Ty, Legal);
442     setOperationAction(ISD::FMINNUM, Ty, Legal);
443     setOperationAction(ISD::FMAXNUM, Ty, Legal);
444     setOperationAction(ISD::FMINNAN, Ty, Legal);
445     setOperationAction(ISD::FMAXNAN, Ty, Legal);
446   }
447
448   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
449
450   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
451
452   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
453   // This requires the Performance Monitors extension.
454   if (Subtarget->hasPerfMon())
455     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
456
457   if (Subtarget->isTargetMachO()) {
458     // For iOS, we don't want to the normal expansion of a libcall to
459     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
460     // traffic.
461     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
462     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
463   } else {
464     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
465     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
466   }
467
468   // Make floating-point constants legal for the large code model, so they don't
469   // become loads from the constant pool.
470   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
471     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
472     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
473   }
474
475   // AArch64 does not have floating-point extending loads, i1 sign-extending
476   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
477   for (MVT VT : MVT::fp_valuetypes()) {
478     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
479     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
480     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
481     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
482   }
483   for (MVT VT : MVT::integer_valuetypes())
484     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
485
486   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
487   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
488   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
489   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
490   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
491   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
492   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
493
494   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
495   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
496
497   // Indexed loads and stores are supported.
498   for (unsigned im = (unsigned)ISD::PRE_INC;
499        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
500     setIndexedLoadAction(im, MVT::i8, Legal);
501     setIndexedLoadAction(im, MVT::i16, Legal);
502     setIndexedLoadAction(im, MVT::i32, Legal);
503     setIndexedLoadAction(im, MVT::i64, Legal);
504     setIndexedLoadAction(im, MVT::f64, Legal);
505     setIndexedLoadAction(im, MVT::f32, Legal);
506     setIndexedLoadAction(im, MVT::f16, Legal);
507     setIndexedStoreAction(im, MVT::i8, Legal);
508     setIndexedStoreAction(im, MVT::i16, Legal);
509     setIndexedStoreAction(im, MVT::i32, Legal);
510     setIndexedStoreAction(im, MVT::i64, Legal);
511     setIndexedStoreAction(im, MVT::f64, Legal);
512     setIndexedStoreAction(im, MVT::f32, Legal);
513     setIndexedStoreAction(im, MVT::f16, Legal);
514   }
515
516   // Trap.
517   setOperationAction(ISD::TRAP, MVT::Other, Legal);
518
519   // We combine OR nodes for bitfield operations.
520   setTargetDAGCombine(ISD::OR);
521
522   // Vector add and sub nodes may conceal a high-half opportunity.
523   // Also, try to fold ADD into CSINC/CSINV..
524   setTargetDAGCombine(ISD::ADD);
525   setTargetDAGCombine(ISD::SUB);
526   setTargetDAGCombine(ISD::SRL);
527   setTargetDAGCombine(ISD::XOR);
528   setTargetDAGCombine(ISD::SINT_TO_FP);
529   setTargetDAGCombine(ISD::UINT_TO_FP);
530
531   setTargetDAGCombine(ISD::FP_TO_SINT);
532   setTargetDAGCombine(ISD::FP_TO_UINT);
533   setTargetDAGCombine(ISD::FDIV);
534
535   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
536
537   setTargetDAGCombine(ISD::ANY_EXTEND);
538   setTargetDAGCombine(ISD::ZERO_EXTEND);
539   setTargetDAGCombine(ISD::SIGN_EXTEND);
540   setTargetDAGCombine(ISD::BITCAST);
541   setTargetDAGCombine(ISD::CONCAT_VECTORS);
542   setTargetDAGCombine(ISD::STORE);
543   if (Subtarget->supportsAddressTopByteIgnored())
544     setTargetDAGCombine(ISD::LOAD);
545
546   setTargetDAGCombine(ISD::MUL);
547
548   setTargetDAGCombine(ISD::SELECT);
549   setTargetDAGCombine(ISD::VSELECT);
550
551   setTargetDAGCombine(ISD::INTRINSIC_VOID);
552   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
554
555   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
556   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
557   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
558
559   setStackPointerRegisterToSaveRestore(AArch64::SP);
560
561   setSchedulingPreference(Sched::Hybrid);
562
563   EnableExtLdPromotion = true;
564
565   // Set required alignment.
566   setMinFunctionAlignment(2);
567   // Set preferred alignments.
568   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
569   setPrefLoopAlignment(STI.getPrefLoopAlignment());
570
571   // Only change the limit for entries in a jump table if specified by
572   // the subtarget, but not at the command line.
573   unsigned MaxJT = STI.getMaximumJumpTableSize();
574   if (MaxJT && getMaximumJumpTableSize() == 0)
575     setMaximumJumpTableSize(MaxJT);
576
577   setHasExtractBitsInsn(true);
578
579   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
580
581   if (Subtarget->hasNEON()) {
582     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
583     // silliness like this:
584     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
585     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
586     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
588     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
589     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
590     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
591     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
592     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
593     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
594     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
595     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
596     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
597     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
598     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
599     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
600     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
601     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
602     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
603     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
604     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
605     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
606     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
608     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
609
610     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
611     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
612     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
613     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
614     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
615
616     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
617
618     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
619     // elements smaller than i32, so promote the input to i32 first.
620     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
621     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
622     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
623     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
624     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
625     // -> v8f16 conversions.
626     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
627     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
628     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
629     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
630     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
631     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
632     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
633     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
634     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
635     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
636     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
637     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
638     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
639
640     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
641     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
642
643     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
644     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
645     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
646     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
647     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
648     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
649     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
650     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
651
652     // AArch64 doesn't have MUL.2d:
653     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
654     // Custom handling for some quad-vector types to detect MULL.
655     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
656     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
657     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
658
659     // Vector reductions
660     for (MVT VT : MVT::integer_valuetypes()) {
661       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
662       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
663       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
664       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
665       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
666     }
667     for (MVT VT : MVT::fp_valuetypes()) {
668       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
669       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
670     }
671
672     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
673     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
674     // Likewise, narrowing and extending vector loads/stores aren't handled
675     // directly.
676     for (MVT VT : MVT::vector_valuetypes()) {
677       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
678
679       setOperationAction(ISD::MULHS, VT, Expand);
680       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
681       setOperationAction(ISD::MULHU, VT, Expand);
682       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
683
684       setOperationAction(ISD::BSWAP, VT, Expand);
685
686       for (MVT InnerVT : MVT::vector_valuetypes()) {
687         setTruncStoreAction(VT, InnerVT, Expand);
688         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
689         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
690         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
691       }
692     }
693
694     // AArch64 has implementations of a lot of rounding-like FP operations.
695     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
696       setOperationAction(ISD::FFLOOR, Ty, Legal);
697       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
698       setOperationAction(ISD::FCEIL, Ty, Legal);
699       setOperationAction(ISD::FRINT, Ty, Legal);
700       setOperationAction(ISD::FTRUNC, Ty, Legal);
701       setOperationAction(ISD::FROUND, Ty, Legal);
702     }
703   }
704
705   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
706 }
707
708 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
709   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
710     setOperationAction(ISD::LOAD, VT, Promote);
711     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
712
713     setOperationAction(ISD::STORE, VT, Promote);
714     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
715   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
716     setOperationAction(ISD::LOAD, VT, Promote);
717     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
718
719     setOperationAction(ISD::STORE, VT, Promote);
720     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
721   }
722
723   // Mark vector float intrinsics as expand.
724   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
725     setOperationAction(ISD::FSIN, VT, Expand);
726     setOperationAction(ISD::FCOS, VT, Expand);
727     setOperationAction(ISD::FPOW, VT, Expand);
728     setOperationAction(ISD::FLOG, VT, Expand);
729     setOperationAction(ISD::FLOG2, VT, Expand);
730     setOperationAction(ISD::FLOG10, VT, Expand);
731     setOperationAction(ISD::FEXP, VT, Expand);
732     setOperationAction(ISD::FEXP2, VT, Expand);
733
734     // But we do support custom-lowering for FCOPYSIGN.
735     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
736   }
737
738   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
740   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
741   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
742   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
743   setOperationAction(ISD::SRA, VT, Custom);
744   setOperationAction(ISD::SRL, VT, Custom);
745   setOperationAction(ISD::SHL, VT, Custom);
746   setOperationAction(ISD::AND, VT, Custom);
747   setOperationAction(ISD::OR, VT, Custom);
748   setOperationAction(ISD::SETCC, VT, Custom);
749   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
750
751   setOperationAction(ISD::SELECT, VT, Expand);
752   setOperationAction(ISD::SELECT_CC, VT, Expand);
753   setOperationAction(ISD::VSELECT, VT, Expand);
754   for (MVT InnerVT : MVT::all_valuetypes())
755     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
756
757   // CNT supports only B element sizes.
758   if (VT != MVT::v8i8 && VT != MVT::v16i8)
759     setOperationAction(ISD::CTPOP, VT, Expand);
760
761   setOperationAction(ISD::UDIV, VT, Expand);
762   setOperationAction(ISD::SDIV, VT, Expand);
763   setOperationAction(ISD::UREM, VT, Expand);
764   setOperationAction(ISD::SREM, VT, Expand);
765   setOperationAction(ISD::FREM, VT, Expand);
766
767   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
768   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
769
770   if (!VT.isFloatingPoint())
771     setOperationAction(ISD::ABS, VT, Legal);
772
773   // [SU][MIN|MAX] are available for all NEON types apart from i64.
774   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
775     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
776       setOperationAction(Opcode, VT, Legal);
777
778   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
779   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
780     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
781                             ISD::FMINNUM, ISD::FMAXNUM})
782       setOperationAction(Opcode, VT, Legal);
783
784   if (Subtarget->isLittleEndian()) {
785     for (unsigned im = (unsigned)ISD::PRE_INC;
786          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
787       setIndexedLoadAction(im, VT, Legal);
788       setIndexedStoreAction(im, VT, Legal);
789     }
790   }
791 }
792
793 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
794   addRegisterClass(VT, &AArch64::FPR64RegClass);
795   addTypeForNEON(VT, MVT::v2i32);
796 }
797
798 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
799   addRegisterClass(VT, &AArch64::FPR128RegClass);
800   addTypeForNEON(VT, MVT::v4i32);
801 }
802
803 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
804                                               EVT VT) const {
805   if (!VT.isVector())
806     return MVT::i32;
807   return VT.changeVectorElementTypeToInteger();
808 }
809
810 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
811                                const APInt &Demanded,
812                                TargetLowering::TargetLoweringOpt &TLO,
813                                unsigned NewOpc) {
814   uint64_t OldImm = Imm, NewImm, Enc;
815   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
816
817   // Return if the immediate is already all zeros, all ones, a bimm32 or a
818   // bimm64.
819   if (Imm == 0 || Imm == Mask ||
820       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
821     return false;
822
823   unsigned EltSize = Size;
824   uint64_t DemandedBits = Demanded.getZExtValue();
825
826   // Clear bits that are not demanded.
827   Imm &= DemandedBits;
828
829   while (true) {
830     // The goal here is to set the non-demanded bits in a way that minimizes
831     // the number of switching between 0 and 1. In order to achieve this goal,
832     // we set the non-demanded bits to the value of the preceding demanded bits.
833     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
834     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
835     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
836     // The final result is 0b11000011.
837     uint64_t NonDemandedBits = ~DemandedBits;
838     uint64_t InvertedImm = ~Imm & DemandedBits;
839     uint64_t RotatedImm =
840         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
841         NonDemandedBits;
842     uint64_t Sum = RotatedImm + NonDemandedBits;
843     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
844     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
845     NewImm = (Imm | Ones) & Mask;
846
847     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
848     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
849     // we halve the element size and continue the search.
850     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
851       break;
852
853     // We cannot shrink the element size any further if it is 2-bits.
854     if (EltSize == 2)
855       return false;
856
857     EltSize /= 2;
858     Mask >>= EltSize;
859     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
860
861     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
862     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
863       return false;
864
865     // Merge the upper and lower halves of Imm and DemandedBits.
866     Imm |= Hi;
867     DemandedBits |= DemandedBitsHi;
868   }
869
870   ++NumOptimizedImms;
871
872   // Replicate the element across the register width.
873   while (EltSize < Size) {
874     NewImm |= NewImm << EltSize;
875     EltSize *= 2;
876   }
877
878   (void)OldImm;
879   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
880          "demanded bits should never be altered");
881   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
882
883   // Create the new constant immediate node.
884   EVT VT = Op.getValueType();
885   SDLoc DL(Op);
886   SDValue New;
887
888   // If the new constant immediate is all-zeros or all-ones, let the target
889   // independent DAG combine optimize this node.
890   if (NewImm == 0 || NewImm == OrigMask) {
891     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
892                           TLO.DAG.getConstant(NewImm, DL, VT));
893   // Otherwise, create a machine node so that target independent DAG combine
894   // doesn't undo this optimization.
895   } else {
896     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
897     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
898     New = SDValue(
899         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
900   }
901
902   return TLO.CombineTo(Op, New);
903 }
904
905 bool AArch64TargetLowering::targetShrinkDemandedConstant(
906     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
907   // Delay this optimization to as late as possible.
908   if (!TLO.LegalOps)
909     return false;
910
911   if (!EnableOptimizeLogicalImm)
912     return false;
913
914   EVT VT = Op.getValueType();
915   if (VT.isVector())
916     return false;
917
918   unsigned Size = VT.getSizeInBits();
919   assert((Size == 32 || Size == 64) &&
920          "i32 or i64 is expected after legalization.");
921
922   // Exit early if we demand all bits.
923   if (Demanded.countPopulation() == Size)
924     return false;
925
926   unsigned NewOpc;
927   switch (Op.getOpcode()) {
928   default:
929     return false;
930   case ISD::AND:
931     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
932     break;
933   case ISD::OR:
934     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
935     break;
936   case ISD::XOR:
937     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
938     break;
939   }
940   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
941   if (!C)
942     return false;
943   uint64_t Imm = C->getZExtValue();
944   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
945 }
946
947 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
948 /// Mask are known to be either zero or one and return them Known.
949 void AArch64TargetLowering::computeKnownBitsForTargetNode(
950     const SDValue Op, KnownBits &Known,
951     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
952   switch (Op.getOpcode()) {
953   default:
954     break;
955   case AArch64ISD::CSEL: {
956     KnownBits Known2;
957     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
958     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
959     Known.Zero &= Known2.Zero;
960     Known.One &= Known2.One;
961     break;
962   }
963   case ISD::INTRINSIC_W_CHAIN: {
964     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
965     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
966     switch (IntID) {
967     default: return;
968     case Intrinsic::aarch64_ldaxr:
969     case Intrinsic::aarch64_ldxr: {
970       unsigned BitWidth = Known.getBitWidth();
971       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
972       unsigned MemBits = VT.getScalarSizeInBits();
973       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
974       return;
975     }
976     }
977     break;
978   }
979   case ISD::INTRINSIC_WO_CHAIN:
980   case ISD::INTRINSIC_VOID: {
981     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
982     switch (IntNo) {
983     default:
984       break;
985     case Intrinsic::aarch64_neon_umaxv:
986     case Intrinsic::aarch64_neon_uminv: {
987       // Figure out the datatype of the vector operand. The UMINV instruction
988       // will zero extend the result, so we can mark as known zero all the
989       // bits larger than the element datatype. 32-bit or larget doesn't need
990       // this as those are legal types and will be handled by isel directly.
991       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
992       unsigned BitWidth = Known.getBitWidth();
993       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
994         assert(BitWidth >= 8 && "Unexpected width!");
995         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
996         Known.Zero |= Mask;
997       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
998         assert(BitWidth >= 16 && "Unexpected width!");
999         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1000         Known.Zero |= Mask;
1001       }
1002       break;
1003     } break;
1004     }
1005   }
1006   }
1007 }
1008
1009 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1010                                                   EVT) const {
1011   return MVT::i64;
1012 }
1013
1014 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1015                                                            unsigned AddrSpace,
1016                                                            unsigned Align,
1017                                                            bool *Fast) const {
1018   if (Subtarget->requiresStrictAlign())
1019     return false;
1020
1021   if (Fast) {
1022     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1023     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1024             // See comments in performSTORECombine() for more details about
1025             // these conditions.
1026
1027             // Code that uses clang vector extensions can mark that it
1028             // wants unaligned accesses to be treated as fast by
1029             // underspecifying alignment to be 1 or 2.
1030             Align <= 2 ||
1031
1032             // Disregard v2i64. Memcpy lowering produces those and splitting
1033             // them regresses performance on micro-benchmarks and olden/bh.
1034             VT == MVT::v2i64;
1035   }
1036   return true;
1037 }
1038
1039 FastISel *
1040 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1041                                       const TargetLibraryInfo *libInfo) const {
1042   return AArch64::createFastISel(funcInfo, libInfo);
1043 }
1044
1045 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1046   switch ((AArch64ISD::NodeType)Opcode) {
1047   case AArch64ISD::FIRST_NUMBER:      break;
1048   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1049   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1050   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1051   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1052   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1053   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1054   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1055   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1056   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1057   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1058   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1059   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1060   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1061   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1062   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1063   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1064   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1065   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1066   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1067   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1068   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1069   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1070   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1071   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1072   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1073   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1074   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1075   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1076   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1077   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1078   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1079   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1080   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1081   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1082   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1083   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1084   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1085   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1086   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1087   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1088   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1089   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1090   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1091   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1092   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1093   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1094   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1095   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1096   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1097   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1098   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1099   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1100   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1101   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1102   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1103   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1104   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1105   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1106   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1107   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1108   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1109   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1110   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1111   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1112   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1113   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1114   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1115   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1116   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1117   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1118   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1119   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1120   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1121   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1122   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1123   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1124   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1125   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1126   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1127   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1128   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1129   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1130   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1131   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1132   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1133   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1134   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1135   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1136   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1137   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1138   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1139   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1140   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1141   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1142   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1143   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1144   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1145   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1146   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1147   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1148   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1149   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1150   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1151   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1152   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1153   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1154   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1155   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1156   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1157   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1158   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1159   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1160   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1161   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1162   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1163   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1164   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1165   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1166   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1167   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1168   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1169   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1170   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1171   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1172   }
1173   return nullptr;
1174 }
1175
1176 MachineBasicBlock *
1177 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1178                                     MachineBasicBlock *MBB) const {
1179   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1180   // phi node:
1181
1182   // OrigBB:
1183   //     [... previous instrs leading to comparison ...]
1184   //     b.ne TrueBB
1185   //     b EndBB
1186   // TrueBB:
1187   //     ; Fallthrough
1188   // EndBB:
1189   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1190
1191   MachineFunction *MF = MBB->getParent();
1192   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1193   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1194   DebugLoc DL = MI.getDebugLoc();
1195   MachineFunction::iterator It = ++MBB->getIterator();
1196
1197   unsigned DestReg = MI.getOperand(0).getReg();
1198   unsigned IfTrueReg = MI.getOperand(1).getReg();
1199   unsigned IfFalseReg = MI.getOperand(2).getReg();
1200   unsigned CondCode = MI.getOperand(3).getImm();
1201   bool NZCVKilled = MI.getOperand(4).isKill();
1202
1203   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205   MF->insert(It, TrueBB);
1206   MF->insert(It, EndBB);
1207
1208   // Transfer rest of current basic-block to EndBB
1209   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1210                 MBB->end());
1211   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1212
1213   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1214   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1215   MBB->addSuccessor(TrueBB);
1216   MBB->addSuccessor(EndBB);
1217
1218   // TrueBB falls through to the end.
1219   TrueBB->addSuccessor(EndBB);
1220
1221   if (!NZCVKilled) {
1222     TrueBB->addLiveIn(AArch64::NZCV);
1223     EndBB->addLiveIn(AArch64::NZCV);
1224   }
1225
1226   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1227       .addReg(IfTrueReg)
1228       .addMBB(TrueBB)
1229       .addReg(IfFalseReg)
1230       .addMBB(MBB);
1231
1232   MI.eraseFromParent();
1233   return EndBB;
1234 }
1235
1236 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1237     MachineInstr &MI, MachineBasicBlock *BB) const {
1238   switch (MI.getOpcode()) {
1239   default:
1240 #ifndef NDEBUG
1241     MI.dump();
1242 #endif
1243     llvm_unreachable("Unexpected instruction for custom inserter!");
1244
1245   case AArch64::F128CSEL:
1246     return EmitF128CSEL(MI, BB);
1247
1248   case TargetOpcode::STACKMAP:
1249   case TargetOpcode::PATCHPOINT:
1250     return emitPatchPoint(MI, BB);
1251   }
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 // AArch64 Lowering private implementation.
1256 //===----------------------------------------------------------------------===//
1257
1258 //===----------------------------------------------------------------------===//
1259 // Lowering Code
1260 //===----------------------------------------------------------------------===//
1261
1262 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1263 /// CC
1264 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1265   switch (CC) {
1266   default:
1267     llvm_unreachable("Unknown condition code!");
1268   case ISD::SETNE:
1269     return AArch64CC::NE;
1270   case ISD::SETEQ:
1271     return AArch64CC::EQ;
1272   case ISD::SETGT:
1273     return AArch64CC::GT;
1274   case ISD::SETGE:
1275     return AArch64CC::GE;
1276   case ISD::SETLT:
1277     return AArch64CC::LT;
1278   case ISD::SETLE:
1279     return AArch64CC::LE;
1280   case ISD::SETUGT:
1281     return AArch64CC::HI;
1282   case ISD::SETUGE:
1283     return AArch64CC::HS;
1284   case ISD::SETULT:
1285     return AArch64CC::LO;
1286   case ISD::SETULE:
1287     return AArch64CC::LS;
1288   }
1289 }
1290
1291 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1292 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1293                                   AArch64CC::CondCode &CondCode,
1294                                   AArch64CC::CondCode &CondCode2) {
1295   CondCode2 = AArch64CC::AL;
1296   switch (CC) {
1297   default:
1298     llvm_unreachable("Unknown FP condition!");
1299   case ISD::SETEQ:
1300   case ISD::SETOEQ:
1301     CondCode = AArch64CC::EQ;
1302     break;
1303   case ISD::SETGT:
1304   case ISD::SETOGT:
1305     CondCode = AArch64CC::GT;
1306     break;
1307   case ISD::SETGE:
1308   case ISD::SETOGE:
1309     CondCode = AArch64CC::GE;
1310     break;
1311   case ISD::SETOLT:
1312     CondCode = AArch64CC::MI;
1313     break;
1314   case ISD::SETOLE:
1315     CondCode = AArch64CC::LS;
1316     break;
1317   case ISD::SETONE:
1318     CondCode = AArch64CC::MI;
1319     CondCode2 = AArch64CC::GT;
1320     break;
1321   case ISD::SETO:
1322     CondCode = AArch64CC::VC;
1323     break;
1324   case ISD::SETUO:
1325     CondCode = AArch64CC::VS;
1326     break;
1327   case ISD::SETUEQ:
1328     CondCode = AArch64CC::EQ;
1329     CondCode2 = AArch64CC::VS;
1330     break;
1331   case ISD::SETUGT:
1332     CondCode = AArch64CC::HI;
1333     break;
1334   case ISD::SETUGE:
1335     CondCode = AArch64CC::PL;
1336     break;
1337   case ISD::SETLT:
1338   case ISD::SETULT:
1339     CondCode = AArch64CC::LT;
1340     break;
1341   case ISD::SETLE:
1342   case ISD::SETULE:
1343     CondCode = AArch64CC::LE;
1344     break;
1345   case ISD::SETNE:
1346   case ISD::SETUNE:
1347     CondCode = AArch64CC::NE;
1348     break;
1349   }
1350 }
1351
1352 /// Convert a DAG fp condition code to an AArch64 CC.
1353 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1354 /// should be AND'ed instead of OR'ed.
1355 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1356                                      AArch64CC::CondCode &CondCode,
1357                                      AArch64CC::CondCode &CondCode2) {
1358   CondCode2 = AArch64CC::AL;
1359   switch (CC) {
1360   default:
1361     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1362     assert(CondCode2 == AArch64CC::AL);
1363     break;
1364   case ISD::SETONE:
1365     // (a one b)
1366     // == ((a olt b) || (a ogt b))
1367     // == ((a ord b) && (a une b))
1368     CondCode = AArch64CC::VC;
1369     CondCode2 = AArch64CC::NE;
1370     break;
1371   case ISD::SETUEQ:
1372     // (a ueq b)
1373     // == ((a uno b) || (a oeq b))
1374     // == ((a ule b) && (a uge b))
1375     CondCode = AArch64CC::PL;
1376     CondCode2 = AArch64CC::LE;
1377     break;
1378   }
1379 }
1380
1381 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1382 /// CC usable with the vector instructions. Fewer operations are available
1383 /// without a real NZCV register, so we have to use less efficient combinations
1384 /// to get the same effect.
1385 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1386                                         AArch64CC::CondCode &CondCode,
1387                                         AArch64CC::CondCode &CondCode2,
1388                                         bool &Invert) {
1389   Invert = false;
1390   switch (CC) {
1391   default:
1392     // Mostly the scalar mappings work fine.
1393     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1394     break;
1395   case ISD::SETUO:
1396     Invert = true;
1397     LLVM_FALLTHROUGH;
1398   case ISD::SETO:
1399     CondCode = AArch64CC::MI;
1400     CondCode2 = AArch64CC::GE;
1401     break;
1402   case ISD::SETUEQ:
1403   case ISD::SETULT:
1404   case ISD::SETULE:
1405   case ISD::SETUGT:
1406   case ISD::SETUGE:
1407     // All of the compare-mask comparisons are ordered, but we can switch
1408     // between the two by a double inversion. E.g. ULE == !OGT.
1409     Invert = true;
1410     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1411     break;
1412   }
1413 }
1414
1415 static bool isLegalArithImmed(uint64_t C) {
1416   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1417   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1418 }
1419
1420 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1421                               const SDLoc &dl, SelectionDAG &DAG) {
1422   EVT VT = LHS.getValueType();
1423
1424   if (VT.isFloatingPoint()) {
1425     assert(VT != MVT::f128);
1426     if (VT == MVT::f16) {
1427       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1428       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1429       VT = MVT::f32;
1430     }
1431     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1432   }
1433
1434   // The CMP instruction is just an alias for SUBS, and representing it as
1435   // SUBS means that it's possible to get CSE with subtract operations.
1436   // A later phase can perform the optimization of setting the destination
1437   // register to WZR/XZR if it ends up being unused.
1438   unsigned Opcode = AArch64ISD::SUBS;
1439
1440   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1441       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1442     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1443     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1444     // can be set differently by this operation. It comes down to whether
1445     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1446     // everything is fine. If not then the optimization is wrong. Thus general
1447     // comparisons are only valid if op2 != 0.
1448
1449     // So, finally, the only LLVM-native comparisons that don't mention C and V
1450     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1451     // the absence of information about op2.
1452     Opcode = AArch64ISD::ADDS;
1453     RHS = RHS.getOperand(1);
1454   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1455              !isUnsignedIntSetCC(CC)) {
1456     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1457     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1458     // of the signed comparisons.
1459     Opcode = AArch64ISD::ANDS;
1460     RHS = LHS.getOperand(1);
1461     LHS = LHS.getOperand(0);
1462   }
1463
1464   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1465       .getValue(1);
1466 }
1467
1468 /// \defgroup AArch64CCMP CMP;CCMP matching
1469 ///
1470 /// These functions deal with the formation of CMP;CCMP;... sequences.
1471 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1472 /// a comparison. They set the NZCV flags to a predefined value if their
1473 /// predicate is false. This allows to express arbitrary conjunctions, for
1474 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1475 /// expressed as:
1476 ///   cmp A
1477 ///   ccmp B, inv(CB), CA
1478 ///   check for CB flags
1479 ///
1480 /// In general we can create code for arbitrary "... (and (and A B) C)"
1481 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1482 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1483 /// negation operations:
1484 /// We can negate the results of a single comparison by inverting the flags
1485 /// used when the predicate fails and inverting the flags tested in the next
1486 /// instruction; We can also negate the results of the whole previous
1487 /// conditional compare sequence by inverting the flags tested in the next
1488 /// instruction. However there is no way to negate the result of a partial
1489 /// sequence.
1490 ///
1491 /// Therefore on encountering an "or" expression we can negate the subtree on
1492 /// one side and have to be able to push the negate to the leafs of the subtree
1493 /// on the other side (see also the comments in code). As complete example:
1494 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1495 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1496 /// is transformed to
1497 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1498 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1499 /// and implemented as:
1500 ///   cmp C
1501 ///   ccmp D, inv(CD), CC
1502 ///   ccmp A, CA, inv(CD)
1503 ///   ccmp B, CB, inv(CA)
1504 ///   check for CB flags
1505 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1506 /// by conditional compare sequences.
1507 /// @{
1508
1509 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1510 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1511                                          ISD::CondCode CC, SDValue CCOp,
1512                                          AArch64CC::CondCode Predicate,
1513                                          AArch64CC::CondCode OutCC,
1514                                          const SDLoc &DL, SelectionDAG &DAG) {
1515   unsigned Opcode = 0;
1516   if (LHS.getValueType().isFloatingPoint()) {
1517     assert(LHS.getValueType() != MVT::f128);
1518     if (LHS.getValueType() == MVT::f16) {
1519       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1520       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1521     }
1522     Opcode = AArch64ISD::FCCMP;
1523   } else if (RHS.getOpcode() == ISD::SUB) {
1524     SDValue SubOp0 = RHS.getOperand(0);
1525     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1526       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1527       Opcode = AArch64ISD::CCMN;
1528       RHS = RHS.getOperand(1);
1529     }
1530   }
1531   if (Opcode == 0)
1532     Opcode = AArch64ISD::CCMP;
1533
1534   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1535   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1536   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1537   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1538   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1539 }
1540
1541 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1542 /// CanPushNegate is set to true if we can push a negate operation through
1543 /// the tree in a was that we are left with AND operations and negate operations
1544 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1545 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1546 /// brought into such a form.
1547 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1548                                          unsigned Depth = 0) {
1549   if (!Val.hasOneUse())
1550     return false;
1551   unsigned Opcode = Val->getOpcode();
1552   if (Opcode == ISD::SETCC) {
1553     if (Val->getOperand(0).getValueType() == MVT::f128)
1554       return false;
1555     CanNegate = true;
1556     return true;
1557   }
1558   // Protect against exponential runtime and stack overflow.
1559   if (Depth > 6)
1560     return false;
1561   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1562     SDValue O0 = Val->getOperand(0);
1563     SDValue O1 = Val->getOperand(1);
1564     bool CanNegateL;
1565     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1566       return false;
1567     bool CanNegateR;
1568     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1569       return false;
1570
1571     if (Opcode == ISD::OR) {
1572       // For an OR expression we need to be able to negate at least one side or
1573       // we cannot do the transformation at all.
1574       if (!CanNegateL && !CanNegateR)
1575         return false;
1576       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1577       // can negate the x and y subtrees.
1578       CanNegate = CanNegateL && CanNegateR;
1579     } else {
1580       // If the operands are OR expressions then we finally need to negate their
1581       // outputs, we can only do that for the operand with emitted last by
1582       // negating OutCC, not for both operands.
1583       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1584       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1585       if (NeedsNegOutL && NeedsNegOutR)
1586         return false;
1587       // We cannot negate an AND operation (it would become an OR),
1588       CanNegate = false;
1589     }
1590     return true;
1591   }
1592   return false;
1593 }
1594
1595 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1596 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1597 /// Tries to transform the given i1 producing node @p Val to a series compare
1598 /// and conditional compare operations. @returns an NZCV flags producing node
1599 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1600 /// transformation was not possible.
1601 /// On recursive invocations @p PushNegate may be set to true to have negation
1602 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1603 /// for the comparisons in the current subtree; @p Depth limits the search
1604 /// depth to avoid stack overflow.
1605 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1606     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1607     AArch64CC::CondCode Predicate) {
1608   // We're at a tree leaf, produce a conditional comparison operation.
1609   unsigned Opcode = Val->getOpcode();
1610   if (Opcode == ISD::SETCC) {
1611     SDValue LHS = Val->getOperand(0);
1612     SDValue RHS = Val->getOperand(1);
1613     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1614     bool isInteger = LHS.getValueType().isInteger();
1615     if (Negate)
1616       CC = getSetCCInverse(CC, isInteger);
1617     SDLoc DL(Val);
1618     // Determine OutCC and handle FP special case.
1619     if (isInteger) {
1620       OutCC = changeIntCCToAArch64CC(CC);
1621     } else {
1622       assert(LHS.getValueType().isFloatingPoint());
1623       AArch64CC::CondCode ExtraCC;
1624       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1625       // Some floating point conditions can't be tested with a single condition
1626       // code. Construct an additional comparison in this case.
1627       if (ExtraCC != AArch64CC::AL) {
1628         SDValue ExtraCmp;
1629         if (!CCOp.getNode())
1630           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1631         else
1632           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1633                                                ExtraCC, DL, DAG);
1634         CCOp = ExtraCmp;
1635         Predicate = ExtraCC;
1636       }
1637     }
1638
1639     // Produce a normal comparison if we are first in the chain
1640     if (!CCOp)
1641       return emitComparison(LHS, RHS, CC, DL, DAG);
1642     // Otherwise produce a ccmp.
1643     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1644                                      DAG);
1645   }
1646   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1647          "Valid conjunction/disjunction tree");
1648
1649   // Check if both sides can be transformed.
1650   SDValue LHS = Val->getOperand(0);
1651   SDValue RHS = Val->getOperand(1);
1652
1653   // In case of an OR we need to negate our operands and the result.
1654   // (A v B) <=> not(not(A) ^ not(B))
1655   bool NegateOpsAndResult = Opcode == ISD::OR;
1656   // We can negate the results of all previous operations by inverting the
1657   // predicate flags giving us a free negation for one side. The other side
1658   // must be negatable by itself.
1659   if (NegateOpsAndResult) {
1660     // See which side we can negate.
1661     bool CanNegateL;
1662     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1663     assert(isValidL && "Valid conjunction/disjunction tree");
1664     (void)isValidL;
1665
1666 #ifndef NDEBUG
1667     bool CanNegateR;
1668     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1669     assert(isValidR && "Valid conjunction/disjunction tree");
1670     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1671 #endif
1672
1673     // Order the side which we cannot negate to RHS so we can emit it first.
1674     if (!CanNegateL)
1675       std::swap(LHS, RHS);
1676   } else {
1677     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1678     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1679            "Valid conjunction/disjunction tree");
1680     // Order the side where we need to negate the output flags to RHS so it
1681     // gets emitted first.
1682     if (NeedsNegOutL)
1683       std::swap(LHS, RHS);
1684   }
1685
1686   // Emit RHS. If we want to negate the tree we only need to push a negate
1687   // through if we are already in a PushNegate case, otherwise we can negate
1688   // the "flags to test" afterwards.
1689   AArch64CC::CondCode RHSCC;
1690   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1691                                                    CCOp, Predicate);
1692   if (NegateOpsAndResult && !Negate)
1693     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1694   // Emit LHS. We may need to negate it.
1695   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1696                                                    NegateOpsAndResult, CmpR,
1697                                                    RHSCC);
1698   // If we transformed an OR to and AND then we have to negate the result
1699   // (or absorb the Negate parameter).
1700   if (NegateOpsAndResult && !Negate)
1701     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1702   return CmpL;
1703 }
1704
1705 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1706 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1707 /// \see emitConjunctionDisjunctionTreeRec().
1708 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1709                                               AArch64CC::CondCode &OutCC) {
1710   bool CanNegate;
1711   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1712     return SDValue();
1713
1714   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1715                                            AArch64CC::AL);
1716 }
1717
1718 /// @}
1719
1720 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1721                              SDValue &AArch64cc, SelectionDAG &DAG,
1722                              const SDLoc &dl) {
1723   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1724     EVT VT = RHS.getValueType();
1725     uint64_t C = RHSC->getZExtValue();
1726     if (!isLegalArithImmed(C)) {
1727       // Constant does not fit, try adjusting it by one?
1728       switch (CC) {
1729       default:
1730         break;
1731       case ISD::SETLT:
1732       case ISD::SETGE:
1733         if ((VT == MVT::i32 && C != 0x80000000 &&
1734              isLegalArithImmed((uint32_t)(C - 1))) ||
1735             (VT == MVT::i64 && C != 0x80000000ULL &&
1736              isLegalArithImmed(C - 1ULL))) {
1737           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1738           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1739           RHS = DAG.getConstant(C, dl, VT);
1740         }
1741         break;
1742       case ISD::SETULT:
1743       case ISD::SETUGE:
1744         if ((VT == MVT::i32 && C != 0 &&
1745              isLegalArithImmed((uint32_t)(C - 1))) ||
1746             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1747           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1748           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1749           RHS = DAG.getConstant(C, dl, VT);
1750         }
1751         break;
1752       case ISD::SETLE:
1753       case ISD::SETGT:
1754         if ((VT == MVT::i32 && C != INT32_MAX &&
1755              isLegalArithImmed((uint32_t)(C + 1))) ||
1756             (VT == MVT::i64 && C != INT64_MAX &&
1757              isLegalArithImmed(C + 1ULL))) {
1758           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1759           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1760           RHS = DAG.getConstant(C, dl, VT);
1761         }
1762         break;
1763       case ISD::SETULE:
1764       case ISD::SETUGT:
1765         if ((VT == MVT::i32 && C != UINT32_MAX &&
1766              isLegalArithImmed((uint32_t)(C + 1))) ||
1767             (VT == MVT::i64 && C != UINT64_MAX &&
1768              isLegalArithImmed(C + 1ULL))) {
1769           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1770           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1771           RHS = DAG.getConstant(C, dl, VT);
1772         }
1773         break;
1774       }
1775     }
1776   }
1777   SDValue Cmp;
1778   AArch64CC::CondCode AArch64CC;
1779   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1780     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1781
1782     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1783     // For the i8 operand, the largest immediate is 255, so this can be easily
1784     // encoded in the compare instruction. For the i16 operand, however, the
1785     // largest immediate cannot be encoded in the compare.
1786     // Therefore, use a sign extending load and cmn to avoid materializing the
1787     // -1 constant. For example,
1788     // movz w1, #65535
1789     // ldrh w0, [x0, #0]
1790     // cmp w0, w1
1791     // >
1792     // ldrsh w0, [x0, #0]
1793     // cmn w0, #1
1794     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1795     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1796     // ensure both the LHS and RHS are truly zero extended and to make sure the
1797     // transformation is profitable.
1798     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1799         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1800         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1801         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1802       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1803       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1804         SDValue SExt =
1805             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1806                         DAG.getValueType(MVT::i16));
1807         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1808                                                    RHS.getValueType()),
1809                              CC, dl, DAG);
1810         AArch64CC = changeIntCCToAArch64CC(CC);
1811       }
1812     }
1813
1814     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1815       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1816         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1817           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1818       }
1819     }
1820   }
1821
1822   if (!Cmp) {
1823     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1824     AArch64CC = changeIntCCToAArch64CC(CC);
1825   }
1826   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1827   return Cmp;
1828 }
1829
1830 static std::pair<SDValue, SDValue>
1831 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1832   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1833          "Unsupported value type");
1834   SDValue Value, Overflow;
1835   SDLoc DL(Op);
1836   SDValue LHS = Op.getOperand(0);
1837   SDValue RHS = Op.getOperand(1);
1838   unsigned Opc = 0;
1839   switch (Op.getOpcode()) {
1840   default:
1841     llvm_unreachable("Unknown overflow instruction!");
1842   case ISD::SADDO:
1843     Opc = AArch64ISD::ADDS;
1844     CC = AArch64CC::VS;
1845     break;
1846   case ISD::UADDO:
1847     Opc = AArch64ISD::ADDS;
1848     CC = AArch64CC::HS;
1849     break;
1850   case ISD::SSUBO:
1851     Opc = AArch64ISD::SUBS;
1852     CC = AArch64CC::VS;
1853     break;
1854   case ISD::USUBO:
1855     Opc = AArch64ISD::SUBS;
1856     CC = AArch64CC::LO;
1857     break;
1858   // Multiply needs a little bit extra work.
1859   case ISD::SMULO:
1860   case ISD::UMULO: {
1861     CC = AArch64CC::NE;
1862     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1863     if (Op.getValueType() == MVT::i32) {
1864       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1865       // For a 32 bit multiply with overflow check we want the instruction
1866       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1867       // need to generate the following pattern:
1868       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1869       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1870       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1871       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1872       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1873                                 DAG.getConstant(0, DL, MVT::i64));
1874       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1875       // operation. We need to clear out the upper 32 bits, because we used a
1876       // widening multiply that wrote all 64 bits. In the end this should be a
1877       // noop.
1878       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1879       if (IsSigned) {
1880         // The signed overflow check requires more than just a simple check for
1881         // any bit set in the upper 32 bits of the result. These bits could be
1882         // just the sign bits of a negative number. To perform the overflow
1883         // check we have to arithmetic shift right the 32nd bit of the result by
1884         // 31 bits. Then we compare the result to the upper 32 bits.
1885         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1886                                         DAG.getConstant(32, DL, MVT::i64));
1887         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1888         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1889                                         DAG.getConstant(31, DL, MVT::i64));
1890         // It is important that LowerBits is last, otherwise the arithmetic
1891         // shift will not be folded into the compare (SUBS).
1892         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1893         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1894                        .getValue(1);
1895       } else {
1896         // The overflow check for unsigned multiply is easy. We only need to
1897         // check if any of the upper 32 bits are set. This can be done with a
1898         // CMP (shifted register). For that we need to generate the following
1899         // pattern:
1900         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1901         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1902                                         DAG.getConstant(32, DL, MVT::i64));
1903         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1904         Overflow =
1905             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1906                         DAG.getConstant(0, DL, MVT::i64),
1907                         UpperBits).getValue(1);
1908       }
1909       break;
1910     }
1911     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1912     // For the 64 bit multiply
1913     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1914     if (IsSigned) {
1915       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1916       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1917                                       DAG.getConstant(63, DL, MVT::i64));
1918       // It is important that LowerBits is last, otherwise the arithmetic
1919       // shift will not be folded into the compare (SUBS).
1920       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1921       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1922                      .getValue(1);
1923     } else {
1924       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1925       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1926       Overflow =
1927           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1928                       DAG.getConstant(0, DL, MVT::i64),
1929                       UpperBits).getValue(1);
1930     }
1931     break;
1932   }
1933   } // switch (...)
1934
1935   if (Opc) {
1936     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1937
1938     // Emit the AArch64 operation with overflow check.
1939     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1940     Overflow = Value.getValue(1);
1941   }
1942   return std::make_pair(Value, Overflow);
1943 }
1944
1945 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1946                                              RTLIB::Libcall Call) const {
1947   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1948   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1949 }
1950
1951 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1952   SDValue Sel = Op.getOperand(0);
1953   SDValue Other = Op.getOperand(1);
1954
1955   // If neither operand is a SELECT_CC, give up.
1956   if (Sel.getOpcode() != ISD::SELECT_CC)
1957     std::swap(Sel, Other);
1958   if (Sel.getOpcode() != ISD::SELECT_CC)
1959     return Op;
1960
1961   // The folding we want to perform is:
1962   // (xor x, (select_cc a, b, cc, 0, -1) )
1963   //   -->
1964   // (csel x, (xor x, -1), cc ...)
1965   //
1966   // The latter will get matched to a CSINV instruction.
1967
1968   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1969   SDValue LHS = Sel.getOperand(0);
1970   SDValue RHS = Sel.getOperand(1);
1971   SDValue TVal = Sel.getOperand(2);
1972   SDValue FVal = Sel.getOperand(3);
1973   SDLoc dl(Sel);
1974
1975   // FIXME: This could be generalized to non-integer comparisons.
1976   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1977     return Op;
1978
1979   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1980   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1981
1982   // The values aren't constants, this isn't the pattern we're looking for.
1983   if (!CFVal || !CTVal)
1984     return Op;
1985
1986   // We can commute the SELECT_CC by inverting the condition.  This
1987   // might be needed to make this fit into a CSINV pattern.
1988   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1989     std::swap(TVal, FVal);
1990     std::swap(CTVal, CFVal);
1991     CC = ISD::getSetCCInverse(CC, true);
1992   }
1993
1994   // If the constants line up, perform the transform!
1995   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1996     SDValue CCVal;
1997     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1998
1999     FVal = Other;
2000     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2001                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2002
2003     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2004                        CCVal, Cmp);
2005   }
2006
2007   return Op;
2008 }
2009
2010 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2011   EVT VT = Op.getValueType();
2012
2013   // Let legalize expand this if it isn't a legal type yet.
2014   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2015     return SDValue();
2016
2017   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2018
2019   unsigned Opc;
2020   bool ExtraOp = false;
2021   switch (Op.getOpcode()) {
2022   default:
2023     llvm_unreachable("Invalid code");
2024   case ISD::ADDC:
2025     Opc = AArch64ISD::ADDS;
2026     break;
2027   case ISD::SUBC:
2028     Opc = AArch64ISD::SUBS;
2029     break;
2030   case ISD::ADDE:
2031     Opc = AArch64ISD::ADCS;
2032     ExtraOp = true;
2033     break;
2034   case ISD::SUBE:
2035     Opc = AArch64ISD::SBCS;
2036     ExtraOp = true;
2037     break;
2038   }
2039
2040   if (!ExtraOp)
2041     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2042   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2043                      Op.getOperand(2));
2044 }
2045
2046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2047   // Let legalize expand this if it isn't a legal type yet.
2048   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2049     return SDValue();
2050
2051   SDLoc dl(Op);
2052   AArch64CC::CondCode CC;
2053   // The actual operation that sets the overflow or carry flag.
2054   SDValue Value, Overflow;
2055   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2056
2057   // We use 0 and 1 as false and true values.
2058   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2059   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2060
2061   // We use an inverted condition, because the conditional select is inverted
2062   // too. This will allow it to be selected to a single instruction:
2063   // CSINC Wd, WZR, WZR, invert(cond).
2064   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2065   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2066                          CCVal, Overflow);
2067
2068   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2069   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2070 }
2071
2072 // Prefetch operands are:
2073 // 1: Address to prefetch
2074 // 2: bool isWrite
2075 // 3: int locality (0 = no locality ... 3 = extreme locality)
2076 // 4: bool isDataCache
2077 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2078   SDLoc DL(Op);
2079   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2080   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2081   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2082
2083   bool IsStream = !Locality;
2084   // When the locality number is set
2085   if (Locality) {
2086     // The front-end should have filtered out the out-of-range values
2087     assert(Locality <= 3 && "Prefetch locality out-of-range");
2088     // The locality degree is the opposite of the cache speed.
2089     // Put the number the other way around.
2090     // The encoding starts at 0 for level 1
2091     Locality = 3 - Locality;
2092   }
2093
2094   // built the mask value encoding the expected behavior.
2095   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2096                    (!IsData << 3) |     // IsDataCache bit
2097                    (Locality << 1) |    // Cache level bits
2098                    (unsigned)IsStream;  // Stream bit
2099   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2100                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2101 }
2102
2103 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2104                                               SelectionDAG &DAG) const {
2105   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2106
2107   RTLIB::Libcall LC;
2108   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2109
2110   return LowerF128Call(Op, DAG, LC);
2111 }
2112
2113 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2114                                              SelectionDAG &DAG) const {
2115   if (Op.getOperand(0).getValueType() != MVT::f128) {
2116     // It's legal except when f128 is involved
2117     return Op;
2118   }
2119
2120   RTLIB::Libcall LC;
2121   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2122
2123   // FP_ROUND node has a second operand indicating whether it is known to be
2124   // precise. That doesn't take part in the LibCall so we can't directly use
2125   // LowerF128Call.
2126   SDValue SrcVal = Op.getOperand(0);
2127   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2128                      SDLoc(Op)).first;
2129 }
2130
2131 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2132   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2133   // Any additional optimization in this function should be recorded
2134   // in the cost tables.
2135   EVT InVT = Op.getOperand(0).getValueType();
2136   EVT VT = Op.getValueType();
2137   unsigned NumElts = InVT.getVectorNumElements();
2138
2139   // f16 vectors are promoted to f32 before a conversion.
2140   if (InVT.getVectorElementType() == MVT::f16) {
2141     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2142     SDLoc dl(Op);
2143     return DAG.getNode(
2144         Op.getOpcode(), dl, Op.getValueType(),
2145         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2146   }
2147
2148   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2149     SDLoc dl(Op);
2150     SDValue Cv =
2151         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2152                     Op.getOperand(0));
2153     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2154   }
2155
2156   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2157     SDLoc dl(Op);
2158     MVT ExtVT =
2159         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2160                          VT.getVectorNumElements());
2161     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2162     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2163   }
2164
2165   // Type changing conversions are illegal.
2166   return Op;
2167 }
2168
2169 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2170                                               SelectionDAG &DAG) const {
2171   if (Op.getOperand(0).getValueType().isVector())
2172     return LowerVectorFP_TO_INT(Op, DAG);
2173
2174   // f16 conversions are promoted to f32.
2175   if (Op.getOperand(0).getValueType() == MVT::f16) {
2176     SDLoc dl(Op);
2177     return DAG.getNode(
2178         Op.getOpcode(), dl, Op.getValueType(),
2179         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2180   }
2181
2182   if (Op.getOperand(0).getValueType() != MVT::f128) {
2183     // It's legal except when f128 is involved
2184     return Op;
2185   }
2186
2187   RTLIB::Libcall LC;
2188   if (Op.getOpcode() == ISD::FP_TO_SINT)
2189     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2190   else
2191     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2192
2193   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2194   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2195 }
2196
2197 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2198   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2199   // Any additional optimization in this function should be recorded
2200   // in the cost tables.
2201   EVT VT = Op.getValueType();
2202   SDLoc dl(Op);
2203   SDValue In = Op.getOperand(0);
2204   EVT InVT = In.getValueType();
2205
2206   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2207     MVT CastVT =
2208         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2209                          InVT.getVectorNumElements());
2210     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2211     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2212   }
2213
2214   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2215     unsigned CastOpc =
2216         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2217     EVT CastVT = VT.changeVectorElementTypeToInteger();
2218     In = DAG.getNode(CastOpc, dl, CastVT, In);
2219     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2220   }
2221
2222   return Op;
2223 }
2224
2225 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2226                                             SelectionDAG &DAG) const {
2227   if (Op.getValueType().isVector())
2228     return LowerVectorINT_TO_FP(Op, DAG);
2229
2230   // f16 conversions are promoted to f32.
2231   if (Op.getValueType() == MVT::f16) {
2232     SDLoc dl(Op);
2233     return DAG.getNode(
2234         ISD::FP_ROUND, dl, MVT::f16,
2235         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2236         DAG.getIntPtrConstant(0, dl));
2237   }
2238
2239   // i128 conversions are libcalls.
2240   if (Op.getOperand(0).getValueType() == MVT::i128)
2241     return SDValue();
2242
2243   // Other conversions are legal, unless it's to the completely software-based
2244   // fp128.
2245   if (Op.getValueType() != MVT::f128)
2246     return Op;
2247
2248   RTLIB::Libcall LC;
2249   if (Op.getOpcode() == ISD::SINT_TO_FP)
2250     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2251   else
2252     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2253
2254   return LowerF128Call(Op, DAG, LC);
2255 }
2256
2257 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2258                                             SelectionDAG &DAG) const {
2259   // For iOS, we want to call an alternative entry point: __sincos_stret,
2260   // which returns the values in two S / D registers.
2261   SDLoc dl(Op);
2262   SDValue Arg = Op.getOperand(0);
2263   EVT ArgVT = Arg.getValueType();
2264   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2265
2266   ArgListTy Args;
2267   ArgListEntry Entry;
2268
2269   Entry.Node = Arg;
2270   Entry.Ty = ArgTy;
2271   Entry.IsSExt = false;
2272   Entry.IsZExt = false;
2273   Args.push_back(Entry);
2274
2275   const char *LibcallName =
2276       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2277   SDValue Callee =
2278       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2279
2280   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2281   TargetLowering::CallLoweringInfo CLI(DAG);
2282   CLI.setDebugLoc(dl)
2283       .setChain(DAG.getEntryNode())
2284       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2285
2286   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2287   return CallResult.first;
2288 }
2289
2290 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2291   if (Op.getValueType() != MVT::f16)
2292     return SDValue();
2293
2294   assert(Op.getOperand(0).getValueType() == MVT::i16);
2295   SDLoc DL(Op);
2296
2297   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2298   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2299   return SDValue(
2300       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2301                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2302       0);
2303 }
2304
2305 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2306   if (OrigVT.getSizeInBits() >= 64)
2307     return OrigVT;
2308
2309   assert(OrigVT.isSimple() && "Expecting a simple value type");
2310
2311   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2312   switch (OrigSimpleTy) {
2313   default: llvm_unreachable("Unexpected Vector Type");
2314   case MVT::v2i8:
2315   case MVT::v2i16:
2316      return MVT::v2i32;
2317   case MVT::v4i8:
2318     return  MVT::v4i16;
2319   }
2320 }
2321
2322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2323                                                  const EVT &OrigTy,
2324                                                  const EVT &ExtTy,
2325                                                  unsigned ExtOpcode) {
2326   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2327   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2328   // 64-bits we need to insert a new extension so that it will be 64-bits.
2329   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2330   if (OrigTy.getSizeInBits() >= 64)
2331     return N;
2332
2333   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2334   EVT NewVT = getExtensionTo64Bits(OrigTy);
2335
2336   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2337 }
2338
2339 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2340                                    bool isSigned) {
2341   EVT VT = N->getValueType(0);
2342
2343   if (N->getOpcode() != ISD::BUILD_VECTOR)
2344     return false;
2345
2346   for (const SDValue &Elt : N->op_values()) {
2347     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2348       unsigned EltSize = VT.getScalarSizeInBits();
2349       unsigned HalfSize = EltSize / 2;
2350       if (isSigned) {
2351         if (!isIntN(HalfSize, C->getSExtValue()))
2352           return false;
2353       } else {
2354         if (!isUIntN(HalfSize, C->getZExtValue()))
2355           return false;
2356       }
2357       continue;
2358     }
2359     return false;
2360   }
2361
2362   return true;
2363 }
2364
2365 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2366   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2367     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2368                                              N->getOperand(0)->getValueType(0),
2369                                              N->getValueType(0),
2370                                              N->getOpcode());
2371
2372   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2373   EVT VT = N->getValueType(0);
2374   SDLoc dl(N);
2375   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2376   unsigned NumElts = VT.getVectorNumElements();
2377   MVT TruncVT = MVT::getIntegerVT(EltSize);
2378   SmallVector<SDValue, 8> Ops;
2379   for (unsigned i = 0; i != NumElts; ++i) {
2380     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2381     const APInt &CInt = C->getAPIntValue();
2382     // Element types smaller than 32 bits are not legal, so use i32 elements.
2383     // The values are implicitly truncated so sext vs. zext doesn't matter.
2384     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2385   }
2386   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2387 }
2388
2389 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2390   return N->getOpcode() == ISD::SIGN_EXTEND ||
2391          isExtendedBUILD_VECTOR(N, DAG, true);
2392 }
2393
2394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2395   return N->getOpcode() == ISD::ZERO_EXTEND ||
2396          isExtendedBUILD_VECTOR(N, DAG, false);
2397 }
2398
2399 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2400   unsigned Opcode = N->getOpcode();
2401   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2402     SDNode *N0 = N->getOperand(0).getNode();
2403     SDNode *N1 = N->getOperand(1).getNode();
2404     return N0->hasOneUse() && N1->hasOneUse() &&
2405       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2406   }
2407   return false;
2408 }
2409
2410 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2411   unsigned Opcode = N->getOpcode();
2412   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2413     SDNode *N0 = N->getOperand(0).getNode();
2414     SDNode *N1 = N->getOperand(1).getNode();
2415     return N0->hasOneUse() && N1->hasOneUse() &&
2416       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2417   }
2418   return false;
2419 }
2420
2421 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2422   // Multiplications are only custom-lowered for 128-bit vectors so that
2423   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2424   EVT VT = Op.getValueType();
2425   assert(VT.is128BitVector() && VT.isInteger() &&
2426          "unexpected type for custom-lowering ISD::MUL");
2427   SDNode *N0 = Op.getOperand(0).getNode();
2428   SDNode *N1 = Op.getOperand(1).getNode();
2429   unsigned NewOpc = 0;
2430   bool isMLA = false;
2431   bool isN0SExt = isSignExtended(N0, DAG);
2432   bool isN1SExt = isSignExtended(N1, DAG);
2433   if (isN0SExt && isN1SExt)
2434     NewOpc = AArch64ISD::SMULL;
2435   else {
2436     bool isN0ZExt = isZeroExtended(N0, DAG);
2437     bool isN1ZExt = isZeroExtended(N1, DAG);
2438     if (isN0ZExt && isN1ZExt)
2439       NewOpc = AArch64ISD::UMULL;
2440     else if (isN1SExt || isN1ZExt) {
2441       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2442       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2443       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2444         NewOpc = AArch64ISD::SMULL;
2445         isMLA = true;
2446       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2447         NewOpc =  AArch64ISD::UMULL;
2448         isMLA = true;
2449       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2450         std::swap(N0, N1);
2451         NewOpc =  AArch64ISD::UMULL;
2452         isMLA = true;
2453       }
2454     }
2455
2456     if (!NewOpc) {
2457       if (VT == MVT::v2i64)
2458         // Fall through to expand this.  It is not legal.
2459         return SDValue();
2460       else
2461         // Other vector multiplications are legal.
2462         return Op;
2463     }
2464   }
2465
2466   // Legalize to a S/UMULL instruction
2467   SDLoc DL(Op);
2468   SDValue Op0;
2469   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2470   if (!isMLA) {
2471     Op0 = skipExtensionForVectorMULL(N0, DAG);
2472     assert(Op0.getValueType().is64BitVector() &&
2473            Op1.getValueType().is64BitVector() &&
2474            "unexpected types for extended operands to VMULL");
2475     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2476   }
2477   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2478   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2479   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2480   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2481   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2482   EVT Op1VT = Op1.getValueType();
2483   return DAG.getNode(N0->getOpcode(), DL, VT,
2484                      DAG.getNode(NewOpc, DL, VT,
2485                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2486                      DAG.getNode(NewOpc, DL, VT,
2487                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2488 }
2489
2490 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2491                                                      SelectionDAG &DAG) const {
2492   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2493   SDLoc dl(Op);
2494   switch (IntNo) {
2495   default: return SDValue();    // Don't custom lower most intrinsics.
2496   case Intrinsic::thread_pointer: {
2497     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2499   }
2500   case Intrinsic::aarch64_neon_abs:
2501     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2502                        Op.getOperand(1));
2503   case Intrinsic::aarch64_neon_smax:
2504     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2505                        Op.getOperand(1), Op.getOperand(2));
2506   case Intrinsic::aarch64_neon_umax:
2507     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2508                        Op.getOperand(1), Op.getOperand(2));
2509   case Intrinsic::aarch64_neon_smin:
2510     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2511                        Op.getOperand(1), Op.getOperand(2));
2512   case Intrinsic::aarch64_neon_umin:
2513     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2514                        Op.getOperand(1), Op.getOperand(2));
2515   }
2516 }
2517
2518 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2519                                               SelectionDAG &DAG) const {
2520   switch (Op.getOpcode()) {
2521   default:
2522     llvm_unreachable("unimplemented operand");
2523     return SDValue();
2524   case ISD::BITCAST:
2525     return LowerBITCAST(Op, DAG);
2526   case ISD::GlobalAddress:
2527     return LowerGlobalAddress(Op, DAG);
2528   case ISD::GlobalTLSAddress:
2529     return LowerGlobalTLSAddress(Op, DAG);
2530   case ISD::SETCC:
2531     return LowerSETCC(Op, DAG);
2532   case ISD::BR_CC:
2533     return LowerBR_CC(Op, DAG);
2534   case ISD::SELECT:
2535     return LowerSELECT(Op, DAG);
2536   case ISD::SELECT_CC:
2537     return LowerSELECT_CC(Op, DAG);
2538   case ISD::JumpTable:
2539     return LowerJumpTable(Op, DAG);
2540   case ISD::ConstantPool:
2541     return LowerConstantPool(Op, DAG);
2542   case ISD::BlockAddress:
2543     return LowerBlockAddress(Op, DAG);
2544   case ISD::VASTART:
2545     return LowerVASTART(Op, DAG);
2546   case ISD::VACOPY:
2547     return LowerVACOPY(Op, DAG);
2548   case ISD::VAARG:
2549     return LowerVAARG(Op, DAG);
2550   case ISD::ADDC:
2551   case ISD::ADDE:
2552   case ISD::SUBC:
2553   case ISD::SUBE:
2554     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2555   case ISD::SADDO:
2556   case ISD::UADDO:
2557   case ISD::SSUBO:
2558   case ISD::USUBO:
2559   case ISD::SMULO:
2560   case ISD::UMULO:
2561     return LowerXALUO(Op, DAG);
2562   case ISD::FADD:
2563     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2564   case ISD::FSUB:
2565     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2566   case ISD::FMUL:
2567     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2568   case ISD::FDIV:
2569     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2570   case ISD::FP_ROUND:
2571     return LowerFP_ROUND(Op, DAG);
2572   case ISD::FP_EXTEND:
2573     return LowerFP_EXTEND(Op, DAG);
2574   case ISD::FRAMEADDR:
2575     return LowerFRAMEADDR(Op, DAG);
2576   case ISD::RETURNADDR:
2577     return LowerRETURNADDR(Op, DAG);
2578   case ISD::INSERT_VECTOR_ELT:
2579     return LowerINSERT_VECTOR_ELT(Op, DAG);
2580   case ISD::EXTRACT_VECTOR_ELT:
2581     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2582   case ISD::BUILD_VECTOR:
2583     return LowerBUILD_VECTOR(Op, DAG);
2584   case ISD::VECTOR_SHUFFLE:
2585     return LowerVECTOR_SHUFFLE(Op, DAG);
2586   case ISD::EXTRACT_SUBVECTOR:
2587     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2588   case ISD::SRA:
2589   case ISD::SRL:
2590   case ISD::SHL:
2591     return LowerVectorSRA_SRL_SHL(Op, DAG);
2592   case ISD::SHL_PARTS:
2593     return LowerShiftLeftParts(Op, DAG);
2594   case ISD::SRL_PARTS:
2595   case ISD::SRA_PARTS:
2596     return LowerShiftRightParts(Op, DAG);
2597   case ISD::CTPOP:
2598     return LowerCTPOP(Op, DAG);
2599   case ISD::FCOPYSIGN:
2600     return LowerFCOPYSIGN(Op, DAG);
2601   case ISD::AND:
2602     return LowerVectorAND(Op, DAG);
2603   case ISD::OR:
2604     return LowerVectorOR(Op, DAG);
2605   case ISD::XOR:
2606     return LowerXOR(Op, DAG);
2607   case ISD::PREFETCH:
2608     return LowerPREFETCH(Op, DAG);
2609   case ISD::SINT_TO_FP:
2610   case ISD::UINT_TO_FP:
2611     return LowerINT_TO_FP(Op, DAG);
2612   case ISD::FP_TO_SINT:
2613   case ISD::FP_TO_UINT:
2614     return LowerFP_TO_INT(Op, DAG);
2615   case ISD::FSINCOS:
2616     return LowerFSINCOS(Op, DAG);
2617   case ISD::MUL:
2618     return LowerMUL(Op, DAG);
2619   case ISD::INTRINSIC_WO_CHAIN:
2620     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2621   case ISD::VECREDUCE_ADD:
2622   case ISD::VECREDUCE_SMAX:
2623   case ISD::VECREDUCE_SMIN:
2624   case ISD::VECREDUCE_UMAX:
2625   case ISD::VECREDUCE_UMIN:
2626   case ISD::VECREDUCE_FMAX:
2627   case ISD::VECREDUCE_FMIN:
2628     return LowerVECREDUCE(Op, DAG);
2629   }
2630 }
2631
2632 //===----------------------------------------------------------------------===//
2633 //                      Calling Convention Implementation
2634 //===----------------------------------------------------------------------===//
2635
2636 #include "AArch64GenCallingConv.inc"
2637
2638 /// Selects the correct CCAssignFn for a given CallingConvention value.
2639 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2640                                                      bool IsVarArg) const {
2641   switch (CC) {
2642   default:
2643     llvm_unreachable("Unsupported calling convention.");
2644   case CallingConv::WebKit_JS:
2645     return CC_AArch64_WebKit_JS;
2646   case CallingConv::GHC:
2647     return CC_AArch64_GHC;
2648   case CallingConv::C:
2649   case CallingConv::Fast:
2650   case CallingConv::PreserveMost:
2651   case CallingConv::CXX_FAST_TLS:
2652   case CallingConv::Swift:
2653     if (Subtarget->isTargetWindows() && IsVarArg)
2654       return CC_AArch64_Win64_VarArg;
2655     if (!Subtarget->isTargetDarwin())
2656       return CC_AArch64_AAPCS;
2657     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2658   case CallingConv::Win64:
2659     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2660   }
2661 }
2662
2663 CCAssignFn *
2664 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2665   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2666                                       : RetCC_AArch64_AAPCS;
2667 }
2668
2669 SDValue AArch64TargetLowering::LowerFormalArguments(
2670     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2671     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2672     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   MachineFrameInfo &MFI = MF.getFrameInfo();
2675   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2676
2677   // Assign locations to all of the incoming arguments.
2678   SmallVector<CCValAssign, 16> ArgLocs;
2679   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2680                  *DAG.getContext());
2681
2682   // At this point, Ins[].VT may already be promoted to i32. To correctly
2683   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2684   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2685   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2686   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2687   // LocVT.
2688   unsigned NumArgs = Ins.size();
2689   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2690   unsigned CurArgIdx = 0;
2691   for (unsigned i = 0; i != NumArgs; ++i) {
2692     MVT ValVT = Ins[i].VT;
2693     if (Ins[i].isOrigArg()) {
2694       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2695       CurArgIdx = Ins[i].getOrigArgIndex();
2696
2697       // Get type of the original argument.
2698       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2699                                   /*AllowUnknown*/ true);
2700       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2701       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2702       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2703         ValVT = MVT::i8;
2704       else if (ActualMVT == MVT::i16)
2705         ValVT = MVT::i16;
2706     }
2707     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2708     bool Res =
2709         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2710     assert(!Res && "Call operand has unhandled type");
2711     (void)Res;
2712   }
2713   assert(ArgLocs.size() == Ins.size());
2714   SmallVector<SDValue, 16> ArgValues;
2715   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2716     CCValAssign &VA = ArgLocs[i];
2717
2718     if (Ins[i].Flags.isByVal()) {
2719       // Byval is used for HFAs in the PCS, but the system should work in a
2720       // non-compliant manner for larger structs.
2721       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2722       int Size = Ins[i].Flags.getByValSize();
2723       unsigned NumRegs = (Size + 7) / 8;
2724
2725       // FIXME: This works on big-endian for composite byvals, which are the common
2726       // case. It should also work for fundamental types too.
2727       unsigned FrameIdx =
2728         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2729       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2730       InVals.push_back(FrameIdxN);
2731
2732       continue;
2733     }
2734
2735     if (VA.isRegLoc()) {
2736       // Arguments stored in registers.
2737       EVT RegVT = VA.getLocVT();
2738
2739       SDValue ArgValue;
2740       const TargetRegisterClass *RC;
2741
2742       if (RegVT == MVT::i32)
2743         RC = &AArch64::GPR32RegClass;
2744       else if (RegVT == MVT::i64)
2745         RC = &AArch64::GPR64RegClass;
2746       else if (RegVT == MVT::f16)
2747         RC = &AArch64::FPR16RegClass;
2748       else if (RegVT == MVT::f32)
2749         RC = &AArch64::FPR32RegClass;
2750       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2751         RC = &AArch64::FPR64RegClass;
2752       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2753         RC = &AArch64::FPR128RegClass;
2754       else
2755         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2756
2757       // Transform the arguments in physical registers into virtual ones.
2758       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2759       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2760
2761       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2762       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2763       // truncate to the right size.
2764       switch (VA.getLocInfo()) {
2765       default:
2766         llvm_unreachable("Unknown loc info!");
2767       case CCValAssign::Full:
2768         break;
2769       case CCValAssign::BCvt:
2770         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2771         break;
2772       case CCValAssign::AExt:
2773       case CCValAssign::SExt:
2774       case CCValAssign::ZExt:
2775         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2776         // nodes after our lowering.
2777         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2778         break;
2779       }
2780
2781       InVals.push_back(ArgValue);
2782
2783     } else { // VA.isRegLoc()
2784       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2785       unsigned ArgOffset = VA.getLocMemOffset();
2786       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2787
2788       uint32_t BEAlign = 0;
2789       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2790           !Ins[i].Flags.isInConsecutiveRegs())
2791         BEAlign = 8 - ArgSize;
2792
2793       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2794
2795       // Create load nodes to retrieve arguments from the stack.
2796       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2797       SDValue ArgValue;
2798
2799       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2800       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2801       MVT MemVT = VA.getValVT();
2802
2803       switch (VA.getLocInfo()) {
2804       default:
2805         break;
2806       case CCValAssign::BCvt:
2807         MemVT = VA.getLocVT();
2808         break;
2809       case CCValAssign::SExt:
2810         ExtType = ISD::SEXTLOAD;
2811         break;
2812       case CCValAssign::ZExt:
2813         ExtType = ISD::ZEXTLOAD;
2814         break;
2815       case CCValAssign::AExt:
2816         ExtType = ISD::EXTLOAD;
2817         break;
2818       }
2819
2820       ArgValue = DAG.getExtLoad(
2821           ExtType, DL, VA.getLocVT(), Chain, FIN,
2822           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2823           MemVT);
2824
2825       InVals.push_back(ArgValue);
2826     }
2827   }
2828
2829   // varargs
2830   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2831   if (isVarArg) {
2832     if (!Subtarget->isTargetDarwin() || IsWin64) {
2833       // The AAPCS variadic function ABI is identical to the non-variadic
2834       // one. As a result there may be more arguments in registers and we should
2835       // save them for future reference.
2836       // Win64 variadic functions also pass arguments in registers, but all float
2837       // arguments are passed in integer registers.
2838       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2839     }
2840
2841     // This will point to the next argument passed via stack.
2842     unsigned StackOffset = CCInfo.getNextStackOffset();
2843     // We currently pass all varargs at 8-byte alignment.
2844     StackOffset = ((StackOffset + 7) & ~7);
2845     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2846   }
2847
2848   unsigned StackArgSize = CCInfo.getNextStackOffset();
2849   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2850   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2851     // This is a non-standard ABI so by fiat I say we're allowed to make full
2852     // use of the stack area to be popped, which must be aligned to 16 bytes in
2853     // any case:
2854     StackArgSize = alignTo(StackArgSize, 16);
2855
2856     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2857     // a multiple of 16.
2858     FuncInfo->setArgumentStackToRestore(StackArgSize);
2859
2860     // This realignment carries over to the available bytes below. Our own
2861     // callers will guarantee the space is free by giving an aligned value to
2862     // CALLSEQ_START.
2863   }
2864   // Even if we're not expected to free up the space, it's useful to know how
2865   // much is there while considering tail calls (because we can reuse it).
2866   FuncInfo->setBytesInStackArgArea(StackArgSize);
2867
2868   return Chain;
2869 }
2870
2871 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2872                                                 SelectionDAG &DAG,
2873                                                 const SDLoc &DL,
2874                                                 SDValue &Chain) const {
2875   MachineFunction &MF = DAG.getMachineFunction();
2876   MachineFrameInfo &MFI = MF.getFrameInfo();
2877   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2878   auto PtrVT = getPointerTy(DAG.getDataLayout());
2879   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2880
2881   SmallVector<SDValue, 8> MemOps;
2882
2883   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2884                                           AArch64::X3, AArch64::X4, AArch64::X5,
2885                                           AArch64::X6, AArch64::X7 };
2886   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2887   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2888
2889   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2890   int GPRIdx = 0;
2891   if (GPRSaveSize != 0) {
2892     if (IsWin64)
2893       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
2894     else
2895       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2896
2897     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2898
2899     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2900       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2901       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2902       SDValue Store = DAG.getStore(
2903           Val.getValue(1), DL, Val, FIN,
2904           IsWin64
2905               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2906                                                   GPRIdx,
2907                                                   (i - FirstVariadicGPR) * 8)
2908               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2909       MemOps.push_back(Store);
2910       FIN =
2911           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2912     }
2913   }
2914   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2915   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2916
2917   if (Subtarget->hasFPARMv8() && !IsWin64) {
2918     static const MCPhysReg FPRArgRegs[] = {
2919         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2920         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2921     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2922     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2923
2924     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2925     int FPRIdx = 0;
2926     if (FPRSaveSize != 0) {
2927       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2928
2929       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2930
2931       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2932         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2933         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2934
2935         SDValue Store = DAG.getStore(
2936             Val.getValue(1), DL, Val, FIN,
2937             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2938         MemOps.push_back(Store);
2939         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2940                           DAG.getConstant(16, DL, PtrVT));
2941       }
2942     }
2943     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2944     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2945   }
2946
2947   if (!MemOps.empty()) {
2948     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2949   }
2950 }
2951
2952 /// LowerCallResult - Lower the result values of a call into the
2953 /// appropriate copies out of appropriate physical registers.
2954 SDValue AArch64TargetLowering::LowerCallResult(
2955     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2956     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2957     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2958     SDValue ThisVal) const {
2959   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2960                           ? RetCC_AArch64_WebKit_JS
2961                           : RetCC_AArch64_AAPCS;
2962   // Assign locations to each value returned by this call.
2963   SmallVector<CCValAssign, 16> RVLocs;
2964   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2965                  *DAG.getContext());
2966   CCInfo.AnalyzeCallResult(Ins, RetCC);
2967
2968   // Copy all of the result registers out of their specified physreg.
2969   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2970     CCValAssign VA = RVLocs[i];
2971
2972     // Pass 'this' value directly from the argument to return value, to avoid
2973     // reg unit interference
2974     if (i == 0 && isThisReturn) {
2975       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2976              "unexpected return calling convention register assignment");
2977       InVals.push_back(ThisVal);
2978       continue;
2979     }
2980
2981     SDValue Val =
2982         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2983     Chain = Val.getValue(1);
2984     InFlag = Val.getValue(2);
2985
2986     switch (VA.getLocInfo()) {
2987     default:
2988       llvm_unreachable("Unknown loc info!");
2989     case CCValAssign::Full:
2990       break;
2991     case CCValAssign::BCvt:
2992       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2993       break;
2994     }
2995
2996     InVals.push_back(Val);
2997   }
2998
2999   return Chain;
3000 }
3001
3002 /// Return true if the calling convention is one that we can guarantee TCO for.
3003 static bool canGuaranteeTCO(CallingConv::ID CC) {
3004   return CC == CallingConv::Fast;
3005 }
3006
3007 /// Return true if we might ever do TCO for calls with this calling convention.
3008 static bool mayTailCallThisCC(CallingConv::ID CC) {
3009   switch (CC) {
3010   case CallingConv::C:
3011   case CallingConv::PreserveMost:
3012   case CallingConv::Swift:
3013     return true;
3014   default:
3015     return canGuaranteeTCO(CC);
3016   }
3017 }
3018
3019 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3020     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3021     const SmallVectorImpl<ISD::OutputArg> &Outs,
3022     const SmallVectorImpl<SDValue> &OutVals,
3023     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3024   if (!mayTailCallThisCC(CalleeCC))
3025     return false;
3026
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   const Function *CallerF = MF.getFunction();
3029   CallingConv::ID CallerCC = CallerF->getCallingConv();
3030   bool CCMatch = CallerCC == CalleeCC;
3031
3032   // Byval parameters hand the function a pointer directly into the stack area
3033   // we want to reuse during a tail call. Working around this *is* possible (see
3034   // X86) but less efficient and uglier in LowerCall.
3035   for (Function::const_arg_iterator i = CallerF->arg_begin(),
3036                                     e = CallerF->arg_end();
3037        i != e; ++i)
3038     if (i->hasByValAttr())
3039       return false;
3040
3041   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3042     return canGuaranteeTCO(CalleeCC) && CCMatch;
3043
3044   // Externally-defined functions with weak linkage should not be
3045   // tail-called on AArch64 when the OS does not support dynamic
3046   // pre-emption of symbols, as the AAELF spec requires normal calls
3047   // to undefined weak functions to be replaced with a NOP or jump to the
3048   // next instruction. The behaviour of branch instructions in this
3049   // situation (as used for tail calls) is implementation-defined, so we
3050   // cannot rely on the linker replacing the tail call with a return.
3051   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3052     const GlobalValue *GV = G->getGlobal();
3053     const Triple &TT = getTargetMachine().getTargetTriple();
3054     if (GV->hasExternalWeakLinkage() &&
3055         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3056       return false;
3057   }
3058
3059   // Now we search for cases where we can use a tail call without changing the
3060   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3061   // concept.
3062
3063   // I want anyone implementing a new calling convention to think long and hard
3064   // about this assert.
3065   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3066          "Unexpected variadic calling convention");
3067
3068   LLVMContext &C = *DAG.getContext();
3069   if (isVarArg && !Outs.empty()) {
3070     // At least two cases here: if caller is fastcc then we can't have any
3071     // memory arguments (we'd be expected to clean up the stack afterwards). If
3072     // caller is C then we could potentially use its argument area.
3073
3074     // FIXME: for now we take the most conservative of these in both cases:
3075     // disallow all variadic memory operands.
3076     SmallVector<CCValAssign, 16> ArgLocs;
3077     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3078
3079     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3080     for (const CCValAssign &ArgLoc : ArgLocs)
3081       if (!ArgLoc.isRegLoc())
3082         return false;
3083   }
3084
3085   // Check that the call results are passed in the same way.
3086   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3087                                   CCAssignFnForCall(CalleeCC, isVarArg),
3088                                   CCAssignFnForCall(CallerCC, isVarArg)))
3089     return false;
3090   // The callee has to preserve all registers the caller needs to preserve.
3091   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3092   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3093   if (!CCMatch) {
3094     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3095     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3096       return false;
3097   }
3098
3099   // Nothing more to check if the callee is taking no arguments
3100   if (Outs.empty())
3101     return true;
3102
3103   SmallVector<CCValAssign, 16> ArgLocs;
3104   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3105
3106   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3107
3108   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3109
3110   // If the stack arguments for this call do not fit into our own save area then
3111   // the call cannot be made tail.
3112   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3113     return false;
3114
3115   const MachineRegisterInfo &MRI = MF.getRegInfo();
3116   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3117     return false;
3118
3119   return true;
3120 }
3121
3122 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3123                                                    SelectionDAG &DAG,
3124                                                    MachineFrameInfo &MFI,
3125                                                    int ClobberedFI) const {
3126   SmallVector<SDValue, 8> ArgChains;
3127   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3128   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3129
3130   // Include the original chain at the beginning of the list. When this is
3131   // used by target LowerCall hooks, this helps legalize find the
3132   // CALLSEQ_BEGIN node.
3133   ArgChains.push_back(Chain);
3134
3135   // Add a chain value for each stack argument corresponding
3136   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3137                             UE = DAG.getEntryNode().getNode()->use_end();
3138        U != UE; ++U)
3139     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3140       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3141         if (FI->getIndex() < 0) {
3142           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3143           int64_t InLastByte = InFirstByte;
3144           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3145
3146           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3147               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3148             ArgChains.push_back(SDValue(L, 1));
3149         }
3150
3151   // Build a tokenfactor for all the chains.
3152   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3153 }
3154
3155 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3156                                                    bool TailCallOpt) const {
3157   return CallCC == CallingConv::Fast && TailCallOpt;
3158 }
3159
3160 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3161 /// and add input and output parameter nodes.
3162 SDValue
3163 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3164                                  SmallVectorImpl<SDValue> &InVals) const {
3165   SelectionDAG &DAG = CLI.DAG;
3166   SDLoc &DL = CLI.DL;
3167   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3168   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3169   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3170   SDValue Chain = CLI.Chain;
3171   SDValue Callee = CLI.Callee;
3172   bool &IsTailCall = CLI.IsTailCall;
3173   CallingConv::ID CallConv = CLI.CallConv;
3174   bool IsVarArg = CLI.IsVarArg;
3175
3176   MachineFunction &MF = DAG.getMachineFunction();
3177   bool IsThisReturn = false;
3178
3179   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3180   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3181   bool IsSibCall = false;
3182
3183   if (IsTailCall) {
3184     // Check if it's really possible to do a tail call.
3185     IsTailCall = isEligibleForTailCallOptimization(
3186         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3187     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3188       report_fatal_error("failed to perform tail call elimination on a call "
3189                          "site marked musttail");
3190
3191     // A sibling call is one where we're under the usual C ABI and not planning
3192     // to change that but can still do a tail call:
3193     if (!TailCallOpt && IsTailCall)
3194       IsSibCall = true;
3195
3196     if (IsTailCall)
3197       ++NumTailCalls;
3198   }
3199
3200   // Analyze operands of the call, assigning locations to each operand.
3201   SmallVector<CCValAssign, 16> ArgLocs;
3202   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3203                  *DAG.getContext());
3204
3205   if (IsVarArg) {
3206     // Handle fixed and variable vector arguments differently.
3207     // Variable vector arguments always go into memory.
3208     unsigned NumArgs = Outs.size();
3209
3210     for (unsigned i = 0; i != NumArgs; ++i) {
3211       MVT ArgVT = Outs[i].VT;
3212       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3213       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3214                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3215       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3216       assert(!Res && "Call operand has unhandled type");
3217       (void)Res;
3218     }
3219   } else {
3220     // At this point, Outs[].VT may already be promoted to i32. To correctly
3221     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3222     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3223     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3224     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3225     // LocVT.
3226     unsigned NumArgs = Outs.size();
3227     for (unsigned i = 0; i != NumArgs; ++i) {
3228       MVT ValVT = Outs[i].VT;
3229       // Get type of the original argument.
3230       EVT ActualVT = getValueType(DAG.getDataLayout(),
3231                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3232                                   /*AllowUnknown*/ true);
3233       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3234       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3235       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3236       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3237         ValVT = MVT::i8;
3238       else if (ActualMVT == MVT::i16)
3239         ValVT = MVT::i16;
3240
3241       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3242       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3243       assert(!Res && "Call operand has unhandled type");
3244       (void)Res;
3245     }
3246   }
3247
3248   // Get a count of how many bytes are to be pushed on the stack.
3249   unsigned NumBytes = CCInfo.getNextStackOffset();
3250
3251   if (IsSibCall) {
3252     // Since we're not changing the ABI to make this a tail call, the memory
3253     // operands are already available in the caller's incoming argument space.
3254     NumBytes = 0;
3255   }
3256
3257   // FPDiff is the byte offset of the call's argument area from the callee's.
3258   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3259   // by this amount for a tail call. In a sibling call it must be 0 because the
3260   // caller will deallocate the entire stack and the callee still expects its
3261   // arguments to begin at SP+0. Completely unused for non-tail calls.
3262   int FPDiff = 0;
3263
3264   if (IsTailCall && !IsSibCall) {
3265     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3266
3267     // Since callee will pop argument stack as a tail call, we must keep the
3268     // popped size 16-byte aligned.
3269     NumBytes = alignTo(NumBytes, 16);
3270
3271     // FPDiff will be negative if this tail call requires more space than we
3272     // would automatically have in our incoming argument space. Positive if we
3273     // can actually shrink the stack.
3274     FPDiff = NumReusableBytes - NumBytes;
3275
3276     // The stack pointer must be 16-byte aligned at all times it's used for a
3277     // memory operation, which in practice means at *all* times and in
3278     // particular across call boundaries. Therefore our own arguments started at
3279     // a 16-byte aligned SP and the delta applied for the tail call should
3280     // satisfy the same constraint.
3281     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3282   }
3283
3284   // Adjust the stack pointer for the new arguments...
3285   // These operations are automatically eliminated by the prolog/epilog pass
3286   if (!IsSibCall)
3287     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3288
3289   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3290                                         getPointerTy(DAG.getDataLayout()));
3291
3292   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3293   SmallVector<SDValue, 8> MemOpChains;
3294   auto PtrVT = getPointerTy(DAG.getDataLayout());
3295
3296   // Walk the register/memloc assignments, inserting copies/loads.
3297   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3298        ++i, ++realArgIdx) {
3299     CCValAssign &VA = ArgLocs[i];
3300     SDValue Arg = OutVals[realArgIdx];
3301     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3302
3303     // Promote the value if needed.
3304     switch (VA.getLocInfo()) {
3305     default:
3306       llvm_unreachable("Unknown loc info!");
3307     case CCValAssign::Full:
3308       break;
3309     case CCValAssign::SExt:
3310       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3311       break;
3312     case CCValAssign::ZExt:
3313       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3314       break;
3315     case CCValAssign::AExt:
3316       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3317         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3318         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3319         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3320       }
3321       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3322       break;
3323     case CCValAssign::BCvt:
3324       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3325       break;
3326     case CCValAssign::FPExt:
3327       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3328       break;
3329     }
3330
3331     if (VA.isRegLoc()) {
3332       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3333           Outs[0].VT == MVT::i64) {
3334         assert(VA.getLocVT() == MVT::i64 &&
3335                "unexpected calling convention register assignment");
3336         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3337                "unexpected use of 'returned'");
3338         IsThisReturn = true;
3339       }
3340       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3341     } else {
3342       assert(VA.isMemLoc());
3343
3344       SDValue DstAddr;
3345       MachinePointerInfo DstInfo;
3346
3347       // FIXME: This works on big-endian for composite byvals, which are the
3348       // common case. It should also work for fundamental types too.
3349       uint32_t BEAlign = 0;
3350       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3351                                         : VA.getValVT().getSizeInBits();
3352       OpSize = (OpSize + 7) / 8;
3353       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3354           !Flags.isInConsecutiveRegs()) {
3355         if (OpSize < 8)
3356           BEAlign = 8 - OpSize;
3357       }
3358       unsigned LocMemOffset = VA.getLocMemOffset();
3359       int32_t Offset = LocMemOffset + BEAlign;
3360       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3361       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3362
3363       if (IsTailCall) {
3364         Offset = Offset + FPDiff;
3365         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3366
3367         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3368         DstInfo =
3369             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3370
3371         // Make sure any stack arguments overlapping with where we're storing
3372         // are loaded before this eventual operation. Otherwise they'll be
3373         // clobbered.
3374         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3375       } else {
3376         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3377
3378         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3379         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3380                                                LocMemOffset);
3381       }
3382
3383       if (Outs[i].Flags.isByVal()) {
3384         SDValue SizeNode =
3385             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3386         SDValue Cpy = DAG.getMemcpy(
3387             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3388             /*isVol = */ false, /*AlwaysInline = */ false,
3389             /*isTailCall = */ false,
3390             DstInfo, MachinePointerInfo());
3391
3392         MemOpChains.push_back(Cpy);
3393       } else {
3394         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3395         // promoted to a legal register type i32, we should truncate Arg back to
3396         // i1/i8/i16.
3397         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3398             VA.getValVT() == MVT::i16)
3399           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3400
3401         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3402         MemOpChains.push_back(Store);
3403       }
3404     }
3405   }
3406
3407   if (!MemOpChains.empty())
3408     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3409
3410   // Build a sequence of copy-to-reg nodes chained together with token chain
3411   // and flag operands which copy the outgoing args into the appropriate regs.
3412   SDValue InFlag;
3413   for (auto &RegToPass : RegsToPass) {
3414     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3415                              RegToPass.second, InFlag);
3416     InFlag = Chain.getValue(1);
3417   }
3418
3419   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3420   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3421   // node so that legalize doesn't hack it.
3422   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3423     auto GV = G->getGlobal();
3424     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3425         AArch64II::MO_GOT) {
3426       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3427       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3428     } else {
3429       const GlobalValue *GV = G->getGlobal();
3430       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3431     }
3432   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3433     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3434         Subtarget->isTargetMachO()) {
3435       const char *Sym = S->getSymbol();
3436       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3437       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3438     } else {
3439       const char *Sym = S->getSymbol();
3440       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3441     }
3442   }
3443
3444   // We don't usually want to end the call-sequence here because we would tidy
3445   // the frame up *after* the call, however in the ABI-changing tail-call case
3446   // we've carefully laid out the parameters so that when sp is reset they'll be
3447   // in the correct location.
3448   if (IsTailCall && !IsSibCall) {
3449     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3450                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3451     InFlag = Chain.getValue(1);
3452   }
3453
3454   std::vector<SDValue> Ops;
3455   Ops.push_back(Chain);
3456   Ops.push_back(Callee);
3457
3458   if (IsTailCall) {
3459     // Each tail call may have to adjust the stack by a different amount, so
3460     // this information must travel along with the operation for eventual
3461     // consumption by emitEpilogue.
3462     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3463   }
3464
3465   // Add argument registers to the end of the list so that they are known live
3466   // into the call.
3467   for (auto &RegToPass : RegsToPass)
3468     Ops.push_back(DAG.getRegister(RegToPass.first,
3469                                   RegToPass.second.getValueType()));
3470
3471   // Add a register mask operand representing the call-preserved registers.
3472   const uint32_t *Mask;
3473   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3474   if (IsThisReturn) {
3475     // For 'this' returns, use the X0-preserving mask if applicable
3476     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3477     if (!Mask) {
3478       IsThisReturn = false;
3479       Mask = TRI->getCallPreservedMask(MF, CallConv);
3480     }
3481   } else
3482     Mask = TRI->getCallPreservedMask(MF, CallConv);
3483
3484   assert(Mask && "Missing call preserved mask for calling convention");
3485   Ops.push_back(DAG.getRegisterMask(Mask));
3486
3487   if (InFlag.getNode())
3488     Ops.push_back(InFlag);
3489
3490   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3491
3492   // If we're doing a tall call, use a TC_RETURN here rather than an
3493   // actual call instruction.
3494   if (IsTailCall) {
3495     MF.getFrameInfo().setHasTailCall();
3496     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3497   }
3498
3499   // Returns a chain and a flag for retval copy to use.
3500   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3501   InFlag = Chain.getValue(1);
3502
3503   uint64_t CalleePopBytes =
3504       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3505
3506   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3507                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3508                              InFlag, DL);
3509   if (!Ins.empty())
3510     InFlag = Chain.getValue(1);
3511
3512   // Handle result values, copying them out of physregs into vregs that we
3513   // return.
3514   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3515                          InVals, IsThisReturn,
3516                          IsThisReturn ? OutVals[0] : SDValue());
3517 }
3518
3519 bool AArch64TargetLowering::CanLowerReturn(
3520     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3521     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3522   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3523                           ? RetCC_AArch64_WebKit_JS
3524                           : RetCC_AArch64_AAPCS;
3525   SmallVector<CCValAssign, 16> RVLocs;
3526   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3527   return CCInfo.CheckReturn(Outs, RetCC);
3528 }
3529
3530 SDValue
3531 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3532                                    bool isVarArg,
3533                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3534                                    const SmallVectorImpl<SDValue> &OutVals,
3535                                    const SDLoc &DL, SelectionDAG &DAG) const {
3536   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3537                           ? RetCC_AArch64_WebKit_JS
3538                           : RetCC_AArch64_AAPCS;
3539   SmallVector<CCValAssign, 16> RVLocs;
3540   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3541                  *DAG.getContext());
3542   CCInfo.AnalyzeReturn(Outs, RetCC);
3543
3544   // Copy the result values into the output registers.
3545   SDValue Flag;
3546   SmallVector<SDValue, 4> RetOps(1, Chain);
3547   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3548        ++i, ++realRVLocIdx) {
3549     CCValAssign &VA = RVLocs[i];
3550     assert(VA.isRegLoc() && "Can only return in registers!");
3551     SDValue Arg = OutVals[realRVLocIdx];
3552
3553     switch (VA.getLocInfo()) {
3554     default:
3555       llvm_unreachable("Unknown loc info!");
3556     case CCValAssign::Full:
3557       if (Outs[i].ArgVT == MVT::i1) {
3558         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3559         // value. This is strictly redundant on Darwin (which uses "zeroext
3560         // i1"), but will be optimised out before ISel.
3561         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3562         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3563       }
3564       break;
3565     case CCValAssign::BCvt:
3566       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3567       break;
3568     }
3569
3570     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3571     Flag = Chain.getValue(1);
3572     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3573   }
3574   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3575   const MCPhysReg *I =
3576       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3577   if (I) {
3578     for (; *I; ++I) {
3579       if (AArch64::GPR64RegClass.contains(*I))
3580         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3581       else if (AArch64::FPR64RegClass.contains(*I))
3582         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3583       else
3584         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3585     }
3586   }
3587
3588   RetOps[0] = Chain; // Update chain.
3589
3590   // Add the flag if we have it.
3591   if (Flag.getNode())
3592     RetOps.push_back(Flag);
3593
3594   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3595 }
3596
3597 //===----------------------------------------------------------------------===//
3598 //  Other Lowering Code
3599 //===----------------------------------------------------------------------===//
3600
3601 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3602                                              SelectionDAG &DAG,
3603                                              unsigned Flag) const {
3604   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3605 }
3606
3607 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3608                                              SelectionDAG &DAG,
3609                                              unsigned Flag) const {
3610   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3611 }
3612
3613 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3614                                              SelectionDAG &DAG,
3615                                              unsigned Flag) const {
3616   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3617                                    N->getOffset(), Flag);
3618 }
3619
3620 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3621                                              SelectionDAG &DAG,
3622                                              unsigned Flag) const {
3623   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3624 }
3625
3626 // (loadGOT sym)
3627 template <class NodeTy>
3628 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3629   DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3630   SDLoc DL(N);
3631   EVT Ty = getPointerTy(DAG.getDataLayout());
3632   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3633   // FIXME: Once remat is capable of dealing with instructions with register
3634   // operands, expand this into two nodes instead of using a wrapper node.
3635   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3636 }
3637
3638 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3639 template <class NodeTy>
3640 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3641   const {
3642   DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3643   SDLoc DL(N);
3644   EVT Ty = getPointerTy(DAG.getDataLayout());
3645   const unsigned char MO_NC = AArch64II::MO_NC;
3646   return DAG.getNode(
3647         AArch64ISD::WrapperLarge, DL, Ty,
3648         getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3649         getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3650         getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3651         getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3652 }
3653
3654 // (addlow (adrp %hi(sym)) %lo(sym))
3655 template <class NodeTy>
3656 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3657   DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3658   SDLoc DL(N);
3659   EVT Ty = getPointerTy(DAG.getDataLayout());
3660   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3661   SDValue Lo = getTargetNode(N, Ty, DAG,
3662                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3663   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3664   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3665 }
3666
3667 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3668                                                   SelectionDAG &DAG) const {
3669   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3670   const GlobalValue *GV = GN->getGlobal();
3671   unsigned char OpFlags =
3672       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3673
3674   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3675          "unexpected offset in global node");
3676
3677   // This also catches the large code model case for Darwin.
3678   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3679     return getGOT(GN, DAG);
3680   }
3681
3682   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3683     return getAddrLarge(GN, DAG);
3684   } else {
3685     return getAddr(GN, DAG);
3686   }
3687 }
3688
3689 /// \brief Convert a TLS address reference into the correct sequence of loads
3690 /// and calls to compute the variable's address (for Darwin, currently) and
3691 /// return an SDValue containing the final node.
3692
3693 /// Darwin only has one TLS scheme which must be capable of dealing with the
3694 /// fully general situation, in the worst case. This means:
3695 ///     + "extern __thread" declaration.
3696 ///     + Defined in a possibly unknown dynamic library.
3697 ///
3698 /// The general system is that each __thread variable has a [3 x i64] descriptor
3699 /// which contains information used by the runtime to calculate the address. The
3700 /// only part of this the compiler needs to know about is the first xword, which
3701 /// contains a function pointer that must be called with the address of the
3702 /// entire descriptor in "x0".
3703 ///
3704 /// Since this descriptor may be in a different unit, in general even the
3705 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3706 /// is:
3707 ///     adrp x0, _var@TLVPPAGE
3708 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3709 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3710 ///                                      ; the function pointer
3711 ///     blr x1                           ; Uses descriptor address in x0
3712 ///     ; Address of _var is now in x0.
3713 ///
3714 /// If the address of _var's descriptor *is* known to the linker, then it can
3715 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3716 /// a slight efficiency gain.
3717 SDValue
3718 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3719                                                    SelectionDAG &DAG) const {
3720   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3721
3722   SDLoc DL(Op);
3723   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3724   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3725
3726   SDValue TLVPAddr =
3727       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3728   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3729
3730   // The first entry in the descriptor is a function pointer that we must call
3731   // to obtain the address of the variable.
3732   SDValue Chain = DAG.getEntryNode();
3733   SDValue FuncTLVGet = DAG.getLoad(
3734       MVT::i64, DL, Chain, DescAddr,
3735       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3736       /* Alignment = */ 8,
3737       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3738           MachineMemOperand::MODereferenceable);
3739   Chain = FuncTLVGet.getValue(1);
3740
3741   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3742   MFI.setAdjustsStack(true);
3743
3744   // TLS calls preserve all registers except those that absolutely must be
3745   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3746   // silly).
3747   const uint32_t *Mask =
3748       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3749
3750   // Finally, we can make the call. This is just a degenerate version of a
3751   // normal AArch64 call node: x0 takes the address of the descriptor, and
3752   // returns the address of the variable in this thread.
3753   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3754   Chain =
3755       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3756                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3757                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3758   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3759 }
3760
3761 /// When accessing thread-local variables under either the general-dynamic or
3762 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3763 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3764 /// is a function pointer to carry out the resolution.
3765 ///
3766 /// The sequence is:
3767 ///    adrp  x0, :tlsdesc:var
3768 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3769 ///    add   x0, x0, #:tlsdesc_lo12:var
3770 ///    .tlsdesccall var
3771 ///    blr   x1
3772 ///    (TPIDR_EL0 offset now in x0)
3773 ///
3774 ///  The above sequence must be produced unscheduled, to enable the linker to
3775 ///  optimize/relax this sequence.
3776 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3777 ///  above sequence, and expanded really late in the compilation flow, to ensure
3778 ///  the sequence is produced as per above.
3779 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3780                                                       const SDLoc &DL,
3781                                                       SelectionDAG &DAG) const {
3782   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3783
3784   SDValue Chain = DAG.getEntryNode();
3785   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3786
3787   Chain =
3788       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3789   SDValue Glue = Chain.getValue(1);
3790
3791   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3792 }
3793
3794 SDValue
3795 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3796                                                 SelectionDAG &DAG) const {
3797   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3798   assert(Subtarget->useSmallAddressing() &&
3799          "ELF TLS only supported in small memory model");
3800   // Different choices can be made for the maximum size of the TLS area for a
3801   // module. For the small address model, the default TLS size is 16MiB and the
3802   // maximum TLS size is 4GiB.
3803   // FIXME: add -mtls-size command line option and make it control the 16MiB
3804   // vs. 4GiB code sequence generation.
3805   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3806
3807   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3808
3809   if (DAG.getTarget().Options.EmulatedTLS)
3810     return LowerToTLSEmulatedModel(GA, DAG);
3811
3812   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3813     if (Model == TLSModel::LocalDynamic)
3814       Model = TLSModel::GeneralDynamic;
3815   }
3816
3817   SDValue TPOff;
3818   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3819   SDLoc DL(Op);
3820   const GlobalValue *GV = GA->getGlobal();
3821
3822   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3823
3824   if (Model == TLSModel::LocalExec) {
3825     SDValue HiVar = DAG.getTargetGlobalAddress(
3826         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3827     SDValue LoVar = DAG.getTargetGlobalAddress(
3828         GV, DL, PtrVT, 0,
3829         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3830
3831     SDValue TPWithOff_lo =
3832         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3833                                    HiVar,
3834                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3835                 0);
3836     SDValue TPWithOff =
3837         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3838                                    LoVar,
3839                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3840                 0);
3841     return TPWithOff;
3842   } else if (Model == TLSModel::InitialExec) {
3843     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3844     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3845   } else if (Model == TLSModel::LocalDynamic) {
3846     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3847     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3848     // the beginning of the module's TLS region, followed by a DTPREL offset
3849     // calculation.
3850
3851     // These accesses will need deduplicating if there's more than one.
3852     AArch64FunctionInfo *MFI =
3853         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3854     MFI->incNumLocalDynamicTLSAccesses();
3855
3856     // The call needs a relocation too for linker relaxation. It doesn't make
3857     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3858     // the address.
3859     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3860                                                   AArch64II::MO_TLS);
3861
3862     // Now we can calculate the offset from TPIDR_EL0 to this module's
3863     // thread-local area.
3864     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3865
3866     // Now use :dtprel_whatever: operations to calculate this variable's offset
3867     // in its thread-storage area.
3868     SDValue HiVar = DAG.getTargetGlobalAddress(
3869         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3870     SDValue LoVar = DAG.getTargetGlobalAddress(
3871         GV, DL, MVT::i64, 0,
3872         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3873
3874     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3875                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3876                     0);
3877     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3878                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3879                     0);
3880   } else if (Model == TLSModel::GeneralDynamic) {
3881     // The call needs a relocation too for linker relaxation. It doesn't make
3882     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3883     // the address.
3884     SDValue SymAddr =
3885         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3886
3887     // Finally we can make a call to calculate the offset from tpidr_el0.
3888     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3889   } else
3890     llvm_unreachable("Unsupported ELF TLS access model");
3891
3892   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3893 }
3894
3895 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3896                                                      SelectionDAG &DAG) const {
3897   if (Subtarget->isTargetDarwin())
3898     return LowerDarwinGlobalTLSAddress(Op, DAG);
3899   if (Subtarget->isTargetELF())
3900     return LowerELFGlobalTLSAddress(Op, DAG);
3901
3902   llvm_unreachable("Unexpected platform trying to use TLS");
3903 }
3904
3905 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3906   SDValue Chain = Op.getOperand(0);
3907   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3908   SDValue LHS = Op.getOperand(2);
3909   SDValue RHS = Op.getOperand(3);
3910   SDValue Dest = Op.getOperand(4);
3911   SDLoc dl(Op);
3912
3913   // Handle f128 first, since lowering it will result in comparing the return
3914   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3915   // is expecting to deal with.
3916   if (LHS.getValueType() == MVT::f128) {
3917     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3918
3919     // If softenSetCCOperands returned a scalar, we need to compare the result
3920     // against zero to select between true and false values.
3921     if (!RHS.getNode()) {
3922       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3923       CC = ISD::SETNE;
3924     }
3925   }
3926
3927   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3928   // instruction.
3929   unsigned Opc = LHS.getOpcode();
3930   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3931       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3932        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3933     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3934            "Unexpected condition code.");
3935     // Only lower legal XALUO ops.
3936     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3937       return SDValue();
3938
3939     // The actual operation with overflow check.
3940     AArch64CC::CondCode OFCC;
3941     SDValue Value, Overflow;
3942     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3943
3944     if (CC == ISD::SETNE)
3945       OFCC = getInvertedCondCode(OFCC);
3946     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3947
3948     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3949                        Overflow);
3950   }
3951
3952   if (LHS.getValueType().isInteger()) {
3953     assert((LHS.getValueType() == RHS.getValueType()) &&
3954            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3955
3956     // If the RHS of the comparison is zero, we can potentially fold this
3957     // to a specialized branch.
3958     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3959     if (RHSC && RHSC->getZExtValue() == 0) {
3960       if (CC == ISD::SETEQ) {
3961         // See if we can use a TBZ to fold in an AND as well.
3962         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3963         // out of bounds, a late MI-layer pass rewrites branches.
3964         // 403.gcc is an example that hits this case.
3965         if (LHS.getOpcode() == ISD::AND &&
3966             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3967             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3968           SDValue Test = LHS.getOperand(0);
3969           uint64_t Mask = LHS.getConstantOperandVal(1);
3970           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3971                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3972                              Dest);
3973         }
3974
3975         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3976       } else if (CC == ISD::SETNE) {
3977         // See if we can use a TBZ to fold in an AND as well.
3978         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3979         // out of bounds, a late MI-layer pass rewrites branches.
3980         // 403.gcc is an example that hits this case.
3981         if (LHS.getOpcode() == ISD::AND &&
3982             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3983             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3984           SDValue Test = LHS.getOperand(0);
3985           uint64_t Mask = LHS.getConstantOperandVal(1);
3986           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3987                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3988                              Dest);
3989         }
3990
3991         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3992       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3993         // Don't combine AND since emitComparison converts the AND to an ANDS
3994         // (a.k.a. TST) and the test in the test bit and branch instruction
3995         // becomes redundant.  This would also increase register pressure.
3996         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3997         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3998                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3999       }
4000     }
4001     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4002         LHS.getOpcode() != ISD::AND) {
4003       // Don't combine AND since emitComparison converts the AND to an ANDS
4004       // (a.k.a. TST) and the test in the test bit and branch instruction
4005       // becomes redundant.  This would also increase register pressure.
4006       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4007       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4008                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4009     }
4010
4011     SDValue CCVal;
4012     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4013     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4014                        Cmp);
4015   }
4016
4017   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4018
4019   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4020   // clean.  Some of them require two branches to implement.
4021   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4022   AArch64CC::CondCode CC1, CC2;
4023   changeFPCCToAArch64CC(CC, CC1, CC2);
4024   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4025   SDValue BR1 =
4026       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4027   if (CC2 != AArch64CC::AL) {
4028     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4029     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4030                        Cmp);
4031   }
4032
4033   return BR1;
4034 }
4035
4036 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4037                                               SelectionDAG &DAG) const {
4038   EVT VT = Op.getValueType();
4039   SDLoc DL(Op);
4040
4041   SDValue In1 = Op.getOperand(0);
4042   SDValue In2 = Op.getOperand(1);
4043   EVT SrcVT = In2.getValueType();
4044
4045   if (SrcVT.bitsLT(VT))
4046     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4047   else if (SrcVT.bitsGT(VT))
4048     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4049
4050   EVT VecVT;
4051   EVT EltVT;
4052   uint64_t EltMask;
4053   SDValue VecVal1, VecVal2;
4054   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4055     EltVT = MVT::i32;
4056     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4057     EltMask = 0x80000000ULL;
4058
4059     if (!VT.isVector()) {
4060       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4061                                           DAG.getUNDEF(VecVT), In1);
4062       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4063                                           DAG.getUNDEF(VecVT), In2);
4064     } else {
4065       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4066       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4067     }
4068   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4069     EltVT = MVT::i64;
4070     VecVT = MVT::v2i64;
4071
4072     // We want to materialize a mask with the high bit set, but the AdvSIMD
4073     // immediate moves cannot materialize that in a single instruction for
4074     // 64-bit elements. Instead, materialize zero and then negate it.
4075     EltMask = 0;
4076
4077     if (!VT.isVector()) {
4078       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4079                                           DAG.getUNDEF(VecVT), In1);
4080       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4081                                           DAG.getUNDEF(VecVT), In2);
4082     } else {
4083       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4084       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4085     }
4086   } else {
4087     llvm_unreachable("Invalid type for copysign!");
4088   }
4089
4090   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4091
4092   // If we couldn't materialize the mask above, then the mask vector will be
4093   // the zero vector, and we need to negate it here.
4094   if (VT == MVT::f64 || VT == MVT::v2f64) {
4095     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4096     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4097     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4098   }
4099
4100   SDValue Sel =
4101       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4102
4103   if (VT == MVT::f32)
4104     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4105   else if (VT == MVT::f64)
4106     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4107   else
4108     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4109 }
4110
4111 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4112   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4113           Attribute::NoImplicitFloat))
4114     return SDValue();
4115
4116   if (!Subtarget->hasNEON())
4117     return SDValue();
4118
4119   // While there is no integer popcount instruction, it can
4120   // be more efficiently lowered to the following sequence that uses
4121   // AdvSIMD registers/instructions as long as the copies to/from
4122   // the AdvSIMD registers are cheap.
4123   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4124   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4125   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4126   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4127   SDValue Val = Op.getOperand(0);
4128   SDLoc DL(Op);
4129   EVT VT = Op.getValueType();
4130
4131   if (VT == MVT::i32)
4132     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4133   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4134
4135   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4136   SDValue UaddLV = DAG.getNode(
4137       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4138       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4139
4140   if (VT == MVT::i64)
4141     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4142   return UaddLV;
4143 }
4144
4145 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4146
4147   if (Op.getValueType().isVector())
4148     return LowerVSETCC(Op, DAG);
4149
4150   SDValue LHS = Op.getOperand(0);
4151   SDValue RHS = Op.getOperand(1);
4152   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4153   SDLoc dl(Op);
4154
4155   // We chose ZeroOrOneBooleanContents, so use zero and one.
4156   EVT VT = Op.getValueType();
4157   SDValue TVal = DAG.getConstant(1, dl, VT);
4158   SDValue FVal = DAG.getConstant(0, dl, VT);
4159
4160   // Handle f128 first, since one possible outcome is a normal integer
4161   // comparison which gets picked up by the next if statement.
4162   if (LHS.getValueType() == MVT::f128) {
4163     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4164
4165     // If softenSetCCOperands returned a scalar, use it.
4166     if (!RHS.getNode()) {
4167       assert(LHS.getValueType() == Op.getValueType() &&
4168              "Unexpected setcc expansion!");
4169       return LHS;
4170     }
4171   }
4172
4173   if (LHS.getValueType().isInteger()) {
4174     SDValue CCVal;
4175     SDValue Cmp =
4176         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4177
4178     // Note that we inverted the condition above, so we reverse the order of
4179     // the true and false operands here.  This will allow the setcc to be
4180     // matched to a single CSINC instruction.
4181     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4182   }
4183
4184   // Now we know we're dealing with FP values.
4185   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4186
4187   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4188   // and do the comparison.
4189   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4190
4191   AArch64CC::CondCode CC1, CC2;
4192   changeFPCCToAArch64CC(CC, CC1, CC2);
4193   if (CC2 == AArch64CC::AL) {
4194     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4195     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4196
4197     // Note that we inverted the condition above, so we reverse the order of
4198     // the true and false operands here.  This will allow the setcc to be
4199     // matched to a single CSINC instruction.
4200     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4201   } else {
4202     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4203     // totally clean.  Some of them require two CSELs to implement.  As is in
4204     // this case, we emit the first CSEL and then emit a second using the output
4205     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4206
4207     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4208     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4209     SDValue CS1 =
4210         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4211
4212     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4213     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4214   }
4215 }
4216
4217 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4218                                               SDValue RHS, SDValue TVal,
4219                                               SDValue FVal, const SDLoc &dl,
4220                                               SelectionDAG &DAG) const {
4221   // Handle f128 first, because it will result in a comparison of some RTLIB
4222   // call result against zero.
4223   if (LHS.getValueType() == MVT::f128) {
4224     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4225
4226     // If softenSetCCOperands returned a scalar, we need to compare the result
4227     // against zero to select between true and false values.
4228     if (!RHS.getNode()) {
4229       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4230       CC = ISD::SETNE;
4231     }
4232   }
4233
4234   // Also handle f16, for which we need to do a f32 comparison.
4235   if (LHS.getValueType() == MVT::f16) {
4236     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4237     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4238   }
4239
4240   // Next, handle integers.
4241   if (LHS.getValueType().isInteger()) {
4242     assert((LHS.getValueType() == RHS.getValueType()) &&
4243            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4244
4245     unsigned Opcode = AArch64ISD::CSEL;
4246
4247     // If both the TVal and the FVal are constants, see if we can swap them in
4248     // order to for a CSINV or CSINC out of them.
4249     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4250     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4251
4252     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4253       std::swap(TVal, FVal);
4254       std::swap(CTVal, CFVal);
4255       CC = ISD::getSetCCInverse(CC, true);
4256     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4257       std::swap(TVal, FVal);
4258       std::swap(CTVal, CFVal);
4259       CC = ISD::getSetCCInverse(CC, true);
4260     } else if (TVal.getOpcode() == ISD::XOR) {
4261       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4262       // with a CSINV rather than a CSEL.
4263       if (isAllOnesConstant(TVal.getOperand(1))) {
4264         std::swap(TVal, FVal);
4265         std::swap(CTVal, CFVal);
4266         CC = ISD::getSetCCInverse(CC, true);
4267       }
4268     } else if (TVal.getOpcode() == ISD::SUB) {
4269       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4270       // that we can match with a CSNEG rather than a CSEL.
4271       if (isNullConstant(TVal.getOperand(0))) {
4272         std::swap(TVal, FVal);
4273         std::swap(CTVal, CFVal);
4274         CC = ISD::getSetCCInverse(CC, true);
4275       }
4276     } else if (CTVal && CFVal) {
4277       const int64_t TrueVal = CTVal->getSExtValue();
4278       const int64_t FalseVal = CFVal->getSExtValue();
4279       bool Swap = false;
4280
4281       // If both TVal and FVal are constants, see if FVal is the
4282       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4283       // instead of a CSEL in that case.
4284       if (TrueVal == ~FalseVal) {
4285         Opcode = AArch64ISD::CSINV;
4286       } else if (TrueVal == -FalseVal) {
4287         Opcode = AArch64ISD::CSNEG;
4288       } else if (TVal.getValueType() == MVT::i32) {
4289         // If our operands are only 32-bit wide, make sure we use 32-bit
4290         // arithmetic for the check whether we can use CSINC. This ensures that
4291         // the addition in the check will wrap around properly in case there is
4292         // an overflow (which would not be the case if we do the check with
4293         // 64-bit arithmetic).
4294         const uint32_t TrueVal32 = CTVal->getZExtValue();
4295         const uint32_t FalseVal32 = CFVal->getZExtValue();
4296
4297         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4298           Opcode = AArch64ISD::CSINC;
4299
4300           if (TrueVal32 > FalseVal32) {
4301             Swap = true;
4302           }
4303         }
4304         // 64-bit check whether we can use CSINC.
4305       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4306         Opcode = AArch64ISD::CSINC;
4307
4308         if (TrueVal > FalseVal) {
4309           Swap = true;
4310         }
4311       }
4312
4313       // Swap TVal and FVal if necessary.
4314       if (Swap) {
4315         std::swap(TVal, FVal);
4316         std::swap(CTVal, CFVal);
4317         CC = ISD::getSetCCInverse(CC, true);
4318       }
4319
4320       if (Opcode != AArch64ISD::CSEL) {
4321         // Drop FVal since we can get its value by simply inverting/negating
4322         // TVal.
4323         FVal = TVal;
4324       }
4325     }
4326
4327     // Avoid materializing a constant when possible by reusing a known value in
4328     // a register.  However, don't perform this optimization if the known value
4329     // is one, zero or negative one in the case of a CSEL.  We can always
4330     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4331     // FVal, respectively.
4332     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4333     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4334         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4335       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4336       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4337       // "a != C ? x : a" to avoid materializing C.
4338       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4339         TVal = LHS;
4340       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4341         FVal = LHS;
4342     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4343       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4344       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4345       // avoid materializing C.
4346       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4347       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4348         Opcode = AArch64ISD::CSINV;
4349         TVal = LHS;
4350         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4351       }
4352     }
4353
4354     SDValue CCVal;
4355     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4356
4357     EVT VT = TVal.getValueType();
4358     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4359   }
4360
4361   // Now we know we're dealing with FP values.
4362   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4363   assert(LHS.getValueType() == RHS.getValueType());
4364   EVT VT = TVal.getValueType();
4365   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4366
4367   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4368   // clean.  Some of them require two CSELs to implement.
4369   AArch64CC::CondCode CC1, CC2;
4370   changeFPCCToAArch64CC(CC, CC1, CC2);
4371
4372   if (DAG.getTarget().Options.UnsafeFPMath) {
4373     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4374     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4375     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4376     if (RHSVal && RHSVal->isZero()) {
4377       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4378       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4379
4380       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4381           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4382         TVal = LHS;
4383       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4384                CFVal && CFVal->isZero() &&
4385                FVal.getValueType() == LHS.getValueType())
4386         FVal = LHS;
4387     }
4388   }
4389
4390   // Emit first, and possibly only, CSEL.
4391   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4392   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4393
4394   // If we need a second CSEL, emit it, using the output of the first as the
4395   // RHS.  We're effectively OR'ing the two CC's together.
4396   if (CC2 != AArch64CC::AL) {
4397     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4398     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4399   }
4400
4401   // Otherwise, return the output of the first CSEL.
4402   return CS1;
4403 }
4404
4405 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4406                                               SelectionDAG &DAG) const {
4407   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4408   SDValue LHS = Op.getOperand(0);
4409   SDValue RHS = Op.getOperand(1);
4410   SDValue TVal = Op.getOperand(2);
4411   SDValue FVal = Op.getOperand(3);
4412   SDLoc DL(Op);
4413   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4414 }
4415
4416 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4417                                            SelectionDAG &DAG) const {
4418   SDValue CCVal = Op->getOperand(0);
4419   SDValue TVal = Op->getOperand(1);
4420   SDValue FVal = Op->getOperand(2);
4421   SDLoc DL(Op);
4422
4423   unsigned Opc = CCVal.getOpcode();
4424   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4425   // instruction.
4426   if (CCVal.getResNo() == 1 &&
4427       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4428        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4429     // Only lower legal XALUO ops.
4430     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4431       return SDValue();
4432
4433     AArch64CC::CondCode OFCC;
4434     SDValue Value, Overflow;
4435     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4436     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4437
4438     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4439                        CCVal, Overflow);
4440   }
4441
4442   // Lower it the same way as we would lower a SELECT_CC node.
4443   ISD::CondCode CC;
4444   SDValue LHS, RHS;
4445   if (CCVal.getOpcode() == ISD::SETCC) {
4446     LHS = CCVal.getOperand(0);
4447     RHS = CCVal.getOperand(1);
4448     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4449   } else {
4450     LHS = CCVal;
4451     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4452     CC = ISD::SETNE;
4453   }
4454   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4455 }
4456
4457 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4458                                               SelectionDAG &DAG) const {
4459   // Jump table entries as PC relative offsets. No additional tweaking
4460   // is necessary here. Just get the address of the jump table.
4461   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4462
4463   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4464       !Subtarget->isTargetMachO()) {
4465     return getAddrLarge(JT, DAG);
4466   }
4467   return getAddr(JT, DAG);
4468 }
4469
4470 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4471                                                  SelectionDAG &DAG) const {
4472   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4473
4474   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4475     // Use the GOT for the large code model on iOS.
4476     if (Subtarget->isTargetMachO()) {
4477       return getGOT(CP, DAG);
4478     }
4479     return getAddrLarge(CP, DAG);
4480   } else {
4481     return getAddr(CP, DAG);
4482   }
4483 }
4484
4485 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4486                                                SelectionDAG &DAG) const {
4487   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4488   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4489       !Subtarget->isTargetMachO()) {
4490     return getAddrLarge(BA, DAG);
4491   } else {
4492     return getAddr(BA, DAG);
4493   }
4494 }
4495
4496 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4497                                                  SelectionDAG &DAG) const {
4498   AArch64FunctionInfo *FuncInfo =
4499       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4500
4501   SDLoc DL(Op);
4502   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4503                                  getPointerTy(DAG.getDataLayout()));
4504   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4505   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4506                       MachinePointerInfo(SV));
4507 }
4508
4509 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4510                                                   SelectionDAG &DAG) const {
4511   AArch64FunctionInfo *FuncInfo =
4512       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4513
4514   SDLoc DL(Op);
4515   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4516                                      ? FuncInfo->getVarArgsGPRIndex()
4517                                      : FuncInfo->getVarArgsStackIndex(),
4518                                  getPointerTy(DAG.getDataLayout()));
4519   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4520   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4521                       MachinePointerInfo(SV));
4522 }
4523
4524 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4525                                                 SelectionDAG &DAG) const {
4526   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4527   // Standard, section B.3.
4528   MachineFunction &MF = DAG.getMachineFunction();
4529   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4530   auto PtrVT = getPointerTy(DAG.getDataLayout());
4531   SDLoc DL(Op);
4532
4533   SDValue Chain = Op.getOperand(0);
4534   SDValue VAList = Op.getOperand(1);
4535   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4536   SmallVector<SDValue, 4> MemOps;
4537
4538   // void *__stack at offset 0
4539   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4540   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4541                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4542
4543   // void *__gr_top at offset 8
4544   int GPRSize = FuncInfo->getVarArgsGPRSize();
4545   if (GPRSize > 0) {
4546     SDValue GRTop, GRTopAddr;
4547
4548     GRTopAddr =
4549         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4550
4551     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4552     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4553                         DAG.getConstant(GPRSize, DL, PtrVT));
4554
4555     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4556                                   MachinePointerInfo(SV, 8),
4557                                   /* Alignment = */ 8));
4558   }
4559
4560   // void *__vr_top at offset 16
4561   int FPRSize = FuncInfo->getVarArgsFPRSize();
4562   if (FPRSize > 0) {
4563     SDValue VRTop, VRTopAddr;
4564     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4565                             DAG.getConstant(16, DL, PtrVT));
4566
4567     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4568     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4569                         DAG.getConstant(FPRSize, DL, PtrVT));
4570
4571     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4572                                   MachinePointerInfo(SV, 16),
4573                                   /* Alignment = */ 8));
4574   }
4575
4576   // int __gr_offs at offset 24
4577   SDValue GROffsAddr =
4578       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4579   MemOps.push_back(DAG.getStore(
4580       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4581       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4582
4583   // int __vr_offs at offset 28
4584   SDValue VROffsAddr =
4585       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4586   MemOps.push_back(DAG.getStore(
4587       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4588       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4589
4590   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4591 }
4592
4593 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4594                                             SelectionDAG &DAG) const {
4595   MachineFunction &MF = DAG.getMachineFunction();
4596
4597   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
4598     return LowerWin64_VASTART(Op, DAG);
4599   else if (Subtarget->isTargetDarwin())
4600     return LowerDarwin_VASTART(Op, DAG);
4601   else
4602     return LowerAAPCS_VASTART(Op, DAG);
4603 }
4604
4605 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4606                                            SelectionDAG &DAG) const {
4607   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4608   // pointer.
4609   SDLoc DL(Op);
4610   unsigned VaListSize =
4611       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
4612   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4613   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4614
4615   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4616                        Op.getOperand(2),
4617                        DAG.getConstant(VaListSize, DL, MVT::i32),
4618                        8, false, false, false, MachinePointerInfo(DestSV),
4619                        MachinePointerInfo(SrcSV));
4620 }
4621
4622 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4623   assert(Subtarget->isTargetDarwin() &&
4624          "automatic va_arg instruction only works on Darwin");
4625
4626   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4627   EVT VT = Op.getValueType();
4628   SDLoc DL(Op);
4629   SDValue Chain = Op.getOperand(0);
4630   SDValue Addr = Op.getOperand(1);
4631   unsigned Align = Op.getConstantOperandVal(3);
4632   auto PtrVT = getPointerTy(DAG.getDataLayout());
4633
4634   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4635   Chain = VAList.getValue(1);
4636
4637   if (Align > 8) {
4638     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4639     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4640                          DAG.getConstant(Align - 1, DL, PtrVT));
4641     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4642                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4643   }
4644
4645   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4646   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4647
4648   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4649   // up to 64 bits.  At the very least, we have to increase the striding of the
4650   // vaargs list to match this, and for FP values we need to introduce
4651   // FP_ROUND nodes as well.
4652   if (VT.isInteger() && !VT.isVector())
4653     ArgSize = 8;
4654   bool NeedFPTrunc = false;
4655   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4656     ArgSize = 8;
4657     NeedFPTrunc = true;
4658   }
4659
4660   // Increment the pointer, VAList, to the next vaarg
4661   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4662                                DAG.getConstant(ArgSize, DL, PtrVT));
4663   // Store the incremented VAList to the legalized pointer
4664   SDValue APStore =
4665       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4666
4667   // Load the actual argument out of the pointer VAList
4668   if (NeedFPTrunc) {
4669     // Load the value as an f64.
4670     SDValue WideFP =
4671         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4672     // Round the value down to an f32.
4673     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4674                                    DAG.getIntPtrConstant(1, DL));
4675     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4676     // Merge the rounded value with the chain output of the load.
4677     return DAG.getMergeValues(Ops, DL);
4678   }
4679
4680   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4681 }
4682
4683 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4684                                               SelectionDAG &DAG) const {
4685   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4686   MFI.setFrameAddressIsTaken(true);
4687
4688   EVT VT = Op.getValueType();
4689   SDLoc DL(Op);
4690   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4691   SDValue FrameAddr =
4692       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4693   while (Depth--)
4694     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4695                             MachinePointerInfo());
4696   return FrameAddr;
4697 }
4698
4699 // FIXME? Maybe this could be a TableGen attribute on some registers and
4700 // this table could be generated automatically from RegInfo.
4701 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4702                                                   SelectionDAG &DAG) const {
4703   unsigned Reg = StringSwitch<unsigned>(RegName)
4704                        .Case("sp", AArch64::SP)
4705                        .Case("x18", AArch64::X18)
4706                        .Case("w18", AArch64::W18)
4707                        .Default(0);
4708   if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4709       !Subtarget->isX18Reserved())
4710     Reg = 0;
4711   if (Reg)
4712     return Reg;
4713   report_fatal_error(Twine("Invalid register name \""
4714                               + StringRef(RegName)  + "\"."));
4715 }
4716
4717 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4718                                                SelectionDAG &DAG) const {
4719   MachineFunction &MF = DAG.getMachineFunction();
4720   MachineFrameInfo &MFI = MF.getFrameInfo();
4721   MFI.setReturnAddressIsTaken(true);
4722
4723   EVT VT = Op.getValueType();
4724   SDLoc DL(Op);
4725   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4726   if (Depth) {
4727     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4728     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4729     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4730                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4731                        MachinePointerInfo());
4732   }
4733
4734   // Return LR, which contains the return address. Mark it an implicit live-in.
4735   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4736   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4737 }
4738
4739 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4740 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4741 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4742                                                     SelectionDAG &DAG) const {
4743   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4744   EVT VT = Op.getValueType();
4745   unsigned VTBits = VT.getSizeInBits();
4746   SDLoc dl(Op);
4747   SDValue ShOpLo = Op.getOperand(0);
4748   SDValue ShOpHi = Op.getOperand(1);
4749   SDValue ShAmt = Op.getOperand(2);
4750   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4751
4752   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4753
4754   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4755                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4756   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4757
4758   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4759   // is "undef". We wanted 0, so CSEL it directly.
4760   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4761                                ISD::SETEQ, dl, DAG);
4762   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4763   HiBitsForLo =
4764       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4765                   HiBitsForLo, CCVal, Cmp);
4766
4767   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4768                                    DAG.getConstant(VTBits, dl, MVT::i64));
4769
4770   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4771   SDValue LoForNormalShift =
4772       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4773
4774   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4775                        dl, DAG);
4776   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4777   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4778   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4779                            LoForNormalShift, CCVal, Cmp);
4780
4781   // AArch64 shifts larger than the register width are wrapped rather than
4782   // clamped, so we can't just emit "hi >> x".
4783   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4784   SDValue HiForBigShift =
4785       Opc == ISD::SRA
4786           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4787                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4788           : DAG.getConstant(0, dl, VT);
4789   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4790                            HiForNormalShift, CCVal, Cmp);
4791
4792   SDValue Ops[2] = { Lo, Hi };
4793   return DAG.getMergeValues(Ops, dl);
4794 }
4795
4796 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4797 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4798 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4799                                                    SelectionDAG &DAG) const {
4800   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4801   EVT VT = Op.getValueType();
4802   unsigned VTBits = VT.getSizeInBits();
4803   SDLoc dl(Op);
4804   SDValue ShOpLo = Op.getOperand(0);
4805   SDValue ShOpHi = Op.getOperand(1);
4806   SDValue ShAmt = Op.getOperand(2);
4807
4808   assert(Op.getOpcode() == ISD::SHL_PARTS);
4809   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4810                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4811   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4812
4813   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4814   // is "undef". We wanted 0, so CSEL it directly.
4815   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4816                                ISD::SETEQ, dl, DAG);
4817   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4818   LoBitsForHi =
4819       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4820                   LoBitsForHi, CCVal, Cmp);
4821
4822   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4823                                    DAG.getConstant(VTBits, dl, MVT::i64));
4824   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4825   SDValue HiForNormalShift =
4826       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4827
4828   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4829
4830   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4831                        dl, DAG);
4832   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4833   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4834                            HiForNormalShift, CCVal, Cmp);
4835
4836   // AArch64 shifts of larger than register sizes are wrapped rather than
4837   // clamped, so we can't just emit "lo << a" if a is too big.
4838   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4839   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4840   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4841                            LoForNormalShift, CCVal, Cmp);
4842
4843   SDValue Ops[2] = { Lo, Hi };
4844   return DAG.getMergeValues(Ops, dl);
4845 }
4846
4847 bool AArch64TargetLowering::isOffsetFoldingLegal(
4848     const GlobalAddressSDNode *GA) const {
4849   // The AArch64 target doesn't support folding offsets into global addresses.
4850   return false;
4851 }
4852
4853 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4854   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4855   // FIXME: We should be able to handle f128 as well with a clever lowering.
4856   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4857     return true;
4858
4859   if (VT == MVT::f64)
4860     return AArch64_AM::getFP64Imm(Imm) != -1;
4861   else if (VT == MVT::f32)
4862     return AArch64_AM::getFP32Imm(Imm) != -1;
4863   return false;
4864 }
4865
4866 //===----------------------------------------------------------------------===//
4867 //                          AArch64 Optimization Hooks
4868 //===----------------------------------------------------------------------===//
4869
4870 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4871                            SDValue Operand, SelectionDAG &DAG,
4872                            int &ExtraSteps) {
4873   EVT VT = Operand.getValueType();
4874   if (ST->hasNEON() &&
4875       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4876        VT == MVT::f32 || VT == MVT::v1f32 ||
4877        VT == MVT::v2f32 || VT == MVT::v4f32)) {
4878     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4879       // For the reciprocal estimates, convergence is quadratic, so the number
4880       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
4881       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
4882       // the result for float (23 mantissa bits) is 2 and for double (52
4883       // mantissa bits) is 3.
4884       ExtraSteps = VT == MVT::f64 ? 3 : 2;
4885
4886     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4887   }
4888
4889   return SDValue();
4890 }
4891
4892 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4893                                                SelectionDAG &DAG, int Enabled,
4894                                                int &ExtraSteps,
4895                                                bool &UseOneConst,
4896                                                bool Reciprocal) const {
4897   if (Enabled == ReciprocalEstimate::Enabled ||
4898       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4899     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4900                                        DAG, ExtraSteps)) {
4901       SDLoc DL(Operand);
4902       EVT VT = Operand.getValueType();
4903
4904       SDNodeFlags Flags;
4905       Flags.setUnsafeAlgebra(true);
4906
4907       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4908       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4909       for (int i = ExtraSteps; i > 0; --i) {
4910         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4911                                    Flags);
4912         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4913         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4914       }
4915
4916       if (!Reciprocal) {
4917         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4918                                       VT);
4919         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4920         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4921
4922         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
4923         // Correct the result if the operand is 0.0.
4924         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4925                                VT, Eq, Operand, Estimate);
4926       }
4927
4928       ExtraSteps = 0;
4929       return Estimate;
4930     }
4931
4932   return SDValue();
4933 }
4934
4935 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4936                                                 SelectionDAG &DAG, int Enabled,
4937                                                 int &ExtraSteps) const {
4938   if (Enabled == ReciprocalEstimate::Enabled)
4939     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4940                                        DAG, ExtraSteps)) {
4941       SDLoc DL(Operand);
4942       EVT VT = Operand.getValueType();
4943
4944       SDNodeFlags Flags;
4945       Flags.setUnsafeAlgebra(true);
4946
4947       // Newton reciprocal iteration: E * (2 - X * E)
4948       // AArch64 reciprocal iteration instruction: (2 - M * N)
4949       for (int i = ExtraSteps; i > 0; --i) {
4950         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4951                                    Estimate, Flags);
4952         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4953       }
4954
4955       ExtraSteps = 0;
4956       return Estimate;
4957     }
4958
4959   return SDValue();
4960 }
4961
4962 //===----------------------------------------------------------------------===//
4963 //                          AArch64 Inline Assembly Support
4964 //===----------------------------------------------------------------------===//
4965
4966 // Table of Constraints
4967 // TODO: This is the current set of constraints supported by ARM for the
4968 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4969 //
4970 // r - A general register
4971 // w - An FP/SIMD register of some size in the range v0-v31
4972 // x - An FP/SIMD register of some size in the range v0-v15
4973 // I - Constant that can be used with an ADD instruction
4974 // J - Constant that can be used with a SUB instruction
4975 // K - Constant that can be used with a 32-bit logical instruction
4976 // L - Constant that can be used with a 64-bit logical instruction
4977 // M - Constant that can be used as a 32-bit MOV immediate
4978 // N - Constant that can be used as a 64-bit MOV immediate
4979 // Q - A memory reference with base register and no offset
4980 // S - A symbolic address
4981 // Y - Floating point constant zero
4982 // Z - Integer constant zero
4983 //
4984 //   Note that general register operands will be output using their 64-bit x
4985 // register name, whatever the size of the variable, unless the asm operand
4986 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4987 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4988 // %q modifier.
4989 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4990   // At this point, we have to lower this constraint to something else, so we
4991   // lower it to an "r" or "w". However, by doing this we will force the result
4992   // to be in register, while the X constraint is much more permissive.
4993   //
4994   // Although we are correct (we are free to emit anything, without
4995   // constraints), we might break use cases that would expect us to be more
4996   // efficient and emit something else.
4997   if (!Subtarget->hasFPARMv8())
4998     return "r";
4999
5000   if (ConstraintVT.isFloatingPoint())
5001     return "w";
5002
5003   if (ConstraintVT.isVector() &&
5004      (ConstraintVT.getSizeInBits() == 64 ||
5005       ConstraintVT.getSizeInBits() == 128))
5006     return "w";
5007
5008   return "r";
5009 }
5010
5011 /// getConstraintType - Given a constraint letter, return the type of
5012 /// constraint it is for this target.
5013 AArch64TargetLowering::ConstraintType
5014 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5015   if (Constraint.size() == 1) {
5016     switch (Constraint[0]) {
5017     default:
5018       break;
5019     case 'z':
5020       return C_Other;
5021     case 'x':
5022     case 'w':
5023       return C_RegisterClass;
5024     // An address with a single base register. Due to the way we
5025     // currently handle addresses it is the same as 'r'.
5026     case 'Q':
5027       return C_Memory;
5028     }
5029   }
5030   return TargetLowering::getConstraintType(Constraint);
5031 }
5032
5033 /// Examine constraint type and operand type and determine a weight value.
5034 /// This object must already have been set up with the operand type
5035 /// and the current alternative constraint selected.
5036 TargetLowering::ConstraintWeight
5037 AArch64TargetLowering::getSingleConstraintMatchWeight(
5038     AsmOperandInfo &info, const char *constraint) const {
5039   ConstraintWeight weight = CW_Invalid;
5040   Value *CallOperandVal = info.CallOperandVal;
5041   // If we don't have a value, we can't do a match,
5042   // but allow it at the lowest weight.
5043   if (!CallOperandVal)
5044     return CW_Default;
5045   Type *type = CallOperandVal->getType();
5046   // Look at the constraint type.
5047   switch (*constraint) {
5048   default:
5049     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5050     break;
5051   case 'x':
5052   case 'w':
5053     if (type->isFloatingPointTy() || type->isVectorTy())
5054       weight = CW_Register;
5055     break;
5056   case 'z':
5057     weight = CW_Constant;
5058     break;
5059   }
5060   return weight;
5061 }
5062
5063 std::pair<unsigned, const TargetRegisterClass *>
5064 AArch64TargetLowering::getRegForInlineAsmConstraint(
5065     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5066   if (Constraint.size() == 1) {
5067     switch (Constraint[0]) {
5068     case 'r':
5069       if (VT.getSizeInBits() == 64)
5070         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5071       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5072     case 'w':
5073       if (VT.getSizeInBits() == 16)
5074         return std::make_pair(0U, &AArch64::FPR16RegClass);
5075       if (VT.getSizeInBits() == 32)
5076         return std::make_pair(0U, &AArch64::FPR32RegClass);
5077       if (VT.getSizeInBits() == 64)
5078         return std::make_pair(0U, &AArch64::FPR64RegClass);
5079       if (VT.getSizeInBits() == 128)
5080         return std::make_pair(0U, &AArch64::FPR128RegClass);
5081       break;
5082     // The instructions that this constraint is designed for can
5083     // only take 128-bit registers so just use that regclass.
5084     case 'x':
5085       if (VT.getSizeInBits() == 128)
5086         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5087       break;
5088     }
5089   }
5090   if (StringRef("{cc}").equals_lower(Constraint))
5091     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5092
5093   // Use the default implementation in TargetLowering to convert the register
5094   // constraint into a member of a register class.
5095   std::pair<unsigned, const TargetRegisterClass *> Res;
5096   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5097
5098   // Not found as a standard register?
5099   if (!Res.second) {
5100     unsigned Size = Constraint.size();
5101     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5102         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5103       int RegNo;
5104       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5105       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5106         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5107         // By default we'll emit v0-v31 for this unless there's a modifier where
5108         // we'll emit the correct register as well.
5109         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5110           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5111           Res.second = &AArch64::FPR64RegClass;
5112         } else {
5113           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5114           Res.second = &AArch64::FPR128RegClass;
5115         }
5116       }
5117     }
5118   }
5119
5120   return Res;
5121 }
5122
5123 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5124 /// vector.  If it is invalid, don't add anything to Ops.
5125 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5126     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5127     SelectionDAG &DAG) const {
5128   SDValue Result;
5129
5130   // Currently only support length 1 constraints.
5131   if (Constraint.length() != 1)
5132     return;
5133
5134   char ConstraintLetter = Constraint[0];
5135   switch (ConstraintLetter) {
5136   default:
5137     break;
5138
5139   // This set of constraints deal with valid constants for various instructions.
5140   // Validate and return a target constant for them if we can.
5141   case 'z': {
5142     // 'z' maps to xzr or wzr so it needs an input of 0.
5143     if (!isNullConstant(Op))
5144       return;
5145
5146     if (Op.getValueType() == MVT::i64)
5147       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5148     else
5149       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5150     break;
5151   }
5152
5153   case 'I':
5154   case 'J':
5155   case 'K':
5156   case 'L':
5157   case 'M':
5158   case 'N':
5159     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5160     if (!C)
5161       return;
5162
5163     // Grab the value and do some validation.
5164     uint64_t CVal = C->getZExtValue();
5165     switch (ConstraintLetter) {
5166     // The I constraint applies only to simple ADD or SUB immediate operands:
5167     // i.e. 0 to 4095 with optional shift by 12
5168     // The J constraint applies only to ADD or SUB immediates that would be
5169     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5170     // instruction [or vice versa], in other words -1 to -4095 with optional
5171     // left shift by 12.
5172     case 'I':
5173       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5174         break;
5175       return;
5176     case 'J': {
5177       uint64_t NVal = -C->getSExtValue();
5178       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5179         CVal = C->getSExtValue();
5180         break;
5181       }
5182       return;
5183     }
5184     // The K and L constraints apply *only* to logical immediates, including
5185     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5186     // been removed and MOV should be used). So these constraints have to
5187     // distinguish between bit patterns that are valid 32-bit or 64-bit
5188     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5189     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5190     // versa.
5191     case 'K':
5192       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5193         break;
5194       return;
5195     case 'L':
5196       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5197         break;
5198       return;
5199     // The M and N constraints are a superset of K and L respectively, for use
5200     // with the MOV (immediate) alias. As well as the logical immediates they
5201     // also match 32 or 64-bit immediates that can be loaded either using a
5202     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5203     // (M) or 64-bit 0x1234000000000000 (N) etc.
5204     // As a note some of this code is liberally stolen from the asm parser.
5205     case 'M': {
5206       if (!isUInt<32>(CVal))
5207         return;
5208       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5209         break;
5210       if ((CVal & 0xFFFF) == CVal)
5211         break;
5212       if ((CVal & 0xFFFF0000ULL) == CVal)
5213         break;
5214       uint64_t NCVal = ~(uint32_t)CVal;
5215       if ((NCVal & 0xFFFFULL) == NCVal)
5216         break;
5217       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5218         break;
5219       return;
5220     }
5221     case 'N': {
5222       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5223         break;
5224       if ((CVal & 0xFFFFULL) == CVal)
5225         break;
5226       if ((CVal & 0xFFFF0000ULL) == CVal)
5227         break;
5228       if ((CVal & 0xFFFF00000000ULL) == CVal)
5229         break;
5230       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5231         break;
5232       uint64_t NCVal = ~CVal;
5233       if ((NCVal & 0xFFFFULL) == NCVal)
5234         break;
5235       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5236         break;
5237       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5238         break;
5239       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5240         break;
5241       return;
5242     }
5243     default:
5244       return;
5245     }
5246
5247     // All assembler immediates are 64-bit integers.
5248     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5249     break;
5250   }
5251
5252   if (Result.getNode()) {
5253     Ops.push_back(Result);
5254     return;
5255   }
5256
5257   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5258 }
5259
5260 //===----------------------------------------------------------------------===//
5261 //                     AArch64 Advanced SIMD Support
5262 //===----------------------------------------------------------------------===//
5263
5264 /// WidenVector - Given a value in the V64 register class, produce the
5265 /// equivalent value in the V128 register class.
5266 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5267   EVT VT = V64Reg.getValueType();
5268   unsigned NarrowSize = VT.getVectorNumElements();
5269   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5270   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5271   SDLoc DL(V64Reg);
5272
5273   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5274                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5275 }
5276
5277 /// getExtFactor - Determine the adjustment factor for the position when
5278 /// generating an "extract from vector registers" instruction.
5279 static unsigned getExtFactor(SDValue &V) {
5280   EVT EltType = V.getValueType().getVectorElementType();
5281   return EltType.getSizeInBits() / 8;
5282 }
5283
5284 /// NarrowVector - Given a value in the V128 register class, produce the
5285 /// equivalent value in the V64 register class.
5286 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5287   EVT VT = V128Reg.getValueType();
5288   unsigned WideSize = VT.getVectorNumElements();
5289   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5290   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5291   SDLoc DL(V128Reg);
5292
5293   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5294 }
5295
5296 // Gather data to see if the operation can be modelled as a
5297 // shuffle in combination with VEXTs.
5298 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5299                                                   SelectionDAG &DAG) const {
5300   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5301   SDLoc dl(Op);
5302   EVT VT = Op.getValueType();
5303   unsigned NumElts = VT.getVectorNumElements();
5304
5305   struct ShuffleSourceInfo {
5306     SDValue Vec;
5307     unsigned MinElt;
5308     unsigned MaxElt;
5309
5310     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5311     // be compatible with the shuffle we intend to construct. As a result
5312     // ShuffleVec will be some sliding window into the original Vec.
5313     SDValue ShuffleVec;
5314
5315     // Code should guarantee that element i in Vec starts at element "WindowBase
5316     // + i * WindowScale in ShuffleVec".
5317     int WindowBase;
5318     int WindowScale;
5319
5320     ShuffleSourceInfo(SDValue Vec)
5321       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5322           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5323
5324     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5325   };
5326
5327   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5328   // node.
5329   SmallVector<ShuffleSourceInfo, 2> Sources;
5330   for (unsigned i = 0; i < NumElts; ++i) {
5331     SDValue V = Op.getOperand(i);
5332     if (V.isUndef())
5333       continue;
5334     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5335              !isa<ConstantSDNode>(V.getOperand(1))) {
5336       // A shuffle can only come from building a vector from various
5337       // elements of other vectors, provided their indices are constant.
5338       return SDValue();
5339     }
5340
5341     // Add this element source to the list if it's not already there.
5342     SDValue SourceVec = V.getOperand(0);
5343     auto Source = find(Sources, SourceVec);
5344     if (Source == Sources.end())
5345       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5346
5347     // Update the minimum and maximum lane number seen.
5348     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5349     Source->MinElt = std::min(Source->MinElt, EltNo);
5350     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5351   }
5352
5353   // Currently only do something sane when at most two source vectors
5354   // are involved.
5355   if (Sources.size() > 2)
5356     return SDValue();
5357
5358   // Find out the smallest element size among result and two sources, and use
5359   // it as element size to build the shuffle_vector.
5360   EVT SmallestEltTy = VT.getVectorElementType();
5361   for (auto &Source : Sources) {
5362     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5363     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5364       SmallestEltTy = SrcEltTy;
5365     }
5366   }
5367   unsigned ResMultiplier =
5368       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5369   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5370   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5371
5372   // If the source vector is too wide or too narrow, we may nevertheless be able
5373   // to construct a compatible shuffle either by concatenating it with UNDEF or
5374   // extracting a suitable range of elements.
5375   for (auto &Src : Sources) {
5376     EVT SrcVT = Src.ShuffleVec.getValueType();
5377
5378     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5379       continue;
5380
5381     // This stage of the search produces a source with the same element type as
5382     // the original, but with a total width matching the BUILD_VECTOR output.
5383     EVT EltVT = SrcVT.getVectorElementType();
5384     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5385     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5386
5387     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5388       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5389       // We can pad out the smaller vector for free, so if it's part of a
5390       // shuffle...
5391       Src.ShuffleVec =
5392           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5393                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5394       continue;
5395     }
5396
5397     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5398
5399     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5400       // Span too large for a VEXT to cope
5401       return SDValue();
5402     }
5403
5404     if (Src.MinElt >= NumSrcElts) {
5405       // The extraction can just take the second half
5406       Src.ShuffleVec =
5407           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5408                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5409       Src.WindowBase = -NumSrcElts;
5410     } else if (Src.MaxElt < NumSrcElts) {
5411       // The extraction can just take the first half
5412       Src.ShuffleVec =
5413           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5414                       DAG.getConstant(0, dl, MVT::i64));
5415     } else {
5416       // An actual VEXT is needed
5417       SDValue VEXTSrc1 =
5418           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5419                       DAG.getConstant(0, dl, MVT::i64));
5420       SDValue VEXTSrc2 =
5421           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5422                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5423       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5424
5425       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5426                                    VEXTSrc2,
5427                                    DAG.getConstant(Imm, dl, MVT::i32));
5428       Src.WindowBase = -Src.MinElt;
5429     }
5430   }
5431
5432   // Another possible incompatibility occurs from the vector element types. We
5433   // can fix this by bitcasting the source vectors to the same type we intend
5434   // for the shuffle.
5435   for (auto &Src : Sources) {
5436     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5437     if (SrcEltTy == SmallestEltTy)
5438       continue;
5439     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5440     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5441     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5442     Src.WindowBase *= Src.WindowScale;
5443   }
5444
5445   // Final sanity check before we try to actually produce a shuffle.
5446   DEBUG(
5447     for (auto Src : Sources)
5448       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5449   );
5450
5451   // The stars all align, our next step is to produce the mask for the shuffle.
5452   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5453   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5454   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5455     SDValue Entry = Op.getOperand(i);
5456     if (Entry.isUndef())
5457       continue;
5458
5459     auto Src = find(Sources, Entry.getOperand(0));
5460     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5461
5462     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5463     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5464     // segment.
5465     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5466     int BitsDefined =
5467         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5468     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5469
5470     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5471     // starting at the appropriate offset.
5472     int *LaneMask = &Mask[i * ResMultiplier];
5473
5474     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5475     ExtractBase += NumElts * (Src - Sources.begin());
5476     for (int j = 0; j < LanesDefined; ++j)
5477       LaneMask[j] = ExtractBase + j;
5478   }
5479
5480   // Final check before we try to produce nonsense...
5481   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5482     return SDValue();
5483
5484   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5485   for (unsigned i = 0; i < Sources.size(); ++i)
5486     ShuffleOps[i] = Sources[i].ShuffleVec;
5487
5488   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5489                                          ShuffleOps[1], Mask);
5490   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5491 }
5492
5493 // check if an EXT instruction can handle the shuffle mask when the
5494 // vector sources of the shuffle are the same.
5495 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5496   unsigned NumElts = VT.getVectorNumElements();
5497
5498   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5499   if (M[0] < 0)
5500     return false;
5501
5502   Imm = M[0];
5503
5504   // If this is a VEXT shuffle, the immediate value is the index of the first
5505   // element.  The other shuffle indices must be the successive elements after
5506   // the first one.
5507   unsigned ExpectedElt = Imm;
5508   for (unsigned i = 1; i < NumElts; ++i) {
5509     // Increment the expected index.  If it wraps around, just follow it
5510     // back to index zero and keep going.
5511     ++ExpectedElt;
5512     if (ExpectedElt == NumElts)
5513       ExpectedElt = 0;
5514
5515     if (M[i] < 0)
5516       continue; // ignore UNDEF indices
5517     if (ExpectedElt != static_cast<unsigned>(M[i]))
5518       return false;
5519   }
5520
5521   return true;
5522 }
5523
5524 // check if an EXT instruction can handle the shuffle mask when the
5525 // vector sources of the shuffle are different.
5526 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5527                       unsigned &Imm) {
5528   // Look for the first non-undef element.
5529   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5530
5531   // Benefit form APInt to handle overflow when calculating expected element.
5532   unsigned NumElts = VT.getVectorNumElements();
5533   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5534   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5535   // The following shuffle indices must be the successive elements after the
5536   // first real element.
5537   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5538       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5539   if (FirstWrongElt != M.end())
5540     return false;
5541
5542   // The index of an EXT is the first element if it is not UNDEF.
5543   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5544   // value of the first element.  E.g.
5545   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5546   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5547   // ExpectedElt is the last mask index plus 1.
5548   Imm = ExpectedElt.getZExtValue();
5549
5550   // There are two difference cases requiring to reverse input vectors.
5551   // For example, for vector <4 x i32> we have the following cases,
5552   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5553   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5554   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5555   // to reverse two input vectors.
5556   if (Imm < NumElts)
5557     ReverseEXT = true;
5558   else
5559     Imm -= NumElts;
5560
5561   return true;
5562 }
5563
5564 /// isREVMask - Check if a vector shuffle corresponds to a REV
5565 /// instruction with the specified blocksize.  (The order of the elements
5566 /// within each block of the vector is reversed.)
5567 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5568   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5569          "Only possible block sizes for REV are: 16, 32, 64");
5570
5571   unsigned EltSz = VT.getScalarSizeInBits();
5572   if (EltSz == 64)
5573     return false;
5574
5575   unsigned NumElts = VT.getVectorNumElements();
5576   unsigned BlockElts = M[0] + 1;
5577   // If the first shuffle index is UNDEF, be optimistic.
5578   if (M[0] < 0)
5579     BlockElts = BlockSize / EltSz;
5580
5581   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5582     return false;
5583
5584   for (unsigned i = 0; i < NumElts; ++i) {
5585     if (M[i] < 0)
5586       continue; // ignore UNDEF indices
5587     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5588       return false;
5589   }
5590
5591   return true;
5592 }
5593
5594 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5595   unsigned NumElts = VT.getVectorNumElements();
5596   WhichResult = (M[0] == 0 ? 0 : 1);
5597   unsigned Idx = WhichResult * NumElts / 2;
5598   for (unsigned i = 0; i != NumElts; i += 2) {
5599     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5600         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5601       return false;
5602     Idx += 1;
5603   }
5604
5605   return true;
5606 }
5607
5608 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5609   unsigned NumElts = VT.getVectorNumElements();
5610   WhichResult = (M[0] == 0 ? 0 : 1);
5611   for (unsigned i = 0; i != NumElts; ++i) {
5612     if (M[i] < 0)
5613       continue; // ignore UNDEF indices
5614     if ((unsigned)M[i] != 2 * i + WhichResult)
5615       return false;
5616   }
5617
5618   return true;
5619 }
5620
5621 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5622   unsigned NumElts = VT.getVectorNumElements();
5623   WhichResult = (M[0] == 0 ? 0 : 1);
5624   for (unsigned i = 0; i < NumElts; i += 2) {
5625     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5626         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5627       return false;
5628   }
5629   return true;
5630 }
5631
5632 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5633 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5634 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5635 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5636   unsigned NumElts = VT.getVectorNumElements();
5637   WhichResult = (M[0] == 0 ? 0 : 1);
5638   unsigned Idx = WhichResult * NumElts / 2;
5639   for (unsigned i = 0; i != NumElts; i += 2) {
5640     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5641         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5642       return false;
5643     Idx += 1;
5644   }
5645
5646   return true;
5647 }
5648
5649 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5650 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5651 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5652 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5653   unsigned Half = VT.getVectorNumElements() / 2;
5654   WhichResult = (M[0] == 0 ? 0 : 1);
5655   for (unsigned j = 0; j != 2; ++j) {
5656     unsigned Idx = WhichResult;
5657     for (unsigned i = 0; i != Half; ++i) {
5658       int MIdx = M[i + j * Half];
5659       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5660         return false;
5661       Idx += 2;
5662     }
5663   }
5664
5665   return true;
5666 }
5667
5668 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5669 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5670 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5671 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5672   unsigned NumElts = VT.getVectorNumElements();
5673   WhichResult = (M[0] == 0 ? 0 : 1);
5674   for (unsigned i = 0; i < NumElts; i += 2) {
5675     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5676         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5677       return false;
5678   }
5679   return true;
5680 }
5681
5682 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5683                       bool &DstIsLeft, int &Anomaly) {
5684   if (M.size() != static_cast<size_t>(NumInputElements))
5685     return false;
5686
5687   int NumLHSMatch = 0, NumRHSMatch = 0;
5688   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5689
5690   for (int i = 0; i < NumInputElements; ++i) {
5691     if (M[i] == -1) {
5692       ++NumLHSMatch;
5693       ++NumRHSMatch;
5694       continue;
5695     }
5696
5697     if (M[i] == i)
5698       ++NumLHSMatch;
5699     else
5700       LastLHSMismatch = i;
5701
5702     if (M[i] == i + NumInputElements)
5703       ++NumRHSMatch;
5704     else
5705       LastRHSMismatch = i;
5706   }
5707
5708   if (NumLHSMatch == NumInputElements - 1) {
5709     DstIsLeft = true;
5710     Anomaly = LastLHSMismatch;
5711     return true;
5712   } else if (NumRHSMatch == NumInputElements - 1) {
5713     DstIsLeft = false;
5714     Anomaly = LastRHSMismatch;
5715     return true;
5716   }
5717
5718   return false;
5719 }
5720
5721 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5722   if (VT.getSizeInBits() != 128)
5723     return false;
5724
5725   unsigned NumElts = VT.getVectorNumElements();
5726
5727   for (int I = 0, E = NumElts / 2; I != E; I++) {
5728     if (Mask[I] != I)
5729       return false;
5730   }
5731
5732   int Offset = NumElts / 2;
5733   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5734     if (Mask[I] != I + SplitLHS * Offset)
5735       return false;
5736   }
5737
5738   return true;
5739 }
5740
5741 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5742   SDLoc DL(Op);
5743   EVT VT = Op.getValueType();
5744   SDValue V0 = Op.getOperand(0);
5745   SDValue V1 = Op.getOperand(1);
5746   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5747
5748   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5749       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5750     return SDValue();
5751
5752   bool SplitV0 = V0.getValueSizeInBits() == 128;
5753
5754   if (!isConcatMask(Mask, VT, SplitV0))
5755     return SDValue();
5756
5757   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5758                                 VT.getVectorNumElements() / 2);
5759   if (SplitV0) {
5760     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5761                      DAG.getConstant(0, DL, MVT::i64));
5762   }
5763   if (V1.getValueSizeInBits() == 128) {
5764     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5765                      DAG.getConstant(0, DL, MVT::i64));
5766   }
5767   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5768 }
5769
5770 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5771 /// the specified operations to build the shuffle.
5772 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5773                                       SDValue RHS, SelectionDAG &DAG,
5774                                       const SDLoc &dl) {
5775   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5776   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5777   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5778
5779   enum {
5780     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5781     OP_VREV,
5782     OP_VDUP0,
5783     OP_VDUP1,
5784     OP_VDUP2,
5785     OP_VDUP3,
5786     OP_VEXT1,
5787     OP_VEXT2,
5788     OP_VEXT3,
5789     OP_VUZPL, // VUZP, left result
5790     OP_VUZPR, // VUZP, right result
5791     OP_VZIPL, // VZIP, left result
5792     OP_VZIPR, // VZIP, right result
5793     OP_VTRNL, // VTRN, left result
5794     OP_VTRNR  // VTRN, right result
5795   };
5796
5797   if (OpNum == OP_COPY) {
5798     if (LHSID == (1 * 9 + 2) * 9 + 3)
5799       return LHS;
5800     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5801     return RHS;
5802   }
5803
5804   SDValue OpLHS, OpRHS;
5805   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5806   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5807   EVT VT = OpLHS.getValueType();
5808
5809   switch (OpNum) {
5810   default:
5811     llvm_unreachable("Unknown shuffle opcode!");
5812   case OP_VREV:
5813     // VREV divides the vector in half and swaps within the half.
5814     if (VT.getVectorElementType() == MVT::i32 ||
5815         VT.getVectorElementType() == MVT::f32)
5816       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5817     // vrev <4 x i16> -> REV32
5818     if (VT.getVectorElementType() == MVT::i16 ||
5819         VT.getVectorElementType() == MVT::f16)
5820       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5821     // vrev <4 x i8> -> REV16
5822     assert(VT.getVectorElementType() == MVT::i8);
5823     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5824   case OP_VDUP0:
5825   case OP_VDUP1:
5826   case OP_VDUP2:
5827   case OP_VDUP3: {
5828     EVT EltTy = VT.getVectorElementType();
5829     unsigned Opcode;
5830     if (EltTy == MVT::i8)
5831       Opcode = AArch64ISD::DUPLANE8;
5832     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5833       Opcode = AArch64ISD::DUPLANE16;
5834     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5835       Opcode = AArch64ISD::DUPLANE32;
5836     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5837       Opcode = AArch64ISD::DUPLANE64;
5838     else
5839       llvm_unreachable("Invalid vector element type?");
5840
5841     if (VT.getSizeInBits() == 64)
5842       OpLHS = WidenVector(OpLHS, DAG);
5843     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5844     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5845   }
5846   case OP_VEXT1:
5847   case OP_VEXT2:
5848   case OP_VEXT3: {
5849     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5850     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5851                        DAG.getConstant(Imm, dl, MVT::i32));
5852   }
5853   case OP_VUZPL:
5854     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5855                        OpRHS);
5856   case OP_VUZPR:
5857     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5858                        OpRHS);
5859   case OP_VZIPL:
5860     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5861                        OpRHS);
5862   case OP_VZIPR:
5863     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5864                        OpRHS);
5865   case OP_VTRNL:
5866     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5867                        OpRHS);
5868   case OP_VTRNR:
5869     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5870                        OpRHS);
5871   }
5872 }
5873
5874 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5875                            SelectionDAG &DAG) {
5876   // Check to see if we can use the TBL instruction.
5877   SDValue V1 = Op.getOperand(0);
5878   SDValue V2 = Op.getOperand(1);
5879   SDLoc DL(Op);
5880
5881   EVT EltVT = Op.getValueType().getVectorElementType();
5882   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5883
5884   SmallVector<SDValue, 8> TBLMask;
5885   for (int Val : ShuffleMask) {
5886     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5887       unsigned Offset = Byte + Val * BytesPerElt;
5888       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5889     }
5890   }
5891
5892   MVT IndexVT = MVT::v8i8;
5893   unsigned IndexLen = 8;
5894   if (Op.getValueSizeInBits() == 128) {
5895     IndexVT = MVT::v16i8;
5896     IndexLen = 16;
5897   }
5898
5899   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5900   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5901
5902   SDValue Shuffle;
5903   if (V2.getNode()->isUndef()) {
5904     if (IndexLen == 8)
5905       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5906     Shuffle = DAG.getNode(
5907         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5908         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5909         DAG.getBuildVector(IndexVT, DL,
5910                            makeArrayRef(TBLMask.data(), IndexLen)));
5911   } else {
5912     if (IndexLen == 8) {
5913       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5914       Shuffle = DAG.getNode(
5915           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5916           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5917           DAG.getBuildVector(IndexVT, DL,
5918                              makeArrayRef(TBLMask.data(), IndexLen)));
5919     } else {
5920       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5921       // cannot currently represent the register constraints on the input
5922       // table registers.
5923       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5924       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5925       //                   IndexLen));
5926       Shuffle = DAG.getNode(
5927           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5928           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5929           V2Cst, DAG.getBuildVector(IndexVT, DL,
5930                                     makeArrayRef(TBLMask.data(), IndexLen)));
5931     }
5932   }
5933   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5934 }
5935
5936 static unsigned getDUPLANEOp(EVT EltType) {
5937   if (EltType == MVT::i8)
5938     return AArch64ISD::DUPLANE8;
5939   if (EltType == MVT::i16 || EltType == MVT::f16)
5940     return AArch64ISD::DUPLANE16;
5941   if (EltType == MVT::i32 || EltType == MVT::f32)
5942     return AArch64ISD::DUPLANE32;
5943   if (EltType == MVT::i64 || EltType == MVT::f64)
5944     return AArch64ISD::DUPLANE64;
5945
5946   llvm_unreachable("Invalid vector element type?");
5947 }
5948
5949 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5950                                                    SelectionDAG &DAG) const {
5951   SDLoc dl(Op);
5952   EVT VT = Op.getValueType();
5953
5954   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5955
5956   // Convert shuffles that are directly supported on NEON to target-specific
5957   // DAG nodes, instead of keeping them as shuffles and matching them again
5958   // during code selection.  This is more efficient and avoids the possibility
5959   // of inconsistencies between legalization and selection.
5960   ArrayRef<int> ShuffleMask = SVN->getMask();
5961
5962   SDValue V1 = Op.getOperand(0);
5963   SDValue V2 = Op.getOperand(1);
5964
5965   if (SVN->isSplat()) {
5966     int Lane = SVN->getSplatIndex();
5967     // If this is undef splat, generate it via "just" vdup, if possible.
5968     if (Lane == -1)
5969       Lane = 0;
5970
5971     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5972       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5973                          V1.getOperand(0));
5974     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5975     // constant. If so, we can just reference the lane's definition directly.
5976     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5977         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5978       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5979
5980     // Otherwise, duplicate from the lane of the input vector.
5981     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5982
5983     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5984     // to make a vector of the same size as this SHUFFLE. We can ignore the
5985     // extract entirely, and canonicalise the concat using WidenVector.
5986     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5987       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5988       V1 = V1.getOperand(0);
5989     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5990       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5991       Lane -= Idx * VT.getVectorNumElements() / 2;
5992       V1 = WidenVector(V1.getOperand(Idx), DAG);
5993     } else if (VT.getSizeInBits() == 64)
5994       V1 = WidenVector(V1, DAG);
5995
5996     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5997   }
5998
5999   if (isREVMask(ShuffleMask, VT, 64))
6000     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6001   if (isREVMask(ShuffleMask, VT, 32))
6002     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6003   if (isREVMask(ShuffleMask, VT, 16))
6004     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6005
6006   bool ReverseEXT = false;
6007   unsigned Imm;
6008   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6009     if (ReverseEXT)
6010       std::swap(V1, V2);
6011     Imm *= getExtFactor(V1);
6012     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6013                        DAG.getConstant(Imm, dl, MVT::i32));
6014   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6015     Imm *= getExtFactor(V1);
6016     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6017                        DAG.getConstant(Imm, dl, MVT::i32));
6018   }
6019
6020   unsigned WhichResult;
6021   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6022     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6023     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6024   }
6025   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6026     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6027     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6028   }
6029   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6030     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6031     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6032   }
6033
6034   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6035     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6036     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6037   }
6038   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6039     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6040     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6041   }
6042   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6043     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6044     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6045   }
6046
6047   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6048     return Concat;
6049
6050   bool DstIsLeft;
6051   int Anomaly;
6052   int NumInputElements = V1.getValueType().getVectorNumElements();
6053   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6054     SDValue DstVec = DstIsLeft ? V1 : V2;
6055     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6056
6057     SDValue SrcVec = V1;
6058     int SrcLane = ShuffleMask[Anomaly];
6059     if (SrcLane >= NumInputElements) {
6060       SrcVec = V2;
6061       SrcLane -= VT.getVectorNumElements();
6062     }
6063     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6064
6065     EVT ScalarVT = VT.getVectorElementType();
6066
6067     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6068       ScalarVT = MVT::i32;
6069
6070     return DAG.getNode(
6071         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6072         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6073         DstLaneV);
6074   }
6075
6076   // If the shuffle is not directly supported and it has 4 elements, use
6077   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6078   unsigned NumElts = VT.getVectorNumElements();
6079   if (NumElts == 4) {
6080     unsigned PFIndexes[4];
6081     for (unsigned i = 0; i != 4; ++i) {
6082       if (ShuffleMask[i] < 0)
6083         PFIndexes[i] = 8;
6084       else
6085         PFIndexes[i] = ShuffleMask[i];
6086     }
6087
6088     // Compute the index in the perfect shuffle table.
6089     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6090                             PFIndexes[2] * 9 + PFIndexes[3];
6091     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6092     unsigned Cost = (PFEntry >> 30);
6093
6094     if (Cost <= 4)
6095       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6096   }
6097
6098   return GenerateTBL(Op, ShuffleMask, DAG);
6099 }
6100
6101 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6102                                APInt &UndefBits) {
6103   EVT VT = BVN->getValueType(0);
6104   APInt SplatBits, SplatUndef;
6105   unsigned SplatBitSize;
6106   bool HasAnyUndefs;
6107   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6108     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6109
6110     for (unsigned i = 0; i < NumSplats; ++i) {
6111       CnstBits <<= SplatBitSize;
6112       UndefBits <<= SplatBitSize;
6113       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6114       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6115     }
6116
6117     return true;
6118   }
6119
6120   return false;
6121 }
6122
6123 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6124                                               SelectionDAG &DAG) const {
6125   BuildVectorSDNode *BVN =
6126       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6127   SDValue LHS = Op.getOperand(0);
6128   SDLoc dl(Op);
6129   EVT VT = Op.getValueType();
6130
6131   if (!BVN)
6132     return Op;
6133
6134   APInt CnstBits(VT.getSizeInBits(), 0);
6135   APInt UndefBits(VT.getSizeInBits(), 0);
6136   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6137     // We only have BIC vector immediate instruction, which is and-not.
6138     CnstBits = ~CnstBits;
6139
6140     // We make use of a little bit of goto ickiness in order to avoid having to
6141     // duplicate the immediate matching logic for the undef toggled case.
6142     bool SecondTry = false;
6143   AttemptModImm:
6144
6145     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6146       CnstBits = CnstBits.zextOrTrunc(64);
6147       uint64_t CnstVal = CnstBits.getZExtValue();
6148
6149       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6150         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6151         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6152         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6153                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6154                                   DAG.getConstant(0, dl, MVT::i32));
6155         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6156       }
6157
6158       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6159         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6160         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6161         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6162                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6163                                   DAG.getConstant(8, dl, MVT::i32));
6164         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6165       }
6166
6167       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6168         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6169         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6170         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6171                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6172                                   DAG.getConstant(16, dl, MVT::i32));
6173         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6174       }
6175
6176       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6177         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6178         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6179         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6180                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6181                                   DAG.getConstant(24, dl, MVT::i32));
6182         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6183       }
6184
6185       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6186         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6187         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6188         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6189                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6190                                   DAG.getConstant(0, dl, MVT::i32));
6191         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6192       }
6193
6194       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6195         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6196         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6197         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6198                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6199                                   DAG.getConstant(8, dl, MVT::i32));
6200         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6201       }
6202     }
6203
6204     if (SecondTry)
6205       goto FailedModImm;
6206     SecondTry = true;
6207     CnstBits = ~UndefBits;
6208     goto AttemptModImm;
6209   }
6210
6211 // We can always fall back to a non-immediate AND.
6212 FailedModImm:
6213   return Op;
6214 }
6215
6216 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6217 // consists of only the same constant int value, returned in reference arg
6218 // ConstVal
6219 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6220                                      uint64_t &ConstVal) {
6221   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6222   if (!Bvec)
6223     return false;
6224   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6225   if (!FirstElt)
6226     return false;
6227   EVT VT = Bvec->getValueType(0);
6228   unsigned NumElts = VT.getVectorNumElements();
6229   for (unsigned i = 1; i < NumElts; ++i)
6230     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6231       return false;
6232   ConstVal = FirstElt->getZExtValue();
6233   return true;
6234 }
6235
6236 static unsigned getIntrinsicID(const SDNode *N) {
6237   unsigned Opcode = N->getOpcode();
6238   switch (Opcode) {
6239   default:
6240     return Intrinsic::not_intrinsic;
6241   case ISD::INTRINSIC_WO_CHAIN: {
6242     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6243     if (IID < Intrinsic::num_intrinsics)
6244       return IID;
6245     return Intrinsic::not_intrinsic;
6246   }
6247   }
6248 }
6249
6250 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6251 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6252 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6253 // Also, logical shift right -> sri, with the same structure.
6254 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6255   EVT VT = N->getValueType(0);
6256
6257   if (!VT.isVector())
6258     return SDValue();
6259
6260   SDLoc DL(N);
6261
6262   // Is the first op an AND?
6263   const SDValue And = N->getOperand(0);
6264   if (And.getOpcode() != ISD::AND)
6265     return SDValue();
6266
6267   // Is the second op an shl or lshr?
6268   SDValue Shift = N->getOperand(1);
6269   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6270   // or AArch64ISD::VLSHR vector, #shift
6271   unsigned ShiftOpc = Shift.getOpcode();
6272   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6273     return SDValue();
6274   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6275
6276   // Is the shift amount constant?
6277   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6278   if (!C2node)
6279     return SDValue();
6280
6281   // Is the and mask vector all constant?
6282   uint64_t C1;
6283   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6284     return SDValue();
6285
6286   // Is C1 == ~C2, taking into account how much one can shift elements of a
6287   // particular size?
6288   uint64_t C2 = C2node->getZExtValue();
6289   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6290   if (C2 > ElemSizeInBits)
6291     return SDValue();
6292   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6293   if ((C1 & ElemMask) != (~C2 & ElemMask))
6294     return SDValue();
6295
6296   SDValue X = And.getOperand(0);
6297   SDValue Y = Shift.getOperand(0);
6298
6299   unsigned Intrin =
6300       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6301   SDValue ResultSLI =
6302       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6303                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6304                   Shift.getOperand(1));
6305
6306   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6307   DEBUG(N->dump(&DAG));
6308   DEBUG(dbgs() << "into: \n");
6309   DEBUG(ResultSLI->dump(&DAG));
6310
6311   ++NumShiftInserts;
6312   return ResultSLI;
6313 }
6314
6315 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6316                                              SelectionDAG &DAG) const {
6317   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6318   if (EnableAArch64SlrGeneration) {
6319     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6320       return Res;
6321   }
6322
6323   BuildVectorSDNode *BVN =
6324       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6325   SDValue LHS = Op.getOperand(1);
6326   SDLoc dl(Op);
6327   EVT VT = Op.getValueType();
6328
6329   // OR commutes, so try swapping the operands.
6330   if (!BVN) {
6331     LHS = Op.getOperand(0);
6332     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6333   }
6334   if (!BVN)
6335     return Op;
6336
6337   APInt CnstBits(VT.getSizeInBits(), 0);
6338   APInt UndefBits(VT.getSizeInBits(), 0);
6339   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6340     // We make use of a little bit of goto ickiness in order to avoid having to
6341     // duplicate the immediate matching logic for the undef toggled case.
6342     bool SecondTry = false;
6343   AttemptModImm:
6344
6345     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6346       CnstBits = CnstBits.zextOrTrunc(64);
6347       uint64_t CnstVal = CnstBits.getZExtValue();
6348
6349       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6350         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6351         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6352         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6353                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6354                                   DAG.getConstant(0, dl, MVT::i32));
6355         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6356       }
6357
6358       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6359         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6360         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6361         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6362                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6363                                   DAG.getConstant(8, dl, MVT::i32));
6364         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6365       }
6366
6367       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6368         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6369         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6370         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6371                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6372                                   DAG.getConstant(16, dl, MVT::i32));
6373         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6374       }
6375
6376       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6377         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6378         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6379         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6380                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6381                                   DAG.getConstant(24, dl, MVT::i32));
6382         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6383       }
6384
6385       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6386         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6387         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6388         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6389                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6390                                   DAG.getConstant(0, dl, MVT::i32));
6391         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6392       }
6393
6394       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6395         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6396         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6397         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6398                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6399                                   DAG.getConstant(8, dl, MVT::i32));
6400         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6401       }
6402     }
6403
6404     if (SecondTry)
6405       goto FailedModImm;
6406     SecondTry = true;
6407     CnstBits = UndefBits;
6408     goto AttemptModImm;
6409   }
6410
6411 // We can always fall back to a non-immediate OR.
6412 FailedModImm:
6413   return Op;
6414 }
6415
6416 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6417 // be truncated to fit element width.
6418 static SDValue NormalizeBuildVector(SDValue Op,
6419                                     SelectionDAG &DAG) {
6420   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6421   SDLoc dl(Op);
6422   EVT VT = Op.getValueType();
6423   EVT EltTy= VT.getVectorElementType();
6424
6425   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6426     return Op;
6427
6428   SmallVector<SDValue, 16> Ops;
6429   for (SDValue Lane : Op->ops()) {
6430     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6431       APInt LowBits(EltTy.getSizeInBits(),
6432                     CstLane->getZExtValue());
6433       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6434     }
6435     Ops.push_back(Lane);
6436   }
6437   return DAG.getBuildVector(VT, dl, Ops);
6438 }
6439
6440 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6441                                                  SelectionDAG &DAG) const {
6442   SDLoc dl(Op);
6443   EVT VT = Op.getValueType();
6444   Op = NormalizeBuildVector(Op, DAG);
6445   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6446
6447   APInt CnstBits(VT.getSizeInBits(), 0);
6448   APInt UndefBits(VT.getSizeInBits(), 0);
6449   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6450     // We make use of a little bit of goto ickiness in order to avoid having to
6451     // duplicate the immediate matching logic for the undef toggled case.
6452     bool SecondTry = false;
6453   AttemptModImm:
6454
6455     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6456       CnstBits = CnstBits.zextOrTrunc(64);
6457       uint64_t CnstVal = CnstBits.getZExtValue();
6458
6459       // Certain magic vector constants (used to express things like NOT
6460       // and NEG) are passed through unmodified.  This allows codegen patterns
6461       // for these operations to match.  Special-purpose patterns will lower
6462       // these immediates to MOVIs if it proves necessary.
6463       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6464         return Op;
6465
6466       // The many faces of MOVI...
6467       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6468         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6469         if (VT.getSizeInBits() == 128) {
6470           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6471                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6472           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6473         }
6474
6475         // Support the V64 version via subregister insertion.
6476         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6477                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6478         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6479       }
6480
6481       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6482         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6483         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6484         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6485                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6486                                   DAG.getConstant(0, dl, MVT::i32));
6487         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6488       }
6489
6490       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6491         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6492         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6493         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6494                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6495                                   DAG.getConstant(8, dl, MVT::i32));
6496         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6497       }
6498
6499       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6500         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6501         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6502         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6503                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6504                                   DAG.getConstant(16, dl, MVT::i32));
6505         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6506       }
6507
6508       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6509         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6510         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6511         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6512                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6513                                   DAG.getConstant(24, dl, MVT::i32));
6514         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6515       }
6516
6517       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6518         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6519         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6520         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6521                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6522                                   DAG.getConstant(0, dl, MVT::i32));
6523         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6524       }
6525
6526       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6527         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6528         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6529         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6530                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6531                                   DAG.getConstant(8, dl, MVT::i32));
6532         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6533       }
6534
6535       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6536         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6537         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6538         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6539                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6540                                   DAG.getConstant(264, dl, MVT::i32));
6541         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6542       }
6543
6544       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6545         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6546         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6547         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6548                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6549                                   DAG.getConstant(272, dl, MVT::i32));
6550         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6551       }
6552
6553       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6554         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6555         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6556         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6557                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6558         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6559       }
6560
6561       // The few faces of FMOV...
6562       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6563         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6564         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6565         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6566                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6567         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6568       }
6569
6570       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6571           VT.getSizeInBits() == 128) {
6572         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6573         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6574                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6575         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6576       }
6577
6578       // The many faces of MVNI...
6579       CnstVal = ~CnstVal;
6580       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6581         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6582         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6583         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6584                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6585                                   DAG.getConstant(0, dl, MVT::i32));
6586         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6587       }
6588
6589       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6590         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6591         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6592         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6593                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6594                                   DAG.getConstant(8, dl, MVT::i32));
6595         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6596       }
6597
6598       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6599         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6600         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6601         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6602                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6603                                   DAG.getConstant(16, dl, MVT::i32));
6604         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6605       }
6606
6607       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6608         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6609         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6610         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6611                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6612                                   DAG.getConstant(24, dl, MVT::i32));
6613         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6614       }
6615
6616       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6617         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6618         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6619         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6620                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6621                                   DAG.getConstant(0, dl, MVT::i32));
6622         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6623       }
6624
6625       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6626         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6627         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6628         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6629                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6630                                   DAG.getConstant(8, dl, MVT::i32));
6631         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6632       }
6633
6634       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6635         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6636         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6637         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6638                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6639                                   DAG.getConstant(264, dl, MVT::i32));
6640         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6641       }
6642
6643       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6644         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6645         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6646         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6647                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6648                                   DAG.getConstant(272, dl, MVT::i32));
6649         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6650       }
6651     }
6652
6653     if (SecondTry)
6654       goto FailedModImm;
6655     SecondTry = true;
6656     CnstBits = UndefBits;
6657     goto AttemptModImm;
6658   }
6659 FailedModImm:
6660
6661   // Scan through the operands to find some interesting properties we can
6662   // exploit:
6663   //   1) If only one value is used, we can use a DUP, or
6664   //   2) if only the low element is not undef, we can just insert that, or
6665   //   3) if only one constant value is used (w/ some non-constant lanes),
6666   //      we can splat the constant value into the whole vector then fill
6667   //      in the non-constant lanes.
6668   //   4) FIXME: If different constant values are used, but we can intelligently
6669   //             select the values we'll be overwriting for the non-constant
6670   //             lanes such that we can directly materialize the vector
6671   //             some other way (MOVI, e.g.), we can be sneaky.
6672   unsigned NumElts = VT.getVectorNumElements();
6673   bool isOnlyLowElement = true;
6674   bool usesOnlyOneValue = true;
6675   bool usesOnlyOneConstantValue = true;
6676   bool isConstant = true;
6677   unsigned NumConstantLanes = 0;
6678   SDValue Value;
6679   SDValue ConstantValue;
6680   for (unsigned i = 0; i < NumElts; ++i) {
6681     SDValue V = Op.getOperand(i);
6682     if (V.isUndef())
6683       continue;
6684     if (i > 0)
6685       isOnlyLowElement = false;
6686     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6687       isConstant = false;
6688
6689     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6690       ++NumConstantLanes;
6691       if (!ConstantValue.getNode())
6692         ConstantValue = V;
6693       else if (ConstantValue != V)
6694         usesOnlyOneConstantValue = false;
6695     }
6696
6697     if (!Value.getNode())
6698       Value = V;
6699     else if (V != Value)
6700       usesOnlyOneValue = false;
6701   }
6702
6703   if (!Value.getNode())
6704     return DAG.getUNDEF(VT);
6705
6706   if (isOnlyLowElement)
6707     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6708
6709   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6710   // i32 and try again.
6711   if (usesOnlyOneValue) {
6712     if (!isConstant) {
6713       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6714           Value.getValueType() != VT)
6715         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6716
6717       // This is actually a DUPLANExx operation, which keeps everything vectory.
6718
6719       // DUPLANE works on 128-bit vectors, widen it if necessary.
6720       SDValue Lane = Value.getOperand(1);
6721       Value = Value.getOperand(0);
6722       if (Value.getValueSizeInBits() == 64)
6723         Value = WidenVector(Value, DAG);
6724
6725       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6726       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6727     }
6728
6729     if (VT.getVectorElementType().isFloatingPoint()) {
6730       SmallVector<SDValue, 8> Ops;
6731       EVT EltTy = VT.getVectorElementType();
6732       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6733               "Unsupported floating-point vector type");
6734       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6735       for (unsigned i = 0; i < NumElts; ++i)
6736         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6737       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6738       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6739       Val = LowerBUILD_VECTOR(Val, DAG);
6740       if (Val.getNode())
6741         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6742     }
6743   }
6744
6745   // If there was only one constant value used and for more than one lane,
6746   // start by splatting that value, then replace the non-constant lanes. This
6747   // is better than the default, which will perform a separate initialization
6748   // for each lane.
6749   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6750     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6751     // Now insert the non-constant lanes.
6752     for (unsigned i = 0; i < NumElts; ++i) {
6753       SDValue V = Op.getOperand(i);
6754       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6755       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6756         // Note that type legalization likely mucked about with the VT of the
6757         // source operand, so we may have to convert it here before inserting.
6758         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6759       }
6760     }
6761     return Val;
6762   }
6763
6764   // If all elements are constants and the case above didn't get hit, fall back
6765   // to the default expansion, which will generate a load from the constant
6766   // pool.
6767   if (isConstant)
6768     return SDValue();
6769
6770   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6771   if (NumElts >= 4) {
6772     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6773       return shuffle;
6774   }
6775
6776   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6777   // know the default expansion would otherwise fall back on something even
6778   // worse. For a vector with one or two non-undef values, that's
6779   // scalar_to_vector for the elements followed by a shuffle (provided the
6780   // shuffle is valid for the target) and materialization element by element
6781   // on the stack followed by a load for everything else.
6782   if (!isConstant && !usesOnlyOneValue) {
6783     SDValue Vec = DAG.getUNDEF(VT);
6784     SDValue Op0 = Op.getOperand(0);
6785     unsigned i = 0;
6786
6787     // Use SCALAR_TO_VECTOR for lane zero to
6788     // a) Avoid a RMW dependency on the full vector register, and
6789     // b) Allow the register coalescer to fold away the copy if the
6790     //    value is already in an S or D register, and we're forced to emit an
6791     //    INSERT_SUBREG that we can't fold anywhere.
6792     //
6793     // We also allow types like i8 and i16 which are illegal scalar but legal
6794     // vector element types. After type-legalization the inserted value is
6795     // extended (i32) and it is safe to cast them to the vector type by ignoring
6796     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6797     if (!Op0.isUndef()) {
6798       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6799       ++i;
6800     }
6801     for (; i < NumElts; ++i) {
6802       SDValue V = Op.getOperand(i);
6803       if (V.isUndef())
6804         continue;
6805       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6806       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6807     }
6808     return Vec;
6809   }
6810
6811   // Just use the default expansion. We failed to find a better alternative.
6812   return SDValue();
6813 }
6814
6815 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6816                                                       SelectionDAG &DAG) const {
6817   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6818
6819   // Check for non-constant or out of range lane.
6820   EVT VT = Op.getOperand(0).getValueType();
6821   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6822   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6823     return SDValue();
6824
6825
6826   // Insertion/extraction are legal for V128 types.
6827   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6828       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6829       VT == MVT::v8f16)
6830     return Op;
6831
6832   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6833       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6834     return SDValue();
6835
6836   // For V64 types, we perform insertion by expanding the value
6837   // to a V128 type and perform the insertion on that.
6838   SDLoc DL(Op);
6839   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6840   EVT WideTy = WideVec.getValueType();
6841
6842   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6843                              Op.getOperand(1), Op.getOperand(2));
6844   // Re-narrow the resultant vector.
6845   return NarrowVector(Node, DAG);
6846 }
6847
6848 SDValue
6849 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6850                                                SelectionDAG &DAG) const {
6851   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6852
6853   // Check for non-constant or out of range lane.
6854   EVT VT = Op.getOperand(0).getValueType();
6855   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6856   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6857     return SDValue();
6858
6859
6860   // Insertion/extraction are legal for V128 types.
6861   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6862       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6863       VT == MVT::v8f16)
6864     return Op;
6865
6866   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6867       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6868     return SDValue();
6869
6870   // For V64 types, we perform extraction by expanding the value
6871   // to a V128 type and perform the extraction on that.
6872   SDLoc DL(Op);
6873   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6874   EVT WideTy = WideVec.getValueType();
6875
6876   EVT ExtrTy = WideTy.getVectorElementType();
6877   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6878     ExtrTy = MVT::i32;
6879
6880   // For extractions, we just return the result directly.
6881   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6882                      Op.getOperand(1));
6883 }
6884
6885 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6886                                                       SelectionDAG &DAG) const {
6887   EVT VT = Op.getOperand(0).getValueType();
6888   SDLoc dl(Op);
6889   // Just in case...
6890   if (!VT.isVector())
6891     return SDValue();
6892
6893   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6894   if (!Cst)
6895     return SDValue();
6896   unsigned Val = Cst->getZExtValue();
6897
6898   unsigned Size = Op.getValueSizeInBits();
6899
6900   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6901   if (Val == 0)
6902     return Op;
6903
6904   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6905   // that directly.
6906   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6907     return Op;
6908
6909   return SDValue();
6910 }
6911
6912 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6913                                                EVT VT) const {
6914   if (VT.getVectorNumElements() == 4 &&
6915       (VT.is128BitVector() || VT.is64BitVector())) {
6916     unsigned PFIndexes[4];
6917     for (unsigned i = 0; i != 4; ++i) {
6918       if (M[i] < 0)
6919         PFIndexes[i] = 8;
6920       else
6921         PFIndexes[i] = M[i];
6922     }
6923
6924     // Compute the index in the perfect shuffle table.
6925     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6926                             PFIndexes[2] * 9 + PFIndexes[3];
6927     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6928     unsigned Cost = (PFEntry >> 30);
6929
6930     if (Cost <= 4)
6931       return true;
6932   }
6933
6934   bool DummyBool;
6935   int DummyInt;
6936   unsigned DummyUnsigned;
6937
6938   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6939           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6940           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6941           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6942           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6943           isZIPMask(M, VT, DummyUnsigned) ||
6944           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6945           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6946           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6947           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6948           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6949 }
6950
6951 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6952 /// operand of a vector shift operation, where all the elements of the
6953 /// build_vector must have the same constant integer value.
6954 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6955   // Ignore bit_converts.
6956   while (Op.getOpcode() == ISD::BITCAST)
6957     Op = Op.getOperand(0);
6958   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6959   APInt SplatBits, SplatUndef;
6960   unsigned SplatBitSize;
6961   bool HasAnyUndefs;
6962   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6963                                     HasAnyUndefs, ElementBits) ||
6964       SplatBitSize > ElementBits)
6965     return false;
6966   Cnt = SplatBits.getSExtValue();
6967   return true;
6968 }
6969
6970 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6971 /// operand of a vector shift left operation.  That value must be in the range:
6972 ///   0 <= Value < ElementBits for a left shift; or
6973 ///   0 <= Value <= ElementBits for a long left shift.
6974 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6975   assert(VT.isVector() && "vector shift count is not a vector type");
6976   int64_t ElementBits = VT.getScalarSizeInBits();
6977   if (!getVShiftImm(Op, ElementBits, Cnt))
6978     return false;
6979   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6980 }
6981
6982 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6983 /// operand of a vector shift right operation. The value must be in the range:
6984 ///   1 <= Value <= ElementBits for a right shift; or
6985 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6986   assert(VT.isVector() && "vector shift count is not a vector type");
6987   int64_t ElementBits = VT.getScalarSizeInBits();
6988   if (!getVShiftImm(Op, ElementBits, Cnt))
6989     return false;
6990   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6991 }
6992
6993 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6994                                                       SelectionDAG &DAG) const {
6995   EVT VT = Op.getValueType();
6996   SDLoc DL(Op);
6997   int64_t Cnt;
6998
6999   if (!Op.getOperand(1).getValueType().isVector())
7000     return Op;
7001   unsigned EltSize = VT.getScalarSizeInBits();
7002
7003   switch (Op.getOpcode()) {
7004   default:
7005     llvm_unreachable("unexpected shift opcode");
7006
7007   case ISD::SHL:
7008     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7009       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7010                          DAG.getConstant(Cnt, DL, MVT::i32));
7011     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7012                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7013                                        MVT::i32),
7014                        Op.getOperand(0), Op.getOperand(1));
7015   case ISD::SRA:
7016   case ISD::SRL:
7017     // Right shift immediate
7018     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7019       unsigned Opc =
7020           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7021       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7022                          DAG.getConstant(Cnt, DL, MVT::i32));
7023     }
7024
7025     // Right shift register.  Note, there is not a shift right register
7026     // instruction, but the shift left register instruction takes a signed
7027     // value, where negative numbers specify a right shift.
7028     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7029                                                 : Intrinsic::aarch64_neon_ushl;
7030     // negate the shift amount
7031     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7032     SDValue NegShiftLeft =
7033         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7034                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7035                     NegShift);
7036     return NegShiftLeft;
7037   }
7038
7039   return SDValue();
7040 }
7041
7042 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7043                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7044                                     const SDLoc &dl, SelectionDAG &DAG) {
7045   EVT SrcVT = LHS.getValueType();
7046   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7047          "function only supposed to emit natural comparisons");
7048
7049   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7050   APInt CnstBits(VT.getSizeInBits(), 0);
7051   APInt UndefBits(VT.getSizeInBits(), 0);
7052   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7053   bool IsZero = IsCnst && (CnstBits == 0);
7054
7055   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7056     switch (CC) {
7057     default:
7058       return SDValue();
7059     case AArch64CC::NE: {
7060       SDValue Fcmeq;
7061       if (IsZero)
7062         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7063       else
7064         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7065       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7066     }
7067     case AArch64CC::EQ:
7068       if (IsZero)
7069         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7070       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7071     case AArch64CC::GE:
7072       if (IsZero)
7073         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7074       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7075     case AArch64CC::GT:
7076       if (IsZero)
7077         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7078       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7079     case AArch64CC::LS:
7080       if (IsZero)
7081         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7082       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7083     case AArch64CC::LT:
7084       if (!NoNans)
7085         return SDValue();
7086       // If we ignore NaNs then we can use to the MI implementation.
7087       LLVM_FALLTHROUGH;
7088     case AArch64CC::MI:
7089       if (IsZero)
7090         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7091       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7092     }
7093   }
7094
7095   switch (CC) {
7096   default:
7097     return SDValue();
7098   case AArch64CC::NE: {
7099     SDValue Cmeq;
7100     if (IsZero)
7101       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7102     else
7103       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7104     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7105   }
7106   case AArch64CC::EQ:
7107     if (IsZero)
7108       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7109     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7110   case AArch64CC::GE:
7111     if (IsZero)
7112       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7113     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7114   case AArch64CC::GT:
7115     if (IsZero)
7116       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7117     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7118   case AArch64CC::LE:
7119     if (IsZero)
7120       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7121     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7122   case AArch64CC::LS:
7123     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7124   case AArch64CC::LO:
7125     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7126   case AArch64CC::LT:
7127     if (IsZero)
7128       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7129     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7130   case AArch64CC::HI:
7131     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7132   case AArch64CC::HS:
7133     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7134   }
7135 }
7136
7137 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7138                                            SelectionDAG &DAG) const {
7139   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7140   SDValue LHS = Op.getOperand(0);
7141   SDValue RHS = Op.getOperand(1);
7142   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7143   SDLoc dl(Op);
7144
7145   if (LHS.getValueType().getVectorElementType().isInteger()) {
7146     assert(LHS.getValueType() == RHS.getValueType());
7147     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7148     SDValue Cmp =
7149         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7150     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7151   }
7152
7153   if (LHS.getValueType().getVectorElementType() == MVT::f16)
7154     return SDValue();
7155
7156   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7157          LHS.getValueType().getVectorElementType() == MVT::f64);
7158
7159   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7160   // clean.  Some of them require two branches to implement.
7161   AArch64CC::CondCode CC1, CC2;
7162   bool ShouldInvert;
7163   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7164
7165   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7166   SDValue Cmp =
7167       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7168   if (!Cmp.getNode())
7169     return SDValue();
7170
7171   if (CC2 != AArch64CC::AL) {
7172     SDValue Cmp2 =
7173         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7174     if (!Cmp2.getNode())
7175       return SDValue();
7176
7177     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7178   }
7179
7180   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7181
7182   if (ShouldInvert)
7183     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7184
7185   return Cmp;
7186 }
7187
7188 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7189                                   SelectionDAG &DAG) {
7190   SDValue VecOp = ScalarOp.getOperand(0);
7191   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7192   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7193                      DAG.getConstant(0, DL, MVT::i64));
7194 }
7195
7196 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7197                                               SelectionDAG &DAG) const {
7198   SDLoc dl(Op);
7199   switch (Op.getOpcode()) {
7200   case ISD::VECREDUCE_ADD:
7201     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7202   case ISD::VECREDUCE_SMAX:
7203     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7204   case ISD::VECREDUCE_SMIN:
7205     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7206   case ISD::VECREDUCE_UMAX:
7207     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7208   case ISD::VECREDUCE_UMIN:
7209     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7210   case ISD::VECREDUCE_FMAX: {
7211     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7212     return DAG.getNode(
7213         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7214         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7215         Op.getOperand(0));
7216   }
7217   case ISD::VECREDUCE_FMIN: {
7218     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7219     return DAG.getNode(
7220         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7221         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7222         Op.getOperand(0));
7223   }
7224   default:
7225     llvm_unreachable("Unhandled reduction");
7226   }
7227 }
7228
7229 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7230 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7231 /// specified in the intrinsic calls.
7232 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7233                                                const CallInst &I,
7234                                                unsigned Intrinsic) const {
7235   auto &DL = I.getModule()->getDataLayout();
7236   switch (Intrinsic) {
7237   case Intrinsic::aarch64_neon_ld2:
7238   case Intrinsic::aarch64_neon_ld3:
7239   case Intrinsic::aarch64_neon_ld4:
7240   case Intrinsic::aarch64_neon_ld1x2:
7241   case Intrinsic::aarch64_neon_ld1x3:
7242   case Intrinsic::aarch64_neon_ld1x4:
7243   case Intrinsic::aarch64_neon_ld2lane:
7244   case Intrinsic::aarch64_neon_ld3lane:
7245   case Intrinsic::aarch64_neon_ld4lane:
7246   case Intrinsic::aarch64_neon_ld2r:
7247   case Intrinsic::aarch64_neon_ld3r:
7248   case Intrinsic::aarch64_neon_ld4r: {
7249     Info.opc = ISD::INTRINSIC_W_CHAIN;
7250     // Conservatively set memVT to the entire set of vectors loaded.
7251     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7252     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7253     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7254     Info.offset = 0;
7255     Info.align = 0;
7256     Info.vol = false; // volatile loads with NEON intrinsics not supported
7257     Info.readMem = true;
7258     Info.writeMem = false;
7259     return true;
7260   }
7261   case Intrinsic::aarch64_neon_st2:
7262   case Intrinsic::aarch64_neon_st3:
7263   case Intrinsic::aarch64_neon_st4:
7264   case Intrinsic::aarch64_neon_st1x2:
7265   case Intrinsic::aarch64_neon_st1x3:
7266   case Intrinsic::aarch64_neon_st1x4:
7267   case Intrinsic::aarch64_neon_st2lane:
7268   case Intrinsic::aarch64_neon_st3lane:
7269   case Intrinsic::aarch64_neon_st4lane: {
7270     Info.opc = ISD::INTRINSIC_VOID;
7271     // Conservatively set memVT to the entire set of vectors stored.
7272     unsigned NumElts = 0;
7273     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7274       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7275       if (!ArgTy->isVectorTy())
7276         break;
7277       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7278     }
7279     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7280     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7281     Info.offset = 0;
7282     Info.align = 0;
7283     Info.vol = false; // volatile stores with NEON intrinsics not supported
7284     Info.readMem = false;
7285     Info.writeMem = true;
7286     return true;
7287   }
7288   case Intrinsic::aarch64_ldaxr:
7289   case Intrinsic::aarch64_ldxr: {
7290     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7291     Info.opc = ISD::INTRINSIC_W_CHAIN;
7292     Info.memVT = MVT::getVT(PtrTy->getElementType());
7293     Info.ptrVal = I.getArgOperand(0);
7294     Info.offset = 0;
7295     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7296     Info.vol = true;
7297     Info.readMem = true;
7298     Info.writeMem = false;
7299     return true;
7300   }
7301   case Intrinsic::aarch64_stlxr:
7302   case Intrinsic::aarch64_stxr: {
7303     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7304     Info.opc = ISD::INTRINSIC_W_CHAIN;
7305     Info.memVT = MVT::getVT(PtrTy->getElementType());
7306     Info.ptrVal = I.getArgOperand(1);
7307     Info.offset = 0;
7308     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7309     Info.vol = true;
7310     Info.readMem = false;
7311     Info.writeMem = true;
7312     return true;
7313   }
7314   case Intrinsic::aarch64_ldaxp:
7315   case Intrinsic::aarch64_ldxp:
7316     Info.opc = ISD::INTRINSIC_W_CHAIN;
7317     Info.memVT = MVT::i128;
7318     Info.ptrVal = I.getArgOperand(0);
7319     Info.offset = 0;
7320     Info.align = 16;
7321     Info.vol = true;
7322     Info.readMem = true;
7323     Info.writeMem = false;
7324     return true;
7325   case Intrinsic::aarch64_stlxp:
7326   case Intrinsic::aarch64_stxp:
7327     Info.opc = ISD::INTRINSIC_W_CHAIN;
7328     Info.memVT = MVT::i128;
7329     Info.ptrVal = I.getArgOperand(2);
7330     Info.offset = 0;
7331     Info.align = 16;
7332     Info.vol = true;
7333     Info.readMem = false;
7334     Info.writeMem = true;
7335     return true;
7336   default:
7337     break;
7338   }
7339
7340   return false;
7341 }
7342
7343 // Truncations from 64-bit GPR to 32-bit GPR is free.
7344 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7345   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7346     return false;
7347   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7348   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7349   return NumBits1 > NumBits2;
7350 }
7351 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7352   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7353     return false;
7354   unsigned NumBits1 = VT1.getSizeInBits();
7355   unsigned NumBits2 = VT2.getSizeInBits();
7356   return NumBits1 > NumBits2;
7357 }
7358
7359 /// Check if it is profitable to hoist instruction in then/else to if.
7360 /// Not profitable if I and it's user can form a FMA instruction
7361 /// because we prefer FMSUB/FMADD.
7362 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7363   if (I->getOpcode() != Instruction::FMul)
7364     return true;
7365
7366   if (!I->hasOneUse())
7367     return true;
7368
7369   Instruction *User = I->user_back();
7370
7371   if (User &&
7372       !(User->getOpcode() == Instruction::FSub ||
7373         User->getOpcode() == Instruction::FAdd))
7374     return true;
7375
7376   const TargetOptions &Options = getTargetMachine().Options;
7377   const DataLayout &DL = I->getModule()->getDataLayout();
7378   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7379
7380   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7381            isOperationLegalOrCustom(ISD::FMA, VT) &&
7382            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7383             Options.UnsafeFPMath));
7384 }
7385
7386 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7387 // 64-bit GPR.
7388 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7389   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7390     return false;
7391   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7392   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7393   return NumBits1 == 32 && NumBits2 == 64;
7394 }
7395 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7396   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7397     return false;
7398   unsigned NumBits1 = VT1.getSizeInBits();
7399   unsigned NumBits2 = VT2.getSizeInBits();
7400   return NumBits1 == 32 && NumBits2 == 64;
7401 }
7402
7403 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7404   EVT VT1 = Val.getValueType();
7405   if (isZExtFree(VT1, VT2)) {
7406     return true;
7407   }
7408
7409   if (Val.getOpcode() != ISD::LOAD)
7410     return false;
7411
7412   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7413   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7414           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7415           VT1.getSizeInBits() <= 32);
7416 }
7417
7418 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7419   if (isa<FPExtInst>(Ext))
7420     return false;
7421
7422   // Vector types are next free.
7423   if (Ext->getType()->isVectorTy())
7424     return false;
7425
7426   for (const Use &U : Ext->uses()) {
7427     // The extension is free if we can fold it with a left shift in an
7428     // addressing mode or an arithmetic operation: add, sub, and cmp.
7429
7430     // Is there a shift?
7431     const Instruction *Instr = cast<Instruction>(U.getUser());
7432
7433     // Is this a constant shift?
7434     switch (Instr->getOpcode()) {
7435     case Instruction::Shl:
7436       if (!isa<ConstantInt>(Instr->getOperand(1)))
7437         return false;
7438       break;
7439     case Instruction::GetElementPtr: {
7440       gep_type_iterator GTI = gep_type_begin(Instr);
7441       auto &DL = Ext->getModule()->getDataLayout();
7442       std::advance(GTI, U.getOperandNo()-1);
7443       Type *IdxTy = GTI.getIndexedType();
7444       // This extension will end up with a shift because of the scaling factor.
7445       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7446       // Get the shift amount based on the scaling factor:
7447       // log2(sizeof(IdxTy)) - log2(8).
7448       uint64_t ShiftAmt =
7449           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7450       // Is the constant foldable in the shift of the addressing mode?
7451       // I.e., shift amount is between 1 and 4 inclusive.
7452       if (ShiftAmt == 0 || ShiftAmt > 4)
7453         return false;
7454       break;
7455     }
7456     case Instruction::Trunc:
7457       // Check if this is a noop.
7458       // trunc(sext ty1 to ty2) to ty1.
7459       if (Instr->getType() == Ext->getOperand(0)->getType())
7460         continue;
7461       LLVM_FALLTHROUGH;
7462     default:
7463       return false;
7464     }
7465
7466     // At this point we can use the bfm family, so this extension is free
7467     // for that use.
7468   }
7469   return true;
7470 }
7471
7472 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7473                                           unsigned &RequiredAligment) const {
7474   if (!LoadedType.isSimple() ||
7475       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7476     return false;
7477   // Cyclone supports unaligned accesses.
7478   RequiredAligment = 0;
7479   unsigned NumBits = LoadedType.getSizeInBits();
7480   return NumBits == 32 || NumBits == 64;
7481 }
7482
7483 /// A helper function for determining the number of interleaved accesses we
7484 /// will generate when lowering accesses of the given type.
7485 unsigned
7486 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7487                                                  const DataLayout &DL) const {
7488   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7489 }
7490
7491 MachineMemOperand::Flags
7492 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7493   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7494       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7495     return MOStridedAccess;
7496   return MachineMemOperand::MONone;
7497 }
7498
7499 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7500     VectorType *VecTy, const DataLayout &DL) const {
7501
7502   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7503   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7504
7505   // Ensure the number of vector elements is greater than 1.
7506   if (VecTy->getNumElements() < 2)
7507     return false;
7508
7509   // Ensure the element type is legal.
7510   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7511     return false;
7512
7513   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7514   // 128 will be split into multiple interleaved accesses.
7515   return VecSize == 64 || VecSize % 128 == 0;
7516 }
7517
7518 /// \brief Lower an interleaved load into a ldN intrinsic.
7519 ///
7520 /// E.g. Lower an interleaved load (Factor = 2):
7521 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7522 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7523 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7524 ///
7525 ///      Into:
7526 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7527 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7528 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7529 bool AArch64TargetLowering::lowerInterleavedLoad(
7530     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7531     ArrayRef<unsigned> Indices, unsigned Factor) const {
7532   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7533          "Invalid interleave factor");
7534   assert(!Shuffles.empty() && "Empty shufflevector input");
7535   assert(Shuffles.size() == Indices.size() &&
7536          "Unmatched number of shufflevectors and indices");
7537
7538   const DataLayout &DL = LI->getModule()->getDataLayout();
7539
7540   VectorType *VecTy = Shuffles[0]->getType();
7541
7542   // Skip if we do not have NEON and skip illegal vector types. We can
7543   // "legalize" wide vector types into multiple interleaved accesses as long as
7544   // the vector types are divisible by 128.
7545   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7546     return false;
7547
7548   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7549
7550   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7551   // load integer vectors first and then convert to pointer vectors.
7552   Type *EltTy = VecTy->getVectorElementType();
7553   if (EltTy->isPointerTy())
7554     VecTy =
7555         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7556
7557   IRBuilder<> Builder(LI);
7558
7559   // The base address of the load.
7560   Value *BaseAddr = LI->getPointerOperand();
7561
7562   if (NumLoads > 1) {
7563     // If we're going to generate more than one load, reset the sub-vector type
7564     // to something legal.
7565     VecTy = VectorType::get(VecTy->getVectorElementType(),
7566                             VecTy->getVectorNumElements() / NumLoads);
7567
7568     // We will compute the pointer operand of each load from the original base
7569     // address using GEPs. Cast the base address to a pointer to the scalar
7570     // element type.
7571     BaseAddr = Builder.CreateBitCast(
7572         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7573                       LI->getPointerAddressSpace()));
7574   }
7575
7576   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7577   Type *Tys[2] = {VecTy, PtrTy};
7578   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7579                                             Intrinsic::aarch64_neon_ld3,
7580                                             Intrinsic::aarch64_neon_ld4};
7581   Function *LdNFunc =
7582       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7583
7584   // Holds sub-vectors extracted from the load intrinsic return values. The
7585   // sub-vectors are associated with the shufflevector instructions they will
7586   // replace.
7587   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7588
7589   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7590
7591     // If we're generating more than one load, compute the base address of
7592     // subsequent loads as an offset from the previous.
7593     if (LoadCount > 0)
7594       BaseAddr = Builder.CreateConstGEP1_32(
7595           BaseAddr, VecTy->getVectorNumElements() * Factor);
7596
7597     CallInst *LdN = Builder.CreateCall(
7598         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7599
7600     // Extract and store the sub-vectors returned by the load intrinsic.
7601     for (unsigned i = 0; i < Shuffles.size(); i++) {
7602       ShuffleVectorInst *SVI = Shuffles[i];
7603       unsigned Index = Indices[i];
7604
7605       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7606
7607       // Convert the integer vector to pointer vector if the element is pointer.
7608       if (EltTy->isPointerTy())
7609         SubVec = Builder.CreateIntToPtr(
7610             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7611                                     VecTy->getVectorNumElements()));
7612       SubVecs[SVI].push_back(SubVec);
7613     }
7614   }
7615
7616   // Replace uses of the shufflevector instructions with the sub-vectors
7617   // returned by the load intrinsic. If a shufflevector instruction is
7618   // associated with more than one sub-vector, those sub-vectors will be
7619   // concatenated into a single wide vector.
7620   for (ShuffleVectorInst *SVI : Shuffles) {
7621     auto &SubVec = SubVecs[SVI];
7622     auto *WideVec =
7623         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7624     SVI->replaceAllUsesWith(WideVec);
7625   }
7626
7627   return true;
7628 }
7629
7630 /// \brief Lower an interleaved store into a stN intrinsic.
7631 ///
7632 /// E.g. Lower an interleaved store (Factor = 3):
7633 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7634 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7635 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7636 ///
7637 ///      Into:
7638 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7639 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7640 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7641 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7642 ///
7643 /// Note that the new shufflevectors will be removed and we'll only generate one
7644 /// st3 instruction in CodeGen.
7645 ///
7646 /// Example for a more general valid mask (Factor 3). Lower:
7647 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7648 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7649 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7650 ///
7651 ///      Into:
7652 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7653 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7654 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7655 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7656 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7657                                                   ShuffleVectorInst *SVI,
7658                                                   unsigned Factor) const {
7659   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7660          "Invalid interleave factor");
7661
7662   VectorType *VecTy = SVI->getType();
7663   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7664          "Invalid interleaved store");
7665
7666   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7667   Type *EltTy = VecTy->getVectorElementType();
7668   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7669
7670   const DataLayout &DL = SI->getModule()->getDataLayout();
7671
7672   // Skip if we do not have NEON and skip illegal vector types. We can
7673   // "legalize" wide vector types into multiple interleaved accesses as long as
7674   // the vector types are divisible by 128.
7675   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7676     return false;
7677
7678   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7679
7680   Value *Op0 = SVI->getOperand(0);
7681   Value *Op1 = SVI->getOperand(1);
7682   IRBuilder<> Builder(SI);
7683
7684   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7685   // vectors to integer vectors.
7686   if (EltTy->isPointerTy()) {
7687     Type *IntTy = DL.getIntPtrType(EltTy);
7688     unsigned NumOpElts =
7689         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7690
7691     // Convert to the corresponding integer vector.
7692     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7693     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7694     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7695
7696     SubVecTy = VectorType::get(IntTy, LaneLen);
7697   }
7698
7699   // The base address of the store.
7700   Value *BaseAddr = SI->getPointerOperand();
7701
7702   if (NumStores > 1) {
7703     // If we're going to generate more than one store, reset the lane length
7704     // and sub-vector type to something legal.
7705     LaneLen /= NumStores;
7706     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7707
7708     // We will compute the pointer operand of each store from the original base
7709     // address using GEPs. Cast the base address to a pointer to the scalar
7710     // element type.
7711     BaseAddr = Builder.CreateBitCast(
7712         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7713                       SI->getPointerAddressSpace()));
7714   }
7715
7716   auto Mask = SVI->getShuffleMask();
7717
7718   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7719   Type *Tys[2] = {SubVecTy, PtrTy};
7720   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7721                                              Intrinsic::aarch64_neon_st3,
7722                                              Intrinsic::aarch64_neon_st4};
7723   Function *StNFunc =
7724       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7725
7726   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7727
7728     SmallVector<Value *, 5> Ops;
7729
7730     // Split the shufflevector operands into sub vectors for the new stN call.
7731     for (unsigned i = 0; i < Factor; i++) {
7732       unsigned IdxI = StoreCount * LaneLen * Factor + i;
7733       if (Mask[IdxI] >= 0) {
7734         Ops.push_back(Builder.CreateShuffleVector(
7735             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7736       } else {
7737         unsigned StartMask = 0;
7738         for (unsigned j = 1; j < LaneLen; j++) {
7739           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7740           if (Mask[IdxJ * Factor + IdxI] >= 0) {
7741             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7742             break;
7743           }
7744         }
7745         // Note: Filling undef gaps with random elements is ok, since
7746         // those elements were being written anyway (with undefs).
7747         // In the case of all undefs we're defaulting to using elems from 0
7748         // Note: StartMask cannot be negative, it's checked in
7749         // isReInterleaveMask
7750         Ops.push_back(Builder.CreateShuffleVector(
7751             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7752       }
7753     }
7754
7755     // If we generating more than one store, we compute the base address of
7756     // subsequent stores as an offset from the previous.
7757     if (StoreCount > 0)
7758       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7759
7760     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7761     Builder.CreateCall(StNFunc, Ops);
7762   }
7763   return true;
7764 }
7765
7766 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7767                        unsigned AlignCheck) {
7768   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7769           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7770 }
7771
7772 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7773                                                unsigned SrcAlign, bool IsMemset,
7774                                                bool ZeroMemset,
7775                                                bool MemcpyStrSrc,
7776                                                MachineFunction &MF) const {
7777   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7778   // instruction to materialize the v2i64 zero and one store (with restrictive
7779   // addressing mode). Just do two i64 store of zero-registers.
7780   bool Fast;
7781   const Function *F = MF.getFunction();
7782   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7783       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7784       (memOpAlign(SrcAlign, DstAlign, 16) ||
7785        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7786     return MVT::f128;
7787
7788   if (Size >= 8 &&
7789       (memOpAlign(SrcAlign, DstAlign, 8) ||
7790        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7791     return MVT::i64;
7792
7793   if (Size >= 4 &&
7794       (memOpAlign(SrcAlign, DstAlign, 4) ||
7795        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7796     return MVT::i32;
7797
7798   return MVT::Other;
7799 }
7800
7801 // 12-bit optionally shifted immediates are legal for adds.
7802 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7803   // Avoid UB for INT64_MIN.
7804   if (Immed == std::numeric_limits<int64_t>::min())
7805     return false;
7806   // Same encoding for add/sub, just flip the sign.
7807   Immed = std::abs(Immed);
7808   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7809 }
7810
7811 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7812 // immediates is the same as for an add or a sub.
7813 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7814   return isLegalAddImmediate(Immed);
7815 }
7816
7817 /// isLegalAddressingMode - Return true if the addressing mode represented
7818 /// by AM is legal for this target, for a load/store of the specified type.
7819 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7820                                                   const AddrMode &AM, Type *Ty,
7821                                                   unsigned AS) const {
7822   // AArch64 has five basic addressing modes:
7823   //  reg
7824   //  reg + 9-bit signed offset
7825   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7826   //  reg1 + reg2
7827   //  reg + SIZE_IN_BYTES * reg
7828
7829   // No global is ever allowed as a base.
7830   if (AM.BaseGV)
7831     return false;
7832
7833   // No reg+reg+imm addressing.
7834   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7835     return false;
7836
7837   // check reg + imm case:
7838   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7839   uint64_t NumBytes = 0;
7840   if (Ty->isSized()) {
7841     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7842     NumBytes = NumBits / 8;
7843     if (!isPowerOf2_64(NumBits))
7844       NumBytes = 0;
7845   }
7846
7847   if (!AM.Scale) {
7848     int64_t Offset = AM.BaseOffs;
7849
7850     // 9-bit signed offset
7851     if (isInt<9>(Offset))
7852       return true;
7853
7854     // 12-bit unsigned offset
7855     unsigned shift = Log2_64(NumBytes);
7856     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7857         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7858         (Offset >> shift) << shift == Offset)
7859       return true;
7860     return false;
7861   }
7862
7863   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7864
7865   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7866 }
7867
7868 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7869                                                 const AddrMode &AM, Type *Ty,
7870                                                 unsigned AS) const {
7871   // Scaling factors are not free at all.
7872   // Operands                     | Rt Latency
7873   // -------------------------------------------
7874   // Rt, [Xn, Xm]                 | 4
7875   // -------------------------------------------
7876   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7877   // Rt, [Xn, Wm, <extend> #imm]  |
7878   if (isLegalAddressingMode(DL, AM, Ty, AS))
7879     // Scale represents reg2 * scale, thus account for 1 if
7880     // it is not equal to 0 or 1.
7881     return AM.Scale != 0 && AM.Scale != 1;
7882   return -1;
7883 }
7884
7885 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7886   VT = VT.getScalarType();
7887
7888   if (!VT.isSimple())
7889     return false;
7890
7891   switch (VT.getSimpleVT().SimpleTy) {
7892   case MVT::f32:
7893   case MVT::f64:
7894     return true;
7895   default:
7896     break;
7897   }
7898
7899   return false;
7900 }
7901
7902 const MCPhysReg *
7903 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7904   // LR is a callee-save register, but we must treat it as clobbered by any call
7905   // site. Hence we include LR in the scratch registers, which are in turn added
7906   // as implicit-defs for stackmaps and patchpoints.
7907   static const MCPhysReg ScratchRegs[] = {
7908     AArch64::X16, AArch64::X17, AArch64::LR, 0
7909   };
7910   return ScratchRegs;
7911 }
7912
7913 bool
7914 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7915   EVT VT = N->getValueType(0);
7916     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7917     // it with shift to let it be lowered to UBFX.
7918   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7919       isa<ConstantSDNode>(N->getOperand(1))) {
7920     uint64_t TruncMask = N->getConstantOperandVal(1);
7921     if (isMask_64(TruncMask) &&
7922       N->getOperand(0).getOpcode() == ISD::SRL &&
7923       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7924       return false;
7925   }
7926   return true;
7927 }
7928
7929 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7930                                                               Type *Ty) const {
7931   assert(Ty->isIntegerTy());
7932
7933   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7934   if (BitSize == 0)
7935     return false;
7936
7937   int64_t Val = Imm.getSExtValue();
7938   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7939     return true;
7940
7941   if ((int64_t)Val < 0)
7942     Val = ~Val;
7943   if (BitSize == 32)
7944     Val &= (1LL << 32) - 1;
7945
7946   unsigned LZ = countLeadingZeros((uint64_t)Val);
7947   unsigned Shift = (63 - LZ) / 16;
7948   // MOVZ is free so return true for one or fewer MOVK.
7949   return Shift < 3;
7950 }
7951
7952 /// Turn vector tests of the signbit in the form of:
7953 ///   xor (sra X, elt_size(X)-1), -1
7954 /// into:
7955 ///   cmge X, X, #0
7956 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7957                                          const AArch64Subtarget *Subtarget) {
7958   EVT VT = N->getValueType(0);
7959   if (!Subtarget->hasNEON() || !VT.isVector())
7960     return SDValue();
7961
7962   // There must be a shift right algebraic before the xor, and the xor must be a
7963   // 'not' operation.
7964   SDValue Shift = N->getOperand(0);
7965   SDValue Ones = N->getOperand(1);
7966   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7967       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7968     return SDValue();
7969
7970   // The shift should be smearing the sign bit across each vector element.
7971   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7972   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7973   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7974     return SDValue();
7975
7976   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7977 }
7978
7979 // Generate SUBS and CSEL for integer abs.
7980 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7981   EVT VT = N->getValueType(0);
7982
7983   SDValue N0 = N->getOperand(0);
7984   SDValue N1 = N->getOperand(1);
7985   SDLoc DL(N);
7986
7987   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7988   // and change it to SUB and CSEL.
7989   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7990       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7991       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7992     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7993       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7994         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7995                                   N0.getOperand(0));
7996         // Generate SUBS & CSEL.
7997         SDValue Cmp =
7998             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7999                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
8000         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8001                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8002                            SDValue(Cmp.getNode(), 1));
8003       }
8004   return SDValue();
8005 }
8006
8007 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8008                                  TargetLowering::DAGCombinerInfo &DCI,
8009                                  const AArch64Subtarget *Subtarget) {
8010   if (DCI.isBeforeLegalizeOps())
8011     return SDValue();
8012
8013   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8014     return Cmp;
8015
8016   return performIntegerAbsCombine(N, DAG);
8017 }
8018
8019 SDValue
8020 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8021                                      SelectionDAG &DAG,
8022                                      std::vector<SDNode *> *Created) const {
8023   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
8024   if (isIntDivCheap(N->getValueType(0), Attr))
8025     return SDValue(N,0); // Lower SDIV as SDIV
8026
8027   // fold (sdiv X, pow2)
8028   EVT VT = N->getValueType(0);
8029   if ((VT != MVT::i32 && VT != MVT::i64) ||
8030       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8031     return SDValue();
8032
8033   SDLoc DL(N);
8034   SDValue N0 = N->getOperand(0);
8035   unsigned Lg2 = Divisor.countTrailingZeros();
8036   SDValue Zero = DAG.getConstant(0, DL, VT);
8037   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8038
8039   // Add (N0 < 0) ? Pow2 - 1 : 0;
8040   SDValue CCVal;
8041   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8042   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8043   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8044
8045   if (Created) {
8046     Created->push_back(Cmp.getNode());
8047     Created->push_back(Add.getNode());
8048     Created->push_back(CSel.getNode());
8049   }
8050
8051   // Divide by pow2.
8052   SDValue SRA =
8053       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8054
8055   // If we're dividing by a positive value, we're done.  Otherwise, we must
8056   // negate the result.
8057   if (Divisor.isNonNegative())
8058     return SRA;
8059
8060   if (Created)
8061     Created->push_back(SRA.getNode());
8062   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8063 }
8064
8065 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8066                                  TargetLowering::DAGCombinerInfo &DCI,
8067                                  const AArch64Subtarget *Subtarget) {
8068   if (DCI.isBeforeLegalizeOps())
8069     return SDValue();
8070
8071   // The below optimizations require a constant RHS.
8072   if (!isa<ConstantSDNode>(N->getOperand(1)))
8073     return SDValue();
8074
8075   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8076   const APInt &ConstValue = C->getAPIntValue();
8077
8078   // Multiplication of a power of two plus/minus one can be done more
8079   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8080   // future CPUs have a cheaper MADD instruction, this may need to be
8081   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8082   // 64-bit is 5 cycles, so this is always a win.
8083   // More aggressively, some multiplications N0 * C can be lowered to
8084   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8085   // e.g. 6=3*2=(2+1)*2.
8086   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8087   // which equals to (1+2)*16-(1+2).
8088   SDValue N0 = N->getOperand(0);
8089   // TrailingZeroes is used to test if the mul can be lowered to
8090   // shift+add+shift.
8091   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8092   if (TrailingZeroes) {
8093     // Conservatively do not lower to shift+add+shift if the mul might be
8094     // folded into smul or umul.
8095     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8096                             isZeroExtended(N0.getNode(), DAG)))
8097       return SDValue();
8098     // Conservatively do not lower to shift+add+shift if the mul might be
8099     // folded into madd or msub.
8100     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8101                            N->use_begin()->getOpcode() == ISD::SUB))
8102       return SDValue();
8103   }
8104   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8105   // and shift+add+shift.
8106   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8107
8108   unsigned ShiftAmt, AddSubOpc;
8109   // Is the shifted value the LHS operand of the add/sub?
8110   bool ShiftValUseIsN0 = true;
8111   // Do we need to negate the result?
8112   bool NegateResult = false;
8113
8114   if (ConstValue.isNonNegative()) {
8115     // (mul x, 2^N + 1) => (add (shl x, N), x)
8116     // (mul x, 2^N - 1) => (sub (shl x, N), x)
8117     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8118     APInt SCVMinus1 = ShiftedConstValue - 1;
8119     APInt CVPlus1 = ConstValue + 1;
8120     if (SCVMinus1.isPowerOf2()) {
8121       ShiftAmt = SCVMinus1.logBase2();
8122       AddSubOpc = ISD::ADD;
8123     } else if (CVPlus1.isPowerOf2()) {
8124       ShiftAmt = CVPlus1.logBase2();
8125       AddSubOpc = ISD::SUB;
8126     } else
8127       return SDValue();
8128   } else {
8129     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8130     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8131     APInt CVNegPlus1 = -ConstValue + 1;
8132     APInt CVNegMinus1 = -ConstValue - 1;
8133     if (CVNegPlus1.isPowerOf2()) {
8134       ShiftAmt = CVNegPlus1.logBase2();
8135       AddSubOpc = ISD::SUB;
8136       ShiftValUseIsN0 = false;
8137     } else if (CVNegMinus1.isPowerOf2()) {
8138       ShiftAmt = CVNegMinus1.logBase2();
8139       AddSubOpc = ISD::ADD;
8140       NegateResult = true;
8141     } else
8142       return SDValue();
8143   }
8144
8145   SDLoc DL(N);
8146   EVT VT = N->getValueType(0);
8147   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8148                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
8149
8150   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8151   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8152   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8153   assert(!(NegateResult && TrailingZeroes) &&
8154          "NegateResult and TrailingZeroes cannot both be true for now.");
8155   // Negate the result.
8156   if (NegateResult)
8157     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8158   // Shift the result.
8159   if (TrailingZeroes)
8160     return DAG.getNode(ISD::SHL, DL, VT, Res,
8161                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8162   return Res;
8163 }
8164
8165 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8166                                                          SelectionDAG &DAG) {
8167   // Take advantage of vector comparisons producing 0 or -1 in each lane to
8168   // optimize away operation when it's from a constant.
8169   //
8170   // The general transformation is:
8171   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8172   //       AND(VECTOR_CMP(x,y), constant2)
8173   //    constant2 = UNARYOP(constant)
8174
8175   // Early exit if this isn't a vector operation, the operand of the
8176   // unary operation isn't a bitwise AND, or if the sizes of the operations
8177   // aren't the same.
8178   EVT VT = N->getValueType(0);
8179   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8180       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8181       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8182     return SDValue();
8183
8184   // Now check that the other operand of the AND is a constant. We could
8185   // make the transformation for non-constant splats as well, but it's unclear
8186   // that would be a benefit as it would not eliminate any operations, just
8187   // perform one more step in scalar code before moving to the vector unit.
8188   if (BuildVectorSDNode *BV =
8189           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8190     // Bail out if the vector isn't a constant.
8191     if (!BV->isConstant())
8192       return SDValue();
8193
8194     // Everything checks out. Build up the new and improved node.
8195     SDLoc DL(N);
8196     EVT IntVT = BV->getValueType(0);
8197     // Create a new constant of the appropriate type for the transformed
8198     // DAG.
8199     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8200     // The AND node needs bitcasts to/from an integer vector type around it.
8201     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8202     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8203                                  N->getOperand(0)->getOperand(0), MaskConst);
8204     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8205     return Res;
8206   }
8207
8208   return SDValue();
8209 }
8210
8211 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8212                                      const AArch64Subtarget *Subtarget) {
8213   // First try to optimize away the conversion when it's conditionally from
8214   // a constant. Vectors only.
8215   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8216     return Res;
8217
8218   EVT VT = N->getValueType(0);
8219   if (VT != MVT::f32 && VT != MVT::f64)
8220     return SDValue();
8221
8222   // Only optimize when the source and destination types have the same width.
8223   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8224     return SDValue();
8225
8226   // If the result of an integer load is only used by an integer-to-float
8227   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8228   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8229   SDValue N0 = N->getOperand(0);
8230   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8231       // Do not change the width of a volatile load.
8232       !cast<LoadSDNode>(N0)->isVolatile()) {
8233     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8234     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8235                                LN0->getPointerInfo(), LN0->getAlignment(),
8236                                LN0->getMemOperand()->getFlags());
8237
8238     // Make sure successors of the original load stay after it by updating them
8239     // to use the new Chain.
8240     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8241
8242     unsigned Opcode =
8243         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8244     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8245   }
8246
8247   return SDValue();
8248 }
8249
8250 /// Fold a floating-point multiply by power of two into floating-point to
8251 /// fixed-point conversion.
8252 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8253                                      TargetLowering::DAGCombinerInfo &DCI,
8254                                      const AArch64Subtarget *Subtarget) {
8255   if (!Subtarget->hasNEON())
8256     return SDValue();
8257
8258   SDValue Op = N->getOperand(0);
8259   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8260       Op.getOpcode() != ISD::FMUL)
8261     return SDValue();
8262
8263   SDValue ConstVec = Op->getOperand(1);
8264   if (!isa<BuildVectorSDNode>(ConstVec))
8265     return SDValue();
8266
8267   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8268   uint32_t FloatBits = FloatTy.getSizeInBits();
8269   if (FloatBits != 32 && FloatBits != 64)
8270     return SDValue();
8271
8272   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8273   uint32_t IntBits = IntTy.getSizeInBits();
8274   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8275     return SDValue();
8276
8277   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8278   if (IntBits > FloatBits)
8279     return SDValue();
8280
8281   BitVector UndefElements;
8282   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8283   int32_t Bits = IntBits == 64 ? 64 : 32;
8284   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8285   if (C == -1 || C == 0 || C > Bits)
8286     return SDValue();
8287
8288   MVT ResTy;
8289   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8290   switch (NumLanes) {
8291   default:
8292     return SDValue();
8293   case 2:
8294     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8295     break;
8296   case 4:
8297     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8298     break;
8299   }
8300
8301   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8302     return SDValue();
8303
8304   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8305          "Illegal vector type after legalization");
8306
8307   SDLoc DL(N);
8308   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8309   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8310                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
8311   SDValue FixConv =
8312       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8313                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8314                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8315   // We can handle smaller integers by generating an extra trunc.
8316   if (IntBits < FloatBits)
8317     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8318
8319   return FixConv;
8320 }
8321
8322 /// Fold a floating-point divide by power of two into fixed-point to
8323 /// floating-point conversion.
8324 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8325                                   TargetLowering::DAGCombinerInfo &DCI,
8326                                   const AArch64Subtarget *Subtarget) {
8327   if (!Subtarget->hasNEON())
8328     return SDValue();
8329
8330   SDValue Op = N->getOperand(0);
8331   unsigned Opc = Op->getOpcode();
8332   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8333       !Op.getOperand(0).getValueType().isSimple() ||
8334       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8335     return SDValue();
8336
8337   SDValue ConstVec = N->getOperand(1);
8338   if (!isa<BuildVectorSDNode>(ConstVec))
8339     return SDValue();
8340
8341   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8342   int32_t IntBits = IntTy.getSizeInBits();
8343   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8344     return SDValue();
8345
8346   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8347   int32_t FloatBits = FloatTy.getSizeInBits();
8348   if (FloatBits != 32 && FloatBits != 64)
8349     return SDValue();
8350
8351   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8352   if (IntBits > FloatBits)
8353     return SDValue();
8354
8355   BitVector UndefElements;
8356   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8357   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8358   if (C == -1 || C == 0 || C > FloatBits)
8359     return SDValue();
8360
8361   MVT ResTy;
8362   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8363   switch (NumLanes) {
8364   default:
8365     return SDValue();
8366   case 2:
8367     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8368     break;
8369   case 4:
8370     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8371     break;
8372   }
8373
8374   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8375     return SDValue();
8376
8377   SDLoc DL(N);
8378   SDValue ConvInput = Op.getOperand(0);
8379   bool IsSigned = Opc == ISD::SINT_TO_FP;
8380   if (IntBits < FloatBits)
8381     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8382                             ResTy, ConvInput);
8383
8384   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8385                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
8386   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8387                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8388                      DAG.getConstant(C, DL, MVT::i32));
8389 }
8390
8391 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8392 /// searches for and classifies those shifts.
8393 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8394                          bool &FromHi) {
8395   if (N.getOpcode() == ISD::SHL)
8396     FromHi = false;
8397   else if (N.getOpcode() == ISD::SRL)
8398     FromHi = true;
8399   else
8400     return false;
8401
8402   if (!isa<ConstantSDNode>(N.getOperand(1)))
8403     return false;
8404
8405   ShiftAmount = N->getConstantOperandVal(1);
8406   Src = N->getOperand(0);
8407   return true;
8408 }
8409
8410 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8411 /// registers viewed as a high/low pair. This function looks for the pattern:
8412 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8413 /// with an EXTR. Can't quite be done in TableGen because the two immediates
8414 /// aren't independent.
8415 static SDValue tryCombineToEXTR(SDNode *N,
8416                                 TargetLowering::DAGCombinerInfo &DCI) {
8417   SelectionDAG &DAG = DCI.DAG;
8418   SDLoc DL(N);
8419   EVT VT = N->getValueType(0);
8420
8421   assert(N->getOpcode() == ISD::OR && "Unexpected root");
8422
8423   if (VT != MVT::i32 && VT != MVT::i64)
8424     return SDValue();
8425
8426   SDValue LHS;
8427   uint32_t ShiftLHS = 0;
8428   bool LHSFromHi = false;
8429   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8430     return SDValue();
8431
8432   SDValue RHS;
8433   uint32_t ShiftRHS = 0;
8434   bool RHSFromHi = false;
8435   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8436     return SDValue();
8437
8438   // If they're both trying to come from the high part of the register, they're
8439   // not really an EXTR.
8440   if (LHSFromHi == RHSFromHi)
8441     return SDValue();
8442
8443   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8444     return SDValue();
8445
8446   if (LHSFromHi) {
8447     std::swap(LHS, RHS);
8448     std::swap(ShiftLHS, ShiftRHS);
8449   }
8450
8451   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8452                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
8453 }
8454
8455 static SDValue tryCombineToBSL(SDNode *N,
8456                                 TargetLowering::DAGCombinerInfo &DCI) {
8457   EVT VT = N->getValueType(0);
8458   SelectionDAG &DAG = DCI.DAG;
8459   SDLoc DL(N);
8460
8461   if (!VT.isVector())
8462     return SDValue();
8463
8464   SDValue N0 = N->getOperand(0);
8465   if (N0.getOpcode() != ISD::AND)
8466     return SDValue();
8467
8468   SDValue N1 = N->getOperand(1);
8469   if (N1.getOpcode() != ISD::AND)
8470     return SDValue();
8471
8472   // We only have to look for constant vectors here since the general, variable
8473   // case can be handled in TableGen.
8474   unsigned Bits = VT.getScalarSizeInBits();
8475   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8476   for (int i = 1; i >= 0; --i)
8477     for (int j = 1; j >= 0; --j) {
8478       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8479       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8480       if (!BVN0 || !BVN1)
8481         continue;
8482
8483       bool FoundMatch = true;
8484       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8485         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8486         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8487         if (!CN0 || !CN1 ||
8488             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8489           FoundMatch = false;
8490           break;
8491         }
8492       }
8493
8494       if (FoundMatch)
8495         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8496                            N0->getOperand(1 - i), N1->getOperand(1 - j));
8497     }
8498
8499   return SDValue();
8500 }
8501
8502 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8503                                 const AArch64Subtarget *Subtarget) {
8504   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8505   SelectionDAG &DAG = DCI.DAG;
8506   EVT VT = N->getValueType(0);
8507
8508   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8509     return SDValue();
8510
8511   if (SDValue Res = tryCombineToEXTR(N, DCI))
8512     return Res;
8513
8514   if (SDValue Res = tryCombineToBSL(N, DCI))
8515     return Res;
8516
8517   return SDValue();
8518 }
8519
8520 static SDValue performSRLCombine(SDNode *N,
8521                                  TargetLowering::DAGCombinerInfo &DCI) {
8522   SelectionDAG &DAG = DCI.DAG;
8523   EVT VT = N->getValueType(0);
8524   if (VT != MVT::i32 && VT != MVT::i64)
8525     return SDValue();
8526
8527   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8528   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8529   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8530   SDValue N0 = N->getOperand(0);
8531   if (N0.getOpcode() == ISD::BSWAP) {
8532     SDLoc DL(N);
8533     SDValue N1 = N->getOperand(1);
8534     SDValue N00 = N0.getOperand(0);
8535     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8536       uint64_t ShiftAmt = C->getZExtValue();
8537       if (VT == MVT::i32 && ShiftAmt == 16 &&
8538           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8539         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8540       if (VT == MVT::i64 && ShiftAmt == 32 &&
8541           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8542         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8543     }
8544   }
8545   return SDValue();
8546 }
8547
8548 static SDValue performBitcastCombine(SDNode *N,
8549                                      TargetLowering::DAGCombinerInfo &DCI,
8550                                      SelectionDAG &DAG) {
8551   // Wait 'til after everything is legalized to try this. That way we have
8552   // legal vector types and such.
8553   if (DCI.isBeforeLegalizeOps())
8554     return SDValue();
8555
8556   // Remove extraneous bitcasts around an extract_subvector.
8557   // For example,
8558   //    (v4i16 (bitconvert
8559   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8560   //  becomes
8561   //    (extract_subvector ((v8i16 ...), (i64 4)))
8562
8563   // Only interested in 64-bit vectors as the ultimate result.
8564   EVT VT = N->getValueType(0);
8565   if (!VT.isVector())
8566     return SDValue();
8567   if (VT.getSimpleVT().getSizeInBits() != 64)
8568     return SDValue();
8569   // Is the operand an extract_subvector starting at the beginning or halfway
8570   // point of the vector? A low half may also come through as an
8571   // EXTRACT_SUBREG, so look for that, too.
8572   SDValue Op0 = N->getOperand(0);
8573   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8574       !(Op0->isMachineOpcode() &&
8575         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8576     return SDValue();
8577   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8578   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8579     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8580       return SDValue();
8581   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8582     if (idx != AArch64::dsub)
8583       return SDValue();
8584     // The dsub reference is equivalent to a lane zero subvector reference.
8585     idx = 0;
8586   }
8587   // Look through the bitcast of the input to the extract.
8588   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8589     return SDValue();
8590   SDValue Source = Op0->getOperand(0)->getOperand(0);
8591   // If the source type has twice the number of elements as our destination
8592   // type, we know this is an extract of the high or low half of the vector.
8593   EVT SVT = Source->getValueType(0);
8594   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8595     return SDValue();
8596
8597   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8598
8599   // Create the simplified form to just extract the low or high half of the
8600   // vector directly rather than bothering with the bitcasts.
8601   SDLoc dl(N);
8602   unsigned NumElements = VT.getVectorNumElements();
8603   if (idx) {
8604     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8605     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8606   } else {
8607     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8608     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8609                                       Source, SubReg),
8610                    0);
8611   }
8612 }
8613
8614 static SDValue performConcatVectorsCombine(SDNode *N,
8615                                            TargetLowering::DAGCombinerInfo &DCI,
8616                                            SelectionDAG &DAG) {
8617   SDLoc dl(N);
8618   EVT VT = N->getValueType(0);
8619   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8620
8621   // Optimize concat_vectors of truncated vectors, where the intermediate
8622   // type is illegal, to avoid said illegality,  e.g.,
8623   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8624   //                          (v2i16 (truncate (v2i64)))))
8625   // ->
8626   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8627   //                                    (v4i32 (bitcast (v2i64))),
8628   //                                    <0, 2, 4, 6>)))
8629   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8630   // on both input and result type, so we might generate worse code.
8631   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8632   if (N->getNumOperands() == 2 &&
8633       N0->getOpcode() == ISD::TRUNCATE &&
8634       N1->getOpcode() == ISD::TRUNCATE) {
8635     SDValue N00 = N0->getOperand(0);
8636     SDValue N10 = N1->getOperand(0);
8637     EVT N00VT = N00.getValueType();
8638
8639     if (N00VT == N10.getValueType() &&
8640         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8641         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8642       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8643       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8644       for (size_t i = 0; i < Mask.size(); ++i)
8645         Mask[i] = i * 2;
8646       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8647                          DAG.getVectorShuffle(
8648                              MidVT, dl,
8649                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8650                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8651     }
8652   }
8653
8654   // Wait 'til after everything is legalized to try this. That way we have
8655   // legal vector types and such.
8656   if (DCI.isBeforeLegalizeOps())
8657     return SDValue();
8658
8659   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8660   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8661   // canonicalise to that.
8662   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8663     assert(VT.getScalarSizeInBits() == 64);
8664     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8665                        DAG.getConstant(0, dl, MVT::i64));
8666   }
8667
8668   // Canonicalise concat_vectors so that the right-hand vector has as few
8669   // bit-casts as possible before its real operation. The primary matching
8670   // destination for these operations will be the narrowing "2" instructions,
8671   // which depend on the operation being performed on this right-hand vector.
8672   // For example,
8673   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8674   // becomes
8675   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8676
8677   if (N1->getOpcode() != ISD::BITCAST)
8678     return SDValue();
8679   SDValue RHS = N1->getOperand(0);
8680   MVT RHSTy = RHS.getValueType().getSimpleVT();
8681   // If the RHS is not a vector, this is not the pattern we're looking for.
8682   if (!RHSTy.isVector())
8683     return SDValue();
8684
8685   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8686
8687   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8688                                   RHSTy.getVectorNumElements() * 2);
8689   return DAG.getNode(ISD::BITCAST, dl, VT,
8690                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8691                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8692                                  RHS));
8693 }
8694
8695 static SDValue tryCombineFixedPointConvert(SDNode *N,
8696                                            TargetLowering::DAGCombinerInfo &DCI,
8697                                            SelectionDAG &DAG) {
8698   // Wait 'til after everything is legalized to try this. That way we have
8699   // legal vector types and such.
8700   if (DCI.isBeforeLegalizeOps())
8701     return SDValue();
8702   // Transform a scalar conversion of a value from a lane extract into a
8703   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8704   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8705   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8706   //
8707   // The second form interacts better with instruction selection and the
8708   // register allocator to avoid cross-class register copies that aren't
8709   // coalescable due to a lane reference.
8710
8711   // Check the operand and see if it originates from a lane extract.
8712   SDValue Op1 = N->getOperand(1);
8713   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8714     // Yep, no additional predication needed. Perform the transform.
8715     SDValue IID = N->getOperand(0);
8716     SDValue Shift = N->getOperand(2);
8717     SDValue Vec = Op1.getOperand(0);
8718     SDValue Lane = Op1.getOperand(1);
8719     EVT ResTy = N->getValueType(0);
8720     EVT VecResTy;
8721     SDLoc DL(N);
8722
8723     // The vector width should be 128 bits by the time we get here, even
8724     // if it started as 64 bits (the extract_vector handling will have
8725     // done so).
8726     assert(Vec.getValueSizeInBits() == 128 &&
8727            "unexpected vector size on extract_vector_elt!");
8728     if (Vec.getValueType() == MVT::v4i32)
8729       VecResTy = MVT::v4f32;
8730     else if (Vec.getValueType() == MVT::v2i64)
8731       VecResTy = MVT::v2f64;
8732     else
8733       llvm_unreachable("unexpected vector type!");
8734
8735     SDValue Convert =
8736         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8737     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8738   }
8739   return SDValue();
8740 }
8741
8742 // AArch64 high-vector "long" operations are formed by performing the non-high
8743 // version on an extract_subvector of each operand which gets the high half:
8744 //
8745 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8746 //
8747 // However, there are cases which don't have an extract_high explicitly, but
8748 // have another operation that can be made compatible with one for free. For
8749 // example:
8750 //
8751 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8752 //
8753 // This routine does the actual conversion of such DUPs, once outer routines
8754 // have determined that everything else is in order.
8755 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8756 // similarly here.
8757 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8758   switch (N.getOpcode()) {
8759   case AArch64ISD::DUP:
8760   case AArch64ISD::DUPLANE8:
8761   case AArch64ISD::DUPLANE16:
8762   case AArch64ISD::DUPLANE32:
8763   case AArch64ISD::DUPLANE64:
8764   case AArch64ISD::MOVI:
8765   case AArch64ISD::MOVIshift:
8766   case AArch64ISD::MOVIedit:
8767   case AArch64ISD::MOVImsl:
8768   case AArch64ISD::MVNIshift:
8769   case AArch64ISD::MVNImsl:
8770     break;
8771   default:
8772     // FMOV could be supported, but isn't very useful, as it would only occur
8773     // if you passed a bitcast' floating point immediate to an eligible long
8774     // integer op (addl, smull, ...).
8775     return SDValue();
8776   }
8777
8778   MVT NarrowTy = N.getSimpleValueType();
8779   if (!NarrowTy.is64BitVector())
8780     return SDValue();
8781
8782   MVT ElementTy = NarrowTy.getVectorElementType();
8783   unsigned NumElems = NarrowTy.getVectorNumElements();
8784   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8785
8786   SDLoc dl(N);
8787   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8788                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8789                      DAG.getConstant(NumElems, dl, MVT::i64));
8790 }
8791
8792 static bool isEssentiallyExtractSubvector(SDValue N) {
8793   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8794     return true;
8795
8796   return N.getOpcode() == ISD::BITCAST &&
8797          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8798 }
8799
8800 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8801 struct GenericSetCCInfo {
8802   const SDValue *Opnd0;
8803   const SDValue *Opnd1;
8804   ISD::CondCode CC;
8805 };
8806
8807 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8808 struct AArch64SetCCInfo {
8809   const SDValue *Cmp;
8810   AArch64CC::CondCode CC;
8811 };
8812
8813 /// \brief Helper structure to keep track of SetCC information.
8814 union SetCCInfo {
8815   GenericSetCCInfo Generic;
8816   AArch64SetCCInfo AArch64;
8817 };
8818
8819 /// \brief Helper structure to be able to read SetCC information.  If set to
8820 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8821 /// GenericSetCCInfo.
8822 struct SetCCInfoAndKind {
8823   SetCCInfo Info;
8824   bool IsAArch64;
8825 };
8826
8827 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8828 /// an
8829 /// AArch64 lowered one.
8830 /// \p SetCCInfo is filled accordingly.
8831 /// \post SetCCInfo is meanginfull only when this function returns true.
8832 /// \return True when Op is a kind of SET_CC operation.
8833 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8834   // If this is a setcc, this is straight forward.
8835   if (Op.getOpcode() == ISD::SETCC) {
8836     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8837     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8838     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8839     SetCCInfo.IsAArch64 = false;
8840     return true;
8841   }
8842   // Otherwise, check if this is a matching csel instruction.
8843   // In other words:
8844   // - csel 1, 0, cc
8845   // - csel 0, 1, !cc
8846   if (Op.getOpcode() != AArch64ISD::CSEL)
8847     return false;
8848   // Set the information about the operands.
8849   // TODO: we want the operands of the Cmp not the csel
8850   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8851   SetCCInfo.IsAArch64 = true;
8852   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8853       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8854
8855   // Check that the operands matches the constraints:
8856   // (1) Both operands must be constants.
8857   // (2) One must be 1 and the other must be 0.
8858   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8859   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8860
8861   // Check (1).
8862   if (!TValue || !FValue)
8863     return false;
8864
8865   // Check (2).
8866   if (!TValue->isOne()) {
8867     // Update the comparison when we are interested in !cc.
8868     std::swap(TValue, FValue);
8869     SetCCInfo.Info.AArch64.CC =
8870         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8871   }
8872   return TValue->isOne() && FValue->isNullValue();
8873 }
8874
8875 // Returns true if Op is setcc or zext of setcc.
8876 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8877   if (isSetCC(Op, Info))
8878     return true;
8879   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8880     isSetCC(Op->getOperand(0), Info));
8881 }
8882
8883 // The folding we want to perform is:
8884 // (add x, [zext] (setcc cc ...) )
8885 //   -->
8886 // (csel x, (add x, 1), !cc ...)
8887 //
8888 // The latter will get matched to a CSINC instruction.
8889 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8890   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8891   SDValue LHS = Op->getOperand(0);
8892   SDValue RHS = Op->getOperand(1);
8893   SetCCInfoAndKind InfoAndKind;
8894
8895   // If neither operand is a SET_CC, give up.
8896   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8897     std::swap(LHS, RHS);
8898     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8899       return SDValue();
8900   }
8901
8902   // FIXME: This could be generatized to work for FP comparisons.
8903   EVT CmpVT = InfoAndKind.IsAArch64
8904                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8905                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8906   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8907     return SDValue();
8908
8909   SDValue CCVal;
8910   SDValue Cmp;
8911   SDLoc dl(Op);
8912   if (InfoAndKind.IsAArch64) {
8913     CCVal = DAG.getConstant(
8914         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8915         MVT::i32);
8916     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8917   } else
8918     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8919                       *InfoAndKind.Info.Generic.Opnd1,
8920                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8921                       CCVal, DAG, dl);
8922
8923   EVT VT = Op->getValueType(0);
8924   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8925   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8926 }
8927
8928 // The basic add/sub long vector instructions have variants with "2" on the end
8929 // which act on the high-half of their inputs. They are normally matched by
8930 // patterns like:
8931 //
8932 // (add (zeroext (extract_high LHS)),
8933 //      (zeroext (extract_high RHS)))
8934 // -> uaddl2 vD, vN, vM
8935 //
8936 // However, if one of the extracts is something like a duplicate, this
8937 // instruction can still be used profitably. This function puts the DAG into a
8938 // more appropriate form for those patterns to trigger.
8939 static SDValue performAddSubLongCombine(SDNode *N,
8940                                         TargetLowering::DAGCombinerInfo &DCI,
8941                                         SelectionDAG &DAG) {
8942   if (DCI.isBeforeLegalizeOps())
8943     return SDValue();
8944
8945   MVT VT = N->getSimpleValueType(0);
8946   if (!VT.is128BitVector()) {
8947     if (N->getOpcode() == ISD::ADD)
8948       return performSetccAddFolding(N, DAG);
8949     return SDValue();
8950   }
8951
8952   // Make sure both branches are extended in the same way.
8953   SDValue LHS = N->getOperand(0);
8954   SDValue RHS = N->getOperand(1);
8955   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8956        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8957       LHS.getOpcode() != RHS.getOpcode())
8958     return SDValue();
8959
8960   unsigned ExtType = LHS.getOpcode();
8961
8962   // It's not worth doing if at least one of the inputs isn't already an
8963   // extract, but we don't know which it'll be so we have to try both.
8964   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8965     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8966     if (!RHS.getNode())
8967       return SDValue();
8968
8969     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8970   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8971     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8972     if (!LHS.getNode())
8973       return SDValue();
8974
8975     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8976   }
8977
8978   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8979 }
8980
8981 // Massage DAGs which we can use the high-half "long" operations on into
8982 // something isel will recognize better. E.g.
8983 //
8984 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8985 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8986 //                     (extract_high (v2i64 (dup128 scalar)))))
8987 //
8988 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8989                                        TargetLowering::DAGCombinerInfo &DCI,
8990                                        SelectionDAG &DAG) {
8991   if (DCI.isBeforeLegalizeOps())
8992     return SDValue();
8993
8994   SDValue LHS = N->getOperand(1);
8995   SDValue RHS = N->getOperand(2);
8996   assert(LHS.getValueType().is64BitVector() &&
8997          RHS.getValueType().is64BitVector() &&
8998          "unexpected shape for long operation");
8999
9000   // Either node could be a DUP, but it's not worth doing both of them (you'd
9001   // just as well use the non-high version) so look for a corresponding extract
9002   // operation on the other "wing".
9003   if (isEssentiallyExtractSubvector(LHS)) {
9004     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9005     if (!RHS.getNode())
9006       return SDValue();
9007   } else if (isEssentiallyExtractSubvector(RHS)) {
9008     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9009     if (!LHS.getNode())
9010       return SDValue();
9011   }
9012
9013   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9014                      N->getOperand(0), LHS, RHS);
9015 }
9016
9017 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9018   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9019   unsigned ElemBits = ElemTy.getSizeInBits();
9020
9021   int64_t ShiftAmount;
9022   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9023     APInt SplatValue, SplatUndef;
9024     unsigned SplatBitSize;
9025     bool HasAnyUndefs;
9026     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9027                               HasAnyUndefs, ElemBits) ||
9028         SplatBitSize != ElemBits)
9029       return SDValue();
9030
9031     ShiftAmount = SplatValue.getSExtValue();
9032   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9033     ShiftAmount = CVN->getSExtValue();
9034   } else
9035     return SDValue();
9036
9037   unsigned Opcode;
9038   bool IsRightShift;
9039   switch (IID) {
9040   default:
9041     llvm_unreachable("Unknown shift intrinsic");
9042   case Intrinsic::aarch64_neon_sqshl:
9043     Opcode = AArch64ISD::SQSHL_I;
9044     IsRightShift = false;
9045     break;
9046   case Intrinsic::aarch64_neon_uqshl:
9047     Opcode = AArch64ISD::UQSHL_I;
9048     IsRightShift = false;
9049     break;
9050   case Intrinsic::aarch64_neon_srshl:
9051     Opcode = AArch64ISD::SRSHR_I;
9052     IsRightShift = true;
9053     break;
9054   case Intrinsic::aarch64_neon_urshl:
9055     Opcode = AArch64ISD::URSHR_I;
9056     IsRightShift = true;
9057     break;
9058   case Intrinsic::aarch64_neon_sqshlu:
9059     Opcode = AArch64ISD::SQSHLU_I;
9060     IsRightShift = false;
9061     break;
9062   }
9063
9064   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9065     SDLoc dl(N);
9066     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9067                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9068   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9069     SDLoc dl(N);
9070     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9071                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
9072   }
9073
9074   return SDValue();
9075 }
9076
9077 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9078 // the intrinsics must be legal and take an i32, this means there's almost
9079 // certainly going to be a zext in the DAG which we can eliminate.
9080 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9081   SDValue AndN = N->getOperand(2);
9082   if (AndN.getOpcode() != ISD::AND)
9083     return SDValue();
9084
9085   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9086   if (!CMask || CMask->getZExtValue() != Mask)
9087     return SDValue();
9088
9089   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9090                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9091 }
9092
9093 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9094                                            SelectionDAG &DAG) {
9095   SDLoc dl(N);
9096   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9097                      DAG.getNode(Opc, dl,
9098                                  N->getOperand(1).getSimpleValueType(),
9099                                  N->getOperand(1)),
9100                      DAG.getConstant(0, dl, MVT::i64));
9101 }
9102
9103 static SDValue performIntrinsicCombine(SDNode *N,
9104                                        TargetLowering::DAGCombinerInfo &DCI,
9105                                        const AArch64Subtarget *Subtarget) {
9106   SelectionDAG &DAG = DCI.DAG;
9107   unsigned IID = getIntrinsicID(N);
9108   switch (IID) {
9109   default:
9110     break;
9111   case Intrinsic::aarch64_neon_vcvtfxs2fp:
9112   case Intrinsic::aarch64_neon_vcvtfxu2fp:
9113     return tryCombineFixedPointConvert(N, DCI, DAG);
9114   case Intrinsic::aarch64_neon_saddv:
9115     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9116   case Intrinsic::aarch64_neon_uaddv:
9117     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9118   case Intrinsic::aarch64_neon_sminv:
9119     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9120   case Intrinsic::aarch64_neon_uminv:
9121     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9122   case Intrinsic::aarch64_neon_smaxv:
9123     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9124   case Intrinsic::aarch64_neon_umaxv:
9125     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9126   case Intrinsic::aarch64_neon_fmax:
9127     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9128                        N->getOperand(1), N->getOperand(2));
9129   case Intrinsic::aarch64_neon_fmin:
9130     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9131                        N->getOperand(1), N->getOperand(2));
9132   case Intrinsic::aarch64_neon_fmaxnm:
9133     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9134                        N->getOperand(1), N->getOperand(2));
9135   case Intrinsic::aarch64_neon_fminnm:
9136     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9137                        N->getOperand(1), N->getOperand(2));
9138   case Intrinsic::aarch64_neon_smull:
9139   case Intrinsic::aarch64_neon_umull:
9140   case Intrinsic::aarch64_neon_pmull:
9141   case Intrinsic::aarch64_neon_sqdmull:
9142     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9143   case Intrinsic::aarch64_neon_sqshl:
9144   case Intrinsic::aarch64_neon_uqshl:
9145   case Intrinsic::aarch64_neon_sqshlu:
9146   case Intrinsic::aarch64_neon_srshl:
9147   case Intrinsic::aarch64_neon_urshl:
9148     return tryCombineShiftImm(IID, N, DAG);
9149   case Intrinsic::aarch64_crc32b:
9150   case Intrinsic::aarch64_crc32cb:
9151     return tryCombineCRC32(0xff, N, DAG);
9152   case Intrinsic::aarch64_crc32h:
9153   case Intrinsic::aarch64_crc32ch:
9154     return tryCombineCRC32(0xffff, N, DAG);
9155   }
9156   return SDValue();
9157 }
9158
9159 static SDValue performExtendCombine(SDNode *N,
9160                                     TargetLowering::DAGCombinerInfo &DCI,
9161                                     SelectionDAG &DAG) {
9162   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9163   // we can convert that DUP into another extract_high (of a bigger DUP), which
9164   // helps the backend to decide that an sabdl2 would be useful, saving a real
9165   // extract_high operation.
9166   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9167       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9168     SDNode *ABDNode = N->getOperand(0).getNode();
9169     unsigned IID = getIntrinsicID(ABDNode);
9170     if (IID == Intrinsic::aarch64_neon_sabd ||
9171         IID == Intrinsic::aarch64_neon_uabd) {
9172       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9173       if (!NewABD.getNode())
9174         return SDValue();
9175
9176       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9177                          NewABD);
9178     }
9179   }
9180
9181   // This is effectively a custom type legalization for AArch64.
9182   //
9183   // Type legalization will split an extend of a small, legal, type to a larger
9184   // illegal type by first splitting the destination type, often creating
9185   // illegal source types, which then get legalized in isel-confusing ways,
9186   // leading to really terrible codegen. E.g.,
9187   //   %result = v8i32 sext v8i8 %value
9188   // becomes
9189   //   %losrc = extract_subreg %value, ...
9190   //   %hisrc = extract_subreg %value, ...
9191   //   %lo = v4i32 sext v4i8 %losrc
9192   //   %hi = v4i32 sext v4i8 %hisrc
9193   // Things go rapidly downhill from there.
9194   //
9195   // For AArch64, the [sz]ext vector instructions can only go up one element
9196   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9197   // take two instructions.
9198   //
9199   // This implies that the most efficient way to do the extend from v8i8
9200   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9201   // the normal splitting to happen for the v8i16->v8i32.
9202
9203   // This is pre-legalization to catch some cases where the default
9204   // type legalization will create ill-tempered code.
9205   if (!DCI.isBeforeLegalizeOps())
9206     return SDValue();
9207
9208   // We're only interested in cleaning things up for non-legal vector types
9209   // here. If both the source and destination are legal, things will just
9210   // work naturally without any fiddling.
9211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9212   EVT ResVT = N->getValueType(0);
9213   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9214     return SDValue();
9215   // If the vector type isn't a simple VT, it's beyond the scope of what
9216   // we're  worried about here. Let legalization do its thing and hope for
9217   // the best.
9218   SDValue Src = N->getOperand(0);
9219   EVT SrcVT = Src->getValueType(0);
9220   if (!ResVT.isSimple() || !SrcVT.isSimple())
9221     return SDValue();
9222
9223   // If the source VT is a 64-bit vector, we can play games and get the
9224   // better results we want.
9225   if (SrcVT.getSizeInBits() != 64)
9226     return SDValue();
9227
9228   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9229   unsigned ElementCount = SrcVT.getVectorNumElements();
9230   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9231   SDLoc DL(N);
9232   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9233
9234   // Now split the rest of the operation into two halves, each with a 64
9235   // bit source.
9236   EVT LoVT, HiVT;
9237   SDValue Lo, Hi;
9238   unsigned NumElements = ResVT.getVectorNumElements();
9239   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9240   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9241                                  ResVT.getVectorElementType(), NumElements / 2);
9242
9243   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9244                                LoVT.getVectorNumElements());
9245   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9246                    DAG.getConstant(0, DL, MVT::i64));
9247   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9248                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9249   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9250   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9251
9252   // Now combine the parts back together so we still have a single result
9253   // like the combiner expects.
9254   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9255 }
9256
9257 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9258                                SDValue SplatVal, unsigned NumVecElts) {
9259   unsigned OrigAlignment = St.getAlignment();
9260   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9261
9262   // Create scalar stores. This is at least as good as the code sequence for a
9263   // split unaligned store which is a dup.s, ext.b, and two stores.
9264   // Most of the time the three stores should be replaced by store pair
9265   // instructions (stp).
9266   SDLoc DL(&St);
9267   SDValue BasePtr = St.getBasePtr();
9268   uint64_t BaseOffset = 0;
9269
9270   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9271   SDValue NewST1 =
9272       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9273                    OrigAlignment, St.getMemOperand()->getFlags());
9274
9275   // As this in ISel, we will not merge this add which may degrade results.
9276   if (BasePtr->getOpcode() == ISD::ADD &&
9277       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9278     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9279     BasePtr = BasePtr->getOperand(0);
9280   }
9281
9282   unsigned Offset = EltOffset;
9283   while (--NumVecElts) {
9284     unsigned Alignment = MinAlign(OrigAlignment, Offset);
9285     SDValue OffsetPtr =
9286         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9287                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
9288     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9289                           PtrInfo.getWithOffset(Offset), Alignment,
9290                           St.getMemOperand()->getFlags());
9291     Offset += EltOffset;
9292   }
9293   return NewST1;
9294 }
9295
9296 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
9297 /// load store optimizer pass will merge them to store pair stores.  This should
9298 /// be better than a movi to create the vector zero followed by a vector store
9299 /// if the zero constant is not re-used, since one instructions and one register
9300 /// live range will be removed.
9301 ///
9302 /// For example, the final generated code should be:
9303 ///
9304 ///   stp xzr, xzr, [x0]
9305 ///
9306 /// instead of:
9307 ///
9308 ///   movi v0.2d, #0
9309 ///   str q0, [x0]
9310 ///
9311 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9312   SDValue StVal = St.getValue();
9313   EVT VT = StVal.getValueType();
9314
9315   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9316   // 2, 3 or 4 i32 elements.
9317   int NumVecElts = VT.getVectorNumElements();
9318   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9319          VT.getVectorElementType().getSizeInBits() == 64) ||
9320         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9321          VT.getVectorElementType().getSizeInBits() == 32)))
9322     return SDValue();
9323
9324   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9325     return SDValue();
9326
9327   // If the zero constant has more than one use then the vector store could be
9328   // better since the constant mov will be amortized and stp q instructions
9329   // should be able to be formed.
9330   if (!StVal.hasOneUse())
9331     return SDValue();
9332
9333   // If the immediate offset of the address operand is too large for the stp
9334   // instruction, then bail out.
9335   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9336     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9337     if (Offset < -512 || Offset > 504)
9338       return SDValue();
9339   }
9340
9341   for (int I = 0; I < NumVecElts; ++I) {
9342     SDValue EltVal = StVal.getOperand(I);
9343     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9344       return SDValue();
9345   }
9346
9347   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9348   // undoing this transformation.
9349   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9350                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
9351                          : DAG.getRegister(AArch64::XZR, MVT::i64);
9352   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9353 }
9354
9355 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9356 /// value. The load store optimizer pass will merge them to store pair stores.
9357 /// This has better performance than a splat of the scalar followed by a split
9358 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9359 /// followed by an ext.b and two stores.
9360 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9361   SDValue StVal = St.getValue();
9362   EVT VT = StVal.getValueType();
9363
9364   // Don't replace floating point stores, they possibly won't be transformed to
9365   // stp because of the store pair suppress pass.
9366   if (VT.isFloatingPoint())
9367     return SDValue();
9368
9369   // We can express a splat as store pair(s) for 2 or 4 elements.
9370   unsigned NumVecElts = VT.getVectorNumElements();
9371   if (NumVecElts != 4 && NumVecElts != 2)
9372     return SDValue();
9373
9374   // Check that this is a splat.
9375   // Make sure that each of the relevant vector element locations are inserted
9376   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9377   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9378   SDValue SplatVal;
9379   for (unsigned I = 0; I < NumVecElts; ++I) {
9380     // Check for insert vector elements.
9381     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9382       return SDValue();
9383
9384     // Check that same value is inserted at each vector element.
9385     if (I == 0)
9386       SplatVal = StVal.getOperand(1);
9387     else if (StVal.getOperand(1) != SplatVal)
9388       return SDValue();
9389
9390     // Check insert element index.
9391     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9392     if (!CIndex)
9393       return SDValue();
9394     uint64_t IndexVal = CIndex->getZExtValue();
9395     if (IndexVal >= NumVecElts)
9396       return SDValue();
9397     IndexNotInserted.reset(IndexVal);
9398
9399     StVal = StVal.getOperand(0);
9400   }
9401   // Check that all vector element locations were inserted to.
9402   if (IndexNotInserted.any())
9403       return SDValue();
9404
9405   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9406 }
9407
9408 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9409                            SelectionDAG &DAG,
9410                            const AArch64Subtarget *Subtarget) {
9411   if (!DCI.isBeforeLegalize())
9412     return SDValue();
9413
9414   StoreSDNode *S = cast<StoreSDNode>(N);
9415   if (S->isVolatile() || S->isIndexed())
9416     return SDValue();
9417
9418   SDValue StVal = S->getValue();
9419   EVT VT = StVal.getValueType();
9420   if (!VT.isVector())
9421     return SDValue();
9422
9423   // If we get a splat of zeros, convert this vector store to a store of
9424   // scalars. They will be merged into store pairs of xzr thereby removing one
9425   // instruction and one register.
9426   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9427     return ReplacedZeroSplat;
9428
9429   // FIXME: The logic for deciding if an unaligned store should be split should
9430   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9431   // a call to that function here.
9432
9433   if (!Subtarget->isMisaligned128StoreSlow())
9434     return SDValue();
9435
9436   // Don't split at -Oz.
9437   if (DAG.getMachineFunction().getFunction()->optForMinSize())
9438     return SDValue();
9439
9440   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9441   // those up regresses performance on micro-benchmarks and olden/bh.
9442   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9443     return SDValue();
9444
9445   // Split unaligned 16B stores. They are terrible for performance.
9446   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9447   // extensions can use this to mark that it does not want splitting to happen
9448   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9449   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9450   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9451       S->getAlignment() <= 2)
9452     return SDValue();
9453
9454   // If we get a splat of a scalar convert this vector store to a store of
9455   // scalars. They will be merged into store pairs thereby removing two
9456   // instructions.
9457   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9458     return ReplacedSplat;
9459
9460   SDLoc DL(S);
9461   unsigned NumElts = VT.getVectorNumElements() / 2;
9462   // Split VT into two.
9463   EVT HalfVT =
9464       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9465   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9466                                    DAG.getConstant(0, DL, MVT::i64));
9467   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9468                                    DAG.getConstant(NumElts, DL, MVT::i64));
9469   SDValue BasePtr = S->getBasePtr();
9470   SDValue NewST1 =
9471       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9472                    S->getAlignment(), S->getMemOperand()->getFlags());
9473   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9474                                   DAG.getConstant(8, DL, MVT::i64));
9475   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9476                       S->getPointerInfo(), S->getAlignment(),
9477                       S->getMemOperand()->getFlags());
9478 }
9479
9480 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9481 /// post-increment LD1R.
9482 static SDValue performPostLD1Combine(SDNode *N,
9483                                      TargetLowering::DAGCombinerInfo &DCI,
9484                                      bool IsLaneOp) {
9485   if (DCI.isBeforeLegalizeOps())
9486     return SDValue();
9487
9488   SelectionDAG &DAG = DCI.DAG;
9489   EVT VT = N->getValueType(0);
9490
9491   unsigned LoadIdx = IsLaneOp ? 1 : 0;
9492   SDNode *LD = N->getOperand(LoadIdx).getNode();
9493   // If it is not LOAD, can not do such combine.
9494   if (LD->getOpcode() != ISD::LOAD)
9495     return SDValue();
9496
9497   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9498   EVT MemVT = LoadSDN->getMemoryVT();
9499   // Check if memory operand is the same type as the vector element.
9500   if (MemVT != VT.getVectorElementType())
9501     return SDValue();
9502
9503   // Check if there are other uses. If so, do not combine as it will introduce
9504   // an extra load.
9505   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9506        ++UI) {
9507     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9508       continue;
9509     if (*UI != N)
9510       return SDValue();
9511   }
9512
9513   SDValue Addr = LD->getOperand(1);
9514   SDValue Vector = N->getOperand(0);
9515   // Search for a use of the address operand that is an increment.
9516   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9517        Addr.getNode()->use_end(); UI != UE; ++UI) {
9518     SDNode *User = *UI;
9519     if (User->getOpcode() != ISD::ADD
9520         || UI.getUse().getResNo() != Addr.getResNo())
9521       continue;
9522
9523     // Check that the add is independent of the load.  Otherwise, folding it
9524     // would create a cycle.
9525     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9526       continue;
9527     // Also check that add is not used in the vector operand.  This would also
9528     // create a cycle.
9529     if (User->isPredecessorOf(Vector.getNode()))
9530       continue;
9531
9532     // If the increment is a constant, it must match the memory ref size.
9533     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9534     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9535       uint32_t IncVal = CInc->getZExtValue();
9536       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9537       if (IncVal != NumBytes)
9538         continue;
9539       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9540     }
9541
9542     // Finally, check that the vector doesn't depend on the load.
9543     // Again, this would create a cycle.
9544     // The load depending on the vector is fine, as that's the case for the
9545     // LD1*post we'll eventually generate anyway.
9546     if (LoadSDN->isPredecessorOf(Vector.getNode()))
9547       continue;
9548
9549     SmallVector<SDValue, 8> Ops;
9550     Ops.push_back(LD->getOperand(0));  // Chain
9551     if (IsLaneOp) {
9552       Ops.push_back(Vector);           // The vector to be inserted
9553       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9554     }
9555     Ops.push_back(Addr);
9556     Ops.push_back(Inc);
9557
9558     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9559     SDVTList SDTys = DAG.getVTList(Tys);
9560     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9561     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9562                                            MemVT,
9563                                            LoadSDN->getMemOperand());
9564
9565     // Update the uses.
9566     SDValue NewResults[] = {
9567         SDValue(LD, 0),            // The result of load
9568         SDValue(UpdN.getNode(), 2) // Chain
9569     };
9570     DCI.CombineTo(LD, NewResults);
9571     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
9572     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
9573
9574     break;
9575   }
9576   return SDValue();
9577 }
9578
9579 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
9580 /// address translation.
9581 static bool performTBISimplification(SDValue Addr,
9582                                      TargetLowering::DAGCombinerInfo &DCI,
9583                                      SelectionDAG &DAG) {
9584   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9585   KnownBits Known;
9586   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9587                                         DCI.isBeforeLegalizeOps());
9588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9589   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9590     DCI.CommitTargetLoweringOpt(TLO);
9591     return true;
9592   }
9593   return false;
9594 }
9595
9596 static SDValue performSTORECombine(SDNode *N,
9597                                    TargetLowering::DAGCombinerInfo &DCI,
9598                                    SelectionDAG &DAG,
9599                                    const AArch64Subtarget *Subtarget) {
9600   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9601     return Split;
9602
9603   if (Subtarget->supportsAddressTopByteIgnored() &&
9604       performTBISimplification(N->getOperand(2), DCI, DAG))
9605     return SDValue(N, 0);
9606
9607   return SDValue();
9608 }
9609
9610
9611 /// Target-specific DAG combine function for NEON load/store intrinsics
9612 /// to merge base address updates.
9613 static SDValue performNEONPostLDSTCombine(SDNode *N,
9614                                           TargetLowering::DAGCombinerInfo &DCI,
9615                                           SelectionDAG &DAG) {
9616   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9617     return SDValue();
9618
9619   unsigned AddrOpIdx = N->getNumOperands() - 1;
9620   SDValue Addr = N->getOperand(AddrOpIdx);
9621
9622   // Search for a use of the address operand that is an increment.
9623   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9624        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9625     SDNode *User = *UI;
9626     if (User->getOpcode() != ISD::ADD ||
9627         UI.getUse().getResNo() != Addr.getResNo())
9628       continue;
9629
9630     // Check that the add is independent of the load/store.  Otherwise, folding
9631     // it would create a cycle.
9632     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9633       continue;
9634
9635     // Find the new opcode for the updating load/store.
9636     bool IsStore = false;
9637     bool IsLaneOp = false;
9638     bool IsDupOp = false;
9639     unsigned NewOpc = 0;
9640     unsigned NumVecs = 0;
9641     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9642     switch (IntNo) {
9643     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9644     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9645       NumVecs = 2; break;
9646     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9647       NumVecs = 3; break;
9648     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9649       NumVecs = 4; break;
9650     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9651       NumVecs = 2; IsStore = true; break;
9652     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9653       NumVecs = 3; IsStore = true; break;
9654     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9655       NumVecs = 4; IsStore = true; break;
9656     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9657       NumVecs = 2; break;
9658     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9659       NumVecs = 3; break;
9660     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9661       NumVecs = 4; break;
9662     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9663       NumVecs = 2; IsStore = true; break;
9664     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9665       NumVecs = 3; IsStore = true; break;
9666     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9667       NumVecs = 4; IsStore = true; break;
9668     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9669       NumVecs = 2; IsDupOp = true; break;
9670     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9671       NumVecs = 3; IsDupOp = true; break;
9672     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9673       NumVecs = 4; IsDupOp = true; break;
9674     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9675       NumVecs = 2; IsLaneOp = true; break;
9676     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9677       NumVecs = 3; IsLaneOp = true; break;
9678     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9679       NumVecs = 4; IsLaneOp = true; break;
9680     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9681       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9682     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9683       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9684     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9685       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9686     }
9687
9688     EVT VecTy;
9689     if (IsStore)
9690       VecTy = N->getOperand(2).getValueType();
9691     else
9692       VecTy = N->getValueType(0);
9693
9694     // If the increment is a constant, it must match the memory ref size.
9695     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9696     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9697       uint32_t IncVal = CInc->getZExtValue();
9698       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9699       if (IsLaneOp || IsDupOp)
9700         NumBytes /= VecTy.getVectorNumElements();
9701       if (IncVal != NumBytes)
9702         continue;
9703       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9704     }
9705     SmallVector<SDValue, 8> Ops;
9706     Ops.push_back(N->getOperand(0)); // Incoming chain
9707     // Load lane and store have vector list as input.
9708     if (IsLaneOp || IsStore)
9709       for (unsigned i = 2; i < AddrOpIdx; ++i)
9710         Ops.push_back(N->getOperand(i));
9711     Ops.push_back(Addr); // Base register
9712     Ops.push_back(Inc);
9713
9714     // Return Types.
9715     EVT Tys[6];
9716     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9717     unsigned n;
9718     for (n = 0; n < NumResultVecs; ++n)
9719       Tys[n] = VecTy;
9720     Tys[n++] = MVT::i64;  // Type of write back register
9721     Tys[n] = MVT::Other;  // Type of the chain
9722     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9723
9724     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9725     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9726                                            MemInt->getMemoryVT(),
9727                                            MemInt->getMemOperand());
9728
9729     // Update the uses.
9730     std::vector<SDValue> NewResults;
9731     for (unsigned i = 0; i < NumResultVecs; ++i) {
9732       NewResults.push_back(SDValue(UpdN.getNode(), i));
9733     }
9734     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9735     DCI.CombineTo(N, NewResults);
9736     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9737
9738     break;
9739   }
9740   return SDValue();
9741 }
9742
9743 // Checks to see if the value is the prescribed width and returns information
9744 // about its extension mode.
9745 static
9746 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9747   ExtType = ISD::NON_EXTLOAD;
9748   switch(V.getNode()->getOpcode()) {
9749   default:
9750     return false;
9751   case ISD::LOAD: {
9752     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9753     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9754        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9755       ExtType = LoadNode->getExtensionType();
9756       return true;
9757     }
9758     return false;
9759   }
9760   case ISD::AssertSext: {
9761     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9762     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9763        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9764       ExtType = ISD::SEXTLOAD;
9765       return true;
9766     }
9767     return false;
9768   }
9769   case ISD::AssertZext: {
9770     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9771     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9772        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9773       ExtType = ISD::ZEXTLOAD;
9774       return true;
9775     }
9776     return false;
9777   }
9778   case ISD::Constant:
9779   case ISD::TargetConstant: {
9780     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9781            1LL << (width - 1);
9782   }
9783   }
9784
9785   return true;
9786 }
9787
9788 // This function does a whole lot of voodoo to determine if the tests are
9789 // equivalent without and with a mask. Essentially what happens is that given a
9790 // DAG resembling:
9791 //
9792 //  +-------------+ +-------------+ +-------------+ +-------------+
9793 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9794 //  +-------------+ +-------------+ +-------------+ +-------------+
9795 //           |           |           |               |
9796 //           V           V           |    +----------+
9797 //          +-------------+  +----+  |    |
9798 //          |     ADD     |  |0xff|  |    |
9799 //          +-------------+  +----+  |    |
9800 //                  |           |    |    |
9801 //                  V           V    |    |
9802 //                 +-------------+   |    |
9803 //                 |     AND     |   |    |
9804 //                 +-------------+   |    |
9805 //                      |            |    |
9806 //                      +-----+      |    |
9807 //                            |      |    |
9808 //                            V      V    V
9809 //                           +-------------+
9810 //                           |     CMP     |
9811 //                           +-------------+
9812 //
9813 // The AND node may be safely removed for some combinations of inputs. In
9814 // particular we need to take into account the extension type of the Input,
9815 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9816 // width of the input (this can work for any width inputs, the above graph is
9817 // specific to 8 bits.
9818 //
9819 // The specific equations were worked out by generating output tables for each
9820 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9821 // problem was simplified by working with 4 bit inputs, which means we only
9822 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9823 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9824 // patterns present in both extensions (0,7). For every distinct set of
9825 // AddConstant and CompConstants bit patterns we can consider the masked and
9826 // unmasked versions to be equivalent if the result of this function is true for
9827 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9828 //
9829 //   sub      w8, w0, w1
9830 //   and      w10, w8, #0x0f
9831 //   cmp      w8, w2
9832 //   cset     w9, AArch64CC
9833 //   cmp      w10, w2
9834 //   cset     w11, AArch64CC
9835 //   cmp      w9, w11
9836 //   cset     w0, eq
9837 //   ret
9838 //
9839 // Since the above function shows when the outputs are equivalent it defines
9840 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9841 // would be expensive to run during compiles. The equations below were written
9842 // in a test harness that confirmed they gave equivalent outputs to the above
9843 // for all inputs function, so they can be used determine if the removal is
9844 // legal instead.
9845 //
9846 // isEquivalentMaskless() is the code for testing if the AND can be removed
9847 // factored out of the DAG recognition as the DAG can take several forms.
9848
9849 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9850                                  ISD::LoadExtType ExtType, int AddConstant,
9851                                  int CompConstant) {
9852   // By being careful about our equations and only writing the in term
9853   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9854   // make them generally applicable to all bit widths.
9855   int MaxUInt = (1 << width);
9856
9857   // For the purposes of these comparisons sign extending the type is
9858   // equivalent to zero extending the add and displacing it by half the integer
9859   // width. Provided we are careful and make sure our equations are valid over
9860   // the whole range we can just adjust the input and avoid writing equations
9861   // for sign extended inputs.
9862   if (ExtType == ISD::SEXTLOAD)
9863     AddConstant -= (1 << (width-1));
9864
9865   switch(CC) {
9866   case AArch64CC::LE:
9867   case AArch64CC::GT:
9868     if ((AddConstant == 0) ||
9869         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9870         (AddConstant >= 0 && CompConstant < 0) ||
9871         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9872       return true;
9873     break;
9874   case AArch64CC::LT:
9875   case AArch64CC::GE:
9876     if ((AddConstant == 0) ||
9877         (AddConstant >= 0 && CompConstant <= 0) ||
9878         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9879       return true;
9880     break;
9881   case AArch64CC::HI:
9882   case AArch64CC::LS:
9883     if ((AddConstant >= 0 && CompConstant < 0) ||
9884        (AddConstant <= 0 && CompConstant >= -1 &&
9885         CompConstant < AddConstant + MaxUInt))
9886       return true;
9887    break;
9888   case AArch64CC::PL:
9889   case AArch64CC::MI:
9890     if ((AddConstant == 0) ||
9891         (AddConstant > 0 && CompConstant <= 0) ||
9892         (AddConstant < 0 && CompConstant <= AddConstant))
9893       return true;
9894     break;
9895   case AArch64CC::LO:
9896   case AArch64CC::HS:
9897     if ((AddConstant >= 0 && CompConstant <= 0) ||
9898         (AddConstant <= 0 && CompConstant >= 0 &&
9899          CompConstant <= AddConstant + MaxUInt))
9900       return true;
9901     break;
9902   case AArch64CC::EQ:
9903   case AArch64CC::NE:
9904     if ((AddConstant > 0 && CompConstant < 0) ||
9905         (AddConstant < 0 && CompConstant >= 0 &&
9906          CompConstant < AddConstant + MaxUInt) ||
9907         (AddConstant >= 0 && CompConstant >= 0 &&
9908          CompConstant >= AddConstant) ||
9909         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9910       return true;
9911     break;
9912   case AArch64CC::VS:
9913   case AArch64CC::VC:
9914   case AArch64CC::AL:
9915   case AArch64CC::NV:
9916     return true;
9917   case AArch64CC::Invalid:
9918     break;
9919   }
9920
9921   return false;
9922 }
9923
9924 static
9925 SDValue performCONDCombine(SDNode *N,
9926                            TargetLowering::DAGCombinerInfo &DCI,
9927                            SelectionDAG &DAG, unsigned CCIndex,
9928                            unsigned CmpIndex) {
9929   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9930   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9931   unsigned CondOpcode = SubsNode->getOpcode();
9932
9933   if (CondOpcode != AArch64ISD::SUBS)
9934     return SDValue();
9935
9936   // There is a SUBS feeding this condition. Is it fed by a mask we can
9937   // use?
9938
9939   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9940   unsigned MaskBits = 0;
9941
9942   if (AndNode->getOpcode() != ISD::AND)
9943     return SDValue();
9944
9945   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9946     uint32_t CNV = CN->getZExtValue();
9947     if (CNV == 255)
9948       MaskBits = 8;
9949     else if (CNV == 65535)
9950       MaskBits = 16;
9951   }
9952
9953   if (!MaskBits)
9954     return SDValue();
9955
9956   SDValue AddValue = AndNode->getOperand(0);
9957
9958   if (AddValue.getOpcode() != ISD::ADD)
9959     return SDValue();
9960
9961   // The basic dag structure is correct, grab the inputs and validate them.
9962
9963   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9964   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9965   SDValue SubsInputValue = SubsNode->getOperand(1);
9966
9967   // The mask is present and the provenance of all the values is a smaller type,
9968   // lets see if the mask is superfluous.
9969
9970   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9971       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9972     return SDValue();
9973
9974   ISD::LoadExtType ExtType;
9975
9976   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9977       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9978       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9979     return SDValue();
9980
9981   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9982                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9983                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9984     return SDValue();
9985
9986   // The AND is not necessary, remove it.
9987
9988   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9989                                SubsNode->getValueType(1));
9990   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9991
9992   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9993   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9994
9995   return SDValue(N, 0);
9996 }
9997
9998 // Optimize compare with zero and branch.
9999 static SDValue performBRCONDCombine(SDNode *N,
10000                                     TargetLowering::DAGCombinerInfo &DCI,
10001                                     SelectionDAG &DAG) {
10002   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10003     N = NV.getNode();
10004   SDValue Chain = N->getOperand(0);
10005   SDValue Dest = N->getOperand(1);
10006   SDValue CCVal = N->getOperand(2);
10007   SDValue Cmp = N->getOperand(3);
10008
10009   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10010   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10011   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10012     return SDValue();
10013
10014   unsigned CmpOpc = Cmp.getOpcode();
10015   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10016     return SDValue();
10017
10018   // Only attempt folding if there is only one use of the flag and no use of the
10019   // value.
10020   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10021     return SDValue();
10022
10023   SDValue LHS = Cmp.getOperand(0);
10024   SDValue RHS = Cmp.getOperand(1);
10025
10026   assert(LHS.getValueType() == RHS.getValueType() &&
10027          "Expected the value type to be the same for both operands!");
10028   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10029     return SDValue();
10030
10031   if (isNullConstant(LHS))
10032     std::swap(LHS, RHS);
10033
10034   if (!isNullConstant(RHS))
10035     return SDValue();
10036
10037   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10038       LHS.getOpcode() == ISD::SRL)
10039     return SDValue();
10040
10041   // Fold the compare into the branch instruction.
10042   SDValue BR;
10043   if (CC == AArch64CC::EQ)
10044     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10045   else
10046     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10047
10048   // Do not add new nodes to DAG combiner worklist.
10049   DCI.CombineTo(N, BR, false);
10050
10051   return SDValue();
10052 }
10053
10054 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
10055 // as well as whether the test should be inverted.  This code is required to
10056 // catch these cases (as opposed to standard dag combines) because
10057 // AArch64ISD::TBZ is matched during legalization.
10058 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10059                                  SelectionDAG &DAG) {
10060
10061   if (!Op->hasOneUse())
10062     return Op;
10063
10064   // We don't handle undef/constant-fold cases below, as they should have
10065   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10066   // etc.)
10067
10068   // (tbz (trunc x), b) -> (tbz x, b)
10069   // This case is just here to enable more of the below cases to be caught.
10070   if (Op->getOpcode() == ISD::TRUNCATE &&
10071       Bit < Op->getValueType(0).getSizeInBits()) {
10072     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10073   }
10074
10075   if (Op->getNumOperands() != 2)
10076     return Op;
10077
10078   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10079   if (!C)
10080     return Op;
10081
10082   switch (Op->getOpcode()) {
10083   default:
10084     return Op;
10085
10086   // (tbz (and x, m), b) -> (tbz x, b)
10087   case ISD::AND:
10088     if ((C->getZExtValue() >> Bit) & 1)
10089       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10090     return Op;
10091
10092   // (tbz (shl x, c), b) -> (tbz x, b-c)
10093   case ISD::SHL:
10094     if (C->getZExtValue() <= Bit &&
10095         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10096       Bit = Bit - C->getZExtValue();
10097       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10098     }
10099     return Op;
10100
10101   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10102   case ISD::SRA:
10103     Bit = Bit + C->getZExtValue();
10104     if (Bit >= Op->getValueType(0).getSizeInBits())
10105       Bit = Op->getValueType(0).getSizeInBits() - 1;
10106     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10107
10108   // (tbz (srl x, c), b) -> (tbz x, b+c)
10109   case ISD::SRL:
10110     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10111       Bit = Bit + C->getZExtValue();
10112       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10113     }
10114     return Op;
10115
10116   // (tbz (xor x, -1), b) -> (tbnz x, b)
10117   case ISD::XOR:
10118     if ((C->getZExtValue() >> Bit) & 1)
10119       Invert = !Invert;
10120     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10121   }
10122 }
10123
10124 // Optimize test single bit zero/non-zero and branch.
10125 static SDValue performTBZCombine(SDNode *N,
10126                                  TargetLowering::DAGCombinerInfo &DCI,
10127                                  SelectionDAG &DAG) {
10128   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10129   bool Invert = false;
10130   SDValue TestSrc = N->getOperand(1);
10131   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10132
10133   if (TestSrc == NewTestSrc)
10134     return SDValue();
10135
10136   unsigned NewOpc = N->getOpcode();
10137   if (Invert) {
10138     if (NewOpc == AArch64ISD::TBZ)
10139       NewOpc = AArch64ISD::TBNZ;
10140     else {
10141       assert(NewOpc == AArch64ISD::TBNZ);
10142       NewOpc = AArch64ISD::TBZ;
10143     }
10144   }
10145
10146   SDLoc DL(N);
10147   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10148                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10149 }
10150
10151 // vselect (v1i1 setcc) ->
10152 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10153 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10154 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10155 // such VSELECT.
10156 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10157   SDValue N0 = N->getOperand(0);
10158   EVT CCVT = N0.getValueType();
10159
10160   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10161       CCVT.getVectorElementType() != MVT::i1)
10162     return SDValue();
10163
10164   EVT ResVT = N->getValueType(0);
10165   EVT CmpVT = N0.getOperand(0).getValueType();
10166   // Only combine when the result type is of the same size as the compared
10167   // operands.
10168   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10169     return SDValue();
10170
10171   SDValue IfTrue = N->getOperand(1);
10172   SDValue IfFalse = N->getOperand(2);
10173   SDValue SetCC =
10174       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10175                    N0.getOperand(0), N0.getOperand(1),
10176                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10177   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10178                      IfTrue, IfFalse);
10179 }
10180
10181 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10182 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10183 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10184 /// with a vector one followed by a DUP shuffle on the result.
10185 static SDValue performSelectCombine(SDNode *N,
10186                                     TargetLowering::DAGCombinerInfo &DCI) {
10187   SelectionDAG &DAG = DCI.DAG;
10188   SDValue N0 = N->getOperand(0);
10189   EVT ResVT = N->getValueType(0);
10190
10191   if (N0.getOpcode() != ISD::SETCC)
10192     return SDValue();
10193
10194   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10195   // scalar SetCCResultType. We also don't expect vectors, because we assume
10196   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10197   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10198          "Scalar-SETCC feeding SELECT has unexpected result type!");
10199
10200   // If NumMaskElts == 0, the comparison is larger than select result. The
10201   // largest real NEON comparison is 64-bits per lane, which means the result is
10202   // at most 32-bits and an illegal vector. Just bail out for now.
10203   EVT SrcVT = N0.getOperand(0).getValueType();
10204
10205   // Don't try to do this optimization when the setcc itself has i1 operands.
10206   // There are no legal vectors of i1, so this would be pointless.
10207   if (SrcVT == MVT::i1)
10208     return SDValue();
10209
10210   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10211   if (!ResVT.isVector() || NumMaskElts == 0)
10212     return SDValue();
10213
10214   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10215   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10216
10217   // Also bail out if the vector CCVT isn't the same size as ResVT.
10218   // This can happen if the SETCC operand size doesn't divide the ResVT size
10219   // (e.g., f64 vs v3f32).
10220   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10221     return SDValue();
10222
10223   // Make sure we didn't create illegal types, if we're not supposed to.
10224   assert(DCI.isBeforeLegalize() ||
10225          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10226
10227   // First perform a vector comparison, where lane 0 is the one we're interested
10228   // in.
10229   SDLoc DL(N0);
10230   SDValue LHS =
10231       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10232   SDValue RHS =
10233       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10234   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10235
10236   // Now duplicate the comparison mask we want across all other lanes.
10237   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10238   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10239   Mask = DAG.getNode(ISD::BITCAST, DL,
10240                      ResVT.changeVectorElementTypeToInteger(), Mask);
10241
10242   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10243 }
10244
10245 /// Get rid of unnecessary NVCASTs (that don't change the type).
10246 static SDValue performNVCASTCombine(SDNode *N) {
10247   if (N->getValueType(0) == N->getOperand(0).getValueType())
10248     return N->getOperand(0);
10249
10250   return SDValue();
10251 }
10252
10253 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10254                                                  DAGCombinerInfo &DCI) const {
10255   SelectionDAG &DAG = DCI.DAG;
10256   switch (N->getOpcode()) {
10257   default:
10258     break;
10259   case ISD::ADD:
10260   case ISD::SUB:
10261     return performAddSubLongCombine(N, DCI, DAG);
10262   case ISD::XOR:
10263     return performXorCombine(N, DAG, DCI, Subtarget);
10264   case ISD::MUL:
10265     return performMulCombine(N, DAG, DCI, Subtarget);
10266   case ISD::SINT_TO_FP:
10267   case ISD::UINT_TO_FP:
10268     return performIntToFpCombine(N, DAG, Subtarget);
10269   case ISD::FP_TO_SINT:
10270   case ISD::FP_TO_UINT:
10271     return performFpToIntCombine(N, DAG, DCI, Subtarget);
10272   case ISD::FDIV:
10273     return performFDivCombine(N, DAG, DCI, Subtarget);
10274   case ISD::OR:
10275     return performORCombine(N, DCI, Subtarget);
10276   case ISD::SRL:
10277     return performSRLCombine(N, DCI);
10278   case ISD::INTRINSIC_WO_CHAIN:
10279     return performIntrinsicCombine(N, DCI, Subtarget);
10280   case ISD::ANY_EXTEND:
10281   case ISD::ZERO_EXTEND:
10282   case ISD::SIGN_EXTEND:
10283     return performExtendCombine(N, DCI, DAG);
10284   case ISD::BITCAST:
10285     return performBitcastCombine(N, DCI, DAG);
10286   case ISD::CONCAT_VECTORS:
10287     return performConcatVectorsCombine(N, DCI, DAG);
10288   case ISD::SELECT:
10289     return performSelectCombine(N, DCI);
10290   case ISD::VSELECT:
10291     return performVSelectCombine(N, DCI.DAG);
10292   case ISD::LOAD:
10293     if (performTBISimplification(N->getOperand(1), DCI, DAG))
10294       return SDValue(N, 0);
10295     break;
10296   case ISD::STORE:
10297     return performSTORECombine(N, DCI, DAG, Subtarget);
10298   case AArch64ISD::BRCOND:
10299     return performBRCONDCombine(N, DCI, DAG);
10300   case AArch64ISD::TBNZ:
10301   case AArch64ISD::TBZ:
10302     return performTBZCombine(N, DCI, DAG);
10303   case AArch64ISD::CSEL:
10304     return performCONDCombine(N, DCI, DAG, 2, 3);
10305   case AArch64ISD::DUP:
10306     return performPostLD1Combine(N, DCI, false);
10307   case AArch64ISD::NVCAST:
10308     return performNVCASTCombine(N);
10309   case ISD::INSERT_VECTOR_ELT:
10310     return performPostLD1Combine(N, DCI, true);
10311   case ISD::INTRINSIC_VOID:
10312   case ISD::INTRINSIC_W_CHAIN:
10313     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10314     case Intrinsic::aarch64_neon_ld2:
10315     case Intrinsic::aarch64_neon_ld3:
10316     case Intrinsic::aarch64_neon_ld4:
10317     case Intrinsic::aarch64_neon_ld1x2:
10318     case Intrinsic::aarch64_neon_ld1x3:
10319     case Intrinsic::aarch64_neon_ld1x4:
10320     case Intrinsic::aarch64_neon_ld2lane:
10321     case Intrinsic::aarch64_neon_ld3lane:
10322     case Intrinsic::aarch64_neon_ld4lane:
10323     case Intrinsic::aarch64_neon_ld2r:
10324     case Intrinsic::aarch64_neon_ld3r:
10325     case Intrinsic::aarch64_neon_ld4r:
10326     case Intrinsic::aarch64_neon_st2:
10327     case Intrinsic::aarch64_neon_st3:
10328     case Intrinsic::aarch64_neon_st4:
10329     case Intrinsic::aarch64_neon_st1x2:
10330     case Intrinsic::aarch64_neon_st1x3:
10331     case Intrinsic::aarch64_neon_st1x4:
10332     case Intrinsic::aarch64_neon_st2lane:
10333     case Intrinsic::aarch64_neon_st3lane:
10334     case Intrinsic::aarch64_neon_st4lane:
10335       return performNEONPostLDSTCombine(N, DCI, DAG);
10336     default:
10337       break;
10338     }
10339   }
10340   return SDValue();
10341 }
10342
10343 // Check if the return value is used as only a return value, as otherwise
10344 // we can't perform a tail-call. In particular, we need to check for
10345 // target ISD nodes that are returns and any other "odd" constructs
10346 // that the generic analysis code won't necessarily catch.
10347 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10348                                                SDValue &Chain) const {
10349   if (N->getNumValues() != 1)
10350     return false;
10351   if (!N->hasNUsesOfValue(1, 0))
10352     return false;
10353
10354   SDValue TCChain = Chain;
10355   SDNode *Copy = *N->use_begin();
10356   if (Copy->getOpcode() == ISD::CopyToReg) {
10357     // If the copy has a glue operand, we conservatively assume it isn't safe to
10358     // perform a tail call.
10359     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10360         MVT::Glue)
10361       return false;
10362     TCChain = Copy->getOperand(0);
10363   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10364     return false;
10365
10366   bool HasRet = false;
10367   for (SDNode *Node : Copy->uses()) {
10368     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10369       return false;
10370     HasRet = true;
10371   }
10372
10373   if (!HasRet)
10374     return false;
10375
10376   Chain = TCChain;
10377   return true;
10378 }
10379
10380 // Return whether the an instruction can potentially be optimized to a tail
10381 // call. This will cause the optimizers to attempt to move, or duplicate,
10382 // return instructions to help enable tail call optimizations for this
10383 // instruction.
10384 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10385   return CI->isTailCall();
10386 }
10387
10388 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10389                                                    SDValue &Offset,
10390                                                    ISD::MemIndexedMode &AM,
10391                                                    bool &IsInc,
10392                                                    SelectionDAG &DAG) const {
10393   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10394     return false;
10395
10396   Base = Op->getOperand(0);
10397   // All of the indexed addressing mode instructions take a signed
10398   // 9 bit immediate offset.
10399   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10400     int64_t RHSC = RHS->getSExtValue();
10401     if (Op->getOpcode() == ISD::SUB)
10402       RHSC = -(uint64_t)RHSC;
10403     if (!isInt<9>(RHSC))
10404       return false;
10405     IsInc = (Op->getOpcode() == ISD::ADD);
10406     Offset = Op->getOperand(1);
10407     return true;
10408   }
10409   return false;
10410 }
10411
10412 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10413                                                       SDValue &Offset,
10414                                                       ISD::MemIndexedMode &AM,
10415                                                       SelectionDAG &DAG) const {
10416   EVT VT;
10417   SDValue Ptr;
10418   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10419     VT = LD->getMemoryVT();
10420     Ptr = LD->getBasePtr();
10421   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10422     VT = ST->getMemoryVT();
10423     Ptr = ST->getBasePtr();
10424   } else
10425     return false;
10426
10427   bool IsInc;
10428   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10429     return false;
10430   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10431   return true;
10432 }
10433
10434 bool AArch64TargetLowering::getPostIndexedAddressParts(
10435     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10436     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10437   EVT VT;
10438   SDValue Ptr;
10439   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10440     VT = LD->getMemoryVT();
10441     Ptr = LD->getBasePtr();
10442   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10443     VT = ST->getMemoryVT();
10444     Ptr = ST->getBasePtr();
10445   } else
10446     return false;
10447
10448   bool IsInc;
10449   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10450     return false;
10451   // Post-indexing updates the base, so it's not a valid transform
10452   // if that's not the same as the load's pointer.
10453   if (Ptr != Base)
10454     return false;
10455   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10456   return true;
10457 }
10458
10459 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10460                                   SelectionDAG &DAG) {
10461   SDLoc DL(N);
10462   SDValue Op = N->getOperand(0);
10463
10464   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10465     return;
10466
10467   Op = SDValue(
10468       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10469                          DAG.getUNDEF(MVT::i32), Op,
10470                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10471       0);
10472   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10473   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10474 }
10475
10476 static void ReplaceReductionResults(SDNode *N,
10477                                     SmallVectorImpl<SDValue> &Results,
10478                                     SelectionDAG &DAG, unsigned InterOp,
10479                                     unsigned AcrossOp) {
10480   EVT LoVT, HiVT;
10481   SDValue Lo, Hi;
10482   SDLoc dl(N);
10483   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10484   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10485   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10486   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10487   Results.push_back(SplitVal);
10488 }
10489
10490 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10491   SDLoc DL(N);
10492   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10493   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10494                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10495                                        DAG.getConstant(64, DL, MVT::i64)));
10496   return std::make_pair(Lo, Hi);
10497 }
10498
10499 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10500                                        SmallVectorImpl<SDValue> & Results,
10501                                        SelectionDAG &DAG) {
10502   assert(N->getValueType(0) == MVT::i128 &&
10503          "AtomicCmpSwap on types less than 128 should be legal");
10504   auto Desired = splitInt128(N->getOperand(2), DAG);
10505   auto New = splitInt128(N->getOperand(3), DAG);
10506   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10507                    New.first,        New.second,    N->getOperand(0)};
10508   SDNode *CmpSwap = DAG.getMachineNode(
10509       AArch64::CMP_SWAP_128, SDLoc(N),
10510       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10511
10512   MachineFunction &MF = DAG.getMachineFunction();
10513   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10514   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10515   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10516
10517   Results.push_back(SDValue(CmpSwap, 0));
10518   Results.push_back(SDValue(CmpSwap, 1));
10519   Results.push_back(SDValue(CmpSwap, 3));
10520 }
10521
10522 void AArch64TargetLowering::ReplaceNodeResults(
10523     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10524   switch (N->getOpcode()) {
10525   default:
10526     llvm_unreachable("Don't know how to custom expand this");
10527   case ISD::BITCAST:
10528     ReplaceBITCASTResults(N, Results, DAG);
10529     return;
10530   case ISD::VECREDUCE_ADD:
10531   case ISD::VECREDUCE_SMAX:
10532   case ISD::VECREDUCE_SMIN:
10533   case ISD::VECREDUCE_UMAX:
10534   case ISD::VECREDUCE_UMIN:
10535     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10536     return;
10537
10538   case AArch64ISD::SADDV:
10539     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10540     return;
10541   case AArch64ISD::UADDV:
10542     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10543     return;
10544   case AArch64ISD::SMINV:
10545     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10546     return;
10547   case AArch64ISD::UMINV:
10548     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10549     return;
10550   case AArch64ISD::SMAXV:
10551     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10552     return;
10553   case AArch64ISD::UMAXV:
10554     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10555     return;
10556   case ISD::FP_TO_UINT:
10557   case ISD::FP_TO_SINT:
10558     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10559     // Let normal code take care of it by not adding anything to Results.
10560     return;
10561   case ISD::ATOMIC_CMP_SWAP:
10562     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10563     return;
10564   }
10565 }
10566
10567 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10568   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10569     return TargetLowering::useLoadStackGuardNode();
10570   return true;
10571 }
10572
10573 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10574   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10575   // reciprocal if there are three or more FDIVs.
10576   return 3;
10577 }
10578
10579 TargetLoweringBase::LegalizeTypeAction
10580 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10581   MVT SVT = VT.getSimpleVT();
10582   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10583   // v4i16, v2i32 instead of to promote.
10584   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10585       || SVT == MVT::v1f32)
10586     return TypeWidenVector;
10587
10588   return TargetLoweringBase::getPreferredVectorAction(VT);
10589 }
10590
10591 // Loads and stores less than 128-bits are already atomic; ones above that
10592 // are doomed anyway, so defer to the default libcall and blame the OS when
10593 // things go wrong.
10594 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10595   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10596   return Size == 128;
10597 }
10598
10599 // Loads and stores less than 128-bits are already atomic; ones above that
10600 // are doomed anyway, so defer to the default libcall and blame the OS when
10601 // things go wrong.
10602 TargetLowering::AtomicExpansionKind
10603 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10604   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10605   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10606 }
10607
10608 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10609 TargetLowering::AtomicExpansionKind
10610 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10611   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10612   if (Size > 128) return AtomicExpansionKind::None;
10613   // Nand not supported in LSE.
10614   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
10615   // Leave 128 bits to LLSC.
10616   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
10617 }
10618
10619 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10620     AtomicCmpXchgInst *AI) const {
10621   // If subtarget has LSE, leave cmpxchg intact for codegen.
10622   if (Subtarget->hasLSE()) return false;
10623   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10624   // implement cmpxchg without spilling. If the address being exchanged is also
10625   // on the stack and close enough to the spill slot, this can lead to a
10626   // situation where the monitor always gets cleared and the atomic operation
10627   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10628   return getTargetMachine().getOptLevel() != 0;
10629 }
10630
10631 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10632                                              AtomicOrdering Ord) const {
10633   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10634   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10635   bool IsAcquire = isAcquireOrStronger(Ord);
10636
10637   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10638   // intrinsic must return {i64, i64} and we have to recombine them into a
10639   // single i128 here.
10640   if (ValTy->getPrimitiveSizeInBits() == 128) {
10641     Intrinsic::ID Int =
10642         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10643     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10644
10645     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10646     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10647
10648     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10649     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10650     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10651     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10652     return Builder.CreateOr(
10653         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10654   }
10655
10656   Type *Tys[] = { Addr->getType() };
10657   Intrinsic::ID Int =
10658       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10659   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10660
10661   return Builder.CreateTruncOrBitCast(
10662       Builder.CreateCall(Ldxr, Addr),
10663       cast<PointerType>(Addr->getType())->getElementType());
10664 }
10665
10666 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10667     IRBuilder<> &Builder) const {
10668   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10669   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10670 }
10671
10672 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10673                                                    Value *Val, Value *Addr,
10674                                                    AtomicOrdering Ord) const {
10675   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10676   bool IsRelease = isReleaseOrStronger(Ord);
10677
10678   // Since the intrinsics must have legal type, the i128 intrinsics take two
10679   // parameters: "i64, i64". We must marshal Val into the appropriate form
10680   // before the call.
10681   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10682     Intrinsic::ID Int =
10683         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10684     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10685     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10686
10687     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10688     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10689     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10690     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10691   }
10692
10693   Intrinsic::ID Int =
10694       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10695   Type *Tys[] = { Addr->getType() };
10696   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10697
10698   return Builder.CreateCall(Stxr,
10699                             {Builder.CreateZExtOrBitCast(
10700                                  Val, Stxr->getFunctionType()->getParamType(0)),
10701                              Addr});
10702 }
10703
10704 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10705     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10706   return Ty->isArrayTy();
10707 }
10708
10709 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10710                                                             EVT) const {
10711   return false;
10712 }
10713
10714 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10715   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10716   Function *ThreadPointerFunc =
10717       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10718   return IRB.CreatePointerCast(
10719       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10720       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10721 }
10722
10723 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10724   // Android provides a fixed TLS slot for the stack cookie. See the definition
10725   // of TLS_SLOT_STACK_GUARD in
10726   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10727   if (Subtarget->isTargetAndroid())
10728     return UseTlsOffset(IRB, 0x28);
10729
10730   // Fuchsia is similar.
10731   // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10732   if (Subtarget->isTargetFuchsia())
10733     return UseTlsOffset(IRB, -0x10);
10734
10735   return TargetLowering::getIRStackGuard(IRB);
10736 }
10737
10738 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10739   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10740   // definition of TLS_SLOT_SAFESTACK in
10741   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10742   if (Subtarget->isTargetAndroid())
10743     return UseTlsOffset(IRB, 0x48);
10744
10745   // Fuchsia is similar.
10746   // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10747   if (Subtarget->isTargetFuchsia())
10748     return UseTlsOffset(IRB, -0x8);
10749
10750   return TargetLowering::getSafeStackPointerLocation(IRB);
10751 }
10752
10753 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10754     const Instruction &AndI) const {
10755   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10756   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
10757   // may be beneficial to sink in other cases, but we would have to check that
10758   // the cmp would not get folded into the br to form a cbz for these to be
10759   // beneficial.
10760   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10761   if (!Mask)
10762     return false;
10763   return Mask->getUniqueInteger().isPowerOf2();
10764 }
10765
10766 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10767   // Update IsSplitCSR in AArch64unctionInfo.
10768   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10769   AFI->setIsSplitCSR(true);
10770 }
10771
10772 void AArch64TargetLowering::insertCopiesSplitCSR(
10773     MachineBasicBlock *Entry,
10774     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10775   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10776   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10777   if (!IStart)
10778     return;
10779
10780   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10781   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10782   MachineBasicBlock::iterator MBBI = Entry->begin();
10783   for (const MCPhysReg *I = IStart; *I; ++I) {
10784     const TargetRegisterClass *RC = nullptr;
10785     if (AArch64::GPR64RegClass.contains(*I))
10786       RC = &AArch64::GPR64RegClass;
10787     else if (AArch64::FPR64RegClass.contains(*I))
10788       RC = &AArch64::FPR64RegClass;
10789     else
10790       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10791
10792     unsigned NewVR = MRI->createVirtualRegister(RC);
10793     // Create copy from CSR to a virtual register.
10794     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10795     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10796     // nounwind. If we want to generalize this later, we may need to emit
10797     // CFI pseudo-instructions.
10798     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10799                Attribute::NoUnwind) &&
10800            "Function should be nounwind in insertCopiesSplitCSR!");
10801     Entry->addLiveIn(*I);
10802     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10803         .addReg(*I);
10804
10805     // Insert the copy-back instructions right before the terminator.
10806     for (auto *Exit : Exits)
10807       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10808               TII->get(TargetOpcode::COPY), *I)
10809           .addReg(NewVR);
10810   }
10811 }
10812
10813 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10814   // Integer division on AArch64 is expensive. However, when aggressively
10815   // optimizing for code size, we prefer to use a div instruction, as it is
10816   // usually smaller than the alternative sequence.
10817   // The exception to this is vector division. Since AArch64 doesn't have vector
10818   // integer division, leaving the division as-is is a loss even in terms of
10819   // size, because it will have to be scalarized, while the alternative code
10820   // sequence can be performed in vector form.
10821   bool OptSize =
10822       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10823   return OptSize && !VT.isVector();
10824 }
10825
10826 unsigned
10827 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10828   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
10829     return getPointerTy(DL).getSizeInBits();
10830
10831   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
10832 }