]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Merge compiler-rt trunk r291476.
[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 "AArch64CallingConvention.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64ISelLowering.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/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.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/CodeGen/CallingConvLower.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/MachineValueType.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/ValueTypes.h"
45 #include "llvm/IR/Attributes.h"
46 #include "llvm/IR/Constants.h"
47 #include "llvm/IR/DataLayout.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/GetElementPtrTypeIterator.h"
52 #include "llvm/IR/GlobalValue.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/OperandTraits.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Use.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/MC/MCRegisterInfo.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CodeGen.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Compiler.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Target/TargetCallingConv.h"
72 #include "llvm/Target/TargetInstrInfo.h"
73 #include "llvm/Target/TargetMachine.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <algorithm>
76 #include <bitset>
77 #include <cassert>
78 #include <cctype>
79 #include <cstdint>
80 #include <cstdlib>
81 #include <iterator>
82 #include <limits>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86
87 using namespace llvm;
88
89 #define DEBUG_TYPE "aarch64-lower"
90
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
93
94 static cl::opt<bool>
95 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
96                            cl::desc("Allow AArch64 SLI/SRI formation"),
97                            cl::init(false));
98
99 // FIXME: The necessary dtprel relocations don't seem to be supported
100 // well in the GNU bfd and gold linkers at the moment. Therefore, by
101 // default, for now, fall back to GeneralDynamic code generation.
102 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
103     "aarch64-elf-ldtls-generation", cl::Hidden,
104     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
105     cl::init(false));
106
107 /// Value type used for condition codes.
108 static const MVT MVT_CC = MVT::i32;
109
110 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
111                                              const AArch64Subtarget &STI)
112     : TargetLowering(TM), Subtarget(&STI) {
113   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
114   // we have to make something up. Arbitrarily, choose ZeroOrOne.
115   setBooleanContents(ZeroOrOneBooleanContent);
116   // When comparing vectors the result sets the different elements in the
117   // vector to all-one or all-zero.
118   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
119
120   // Set up the register classes.
121   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
122   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
123
124   if (Subtarget->hasFPARMv8()) {
125     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
126     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
127     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
128     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
129   }
130
131   if (Subtarget->hasNEON()) {
132     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
133     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
134     // Someone set us up the NEON.
135     addDRTypeForNEON(MVT::v2f32);
136     addDRTypeForNEON(MVT::v8i8);
137     addDRTypeForNEON(MVT::v4i16);
138     addDRTypeForNEON(MVT::v2i32);
139     addDRTypeForNEON(MVT::v1i64);
140     addDRTypeForNEON(MVT::v1f64);
141     addDRTypeForNEON(MVT::v4f16);
142
143     addQRTypeForNEON(MVT::v4f32);
144     addQRTypeForNEON(MVT::v2f64);
145     addQRTypeForNEON(MVT::v16i8);
146     addQRTypeForNEON(MVT::v8i16);
147     addQRTypeForNEON(MVT::v4i32);
148     addQRTypeForNEON(MVT::v2i64);
149     addQRTypeForNEON(MVT::v8f16);
150   }
151
152   // Compute derived properties from the register classes
153   computeRegisterProperties(Subtarget->getRegisterInfo());
154
155   // Provide all sorts of operation actions
156   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
157   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
158   setOperationAction(ISD::SETCC, MVT::i32, Custom);
159   setOperationAction(ISD::SETCC, MVT::i64, Custom);
160   setOperationAction(ISD::SETCC, MVT::f32, Custom);
161   setOperationAction(ISD::SETCC, MVT::f64, Custom);
162   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
163   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
164   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
165   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
167   setOperationAction(ISD::SELECT, MVT::i32, Custom);
168   setOperationAction(ISD::SELECT, MVT::i64, Custom);
169   setOperationAction(ISD::SELECT, MVT::f32, Custom);
170   setOperationAction(ISD::SELECT, MVT::f64, Custom);
171   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
172   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
173   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
174   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
175   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
176   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
177
178   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
179   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
180   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
181
182   setOperationAction(ISD::FREM, MVT::f32, Expand);
183   setOperationAction(ISD::FREM, MVT::f64, Expand);
184   setOperationAction(ISD::FREM, MVT::f80, Expand);
185
186   // Custom lowering hooks are needed for XOR
187   // to fold it into CSINC/CSINV.
188   setOperationAction(ISD::XOR, MVT::i32, Custom);
189   setOperationAction(ISD::XOR, MVT::i64, Custom);
190
191   // Virtually no operation on f128 is legal, but LLVM can't expand them when
192   // there's a valid register class, so we need custom operations in most cases.
193   setOperationAction(ISD::FABS, MVT::f128, Expand);
194   setOperationAction(ISD::FADD, MVT::f128, Custom);
195   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
196   setOperationAction(ISD::FCOS, MVT::f128, Expand);
197   setOperationAction(ISD::FDIV, MVT::f128, Custom);
198   setOperationAction(ISD::FMA, MVT::f128, Expand);
199   setOperationAction(ISD::FMUL, MVT::f128, Custom);
200   setOperationAction(ISD::FNEG, MVT::f128, Expand);
201   setOperationAction(ISD::FPOW, MVT::f128, Expand);
202   setOperationAction(ISD::FREM, MVT::f128, Expand);
203   setOperationAction(ISD::FRINT, MVT::f128, Expand);
204   setOperationAction(ISD::FSIN, MVT::f128, Expand);
205   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
206   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
207   setOperationAction(ISD::FSUB, MVT::f128, Custom);
208   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
209   setOperationAction(ISD::SETCC, MVT::f128, Custom);
210   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
211   setOperationAction(ISD::SELECT, MVT::f128, Custom);
212   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
213   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
214
215   // Lowering for many of the conversions is actually specified by the non-f128
216   // type. The LowerXXX function will be trivial when f128 isn't involved.
217   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
218   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
219   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
220   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
221   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
222   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
223   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
224   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
225   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
226   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
227   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
228   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
229   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
230   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
231
232   // Variable arguments.
233   setOperationAction(ISD::VASTART, MVT::Other, Custom);
234   setOperationAction(ISD::VAARG, MVT::Other, Custom);
235   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
236   setOperationAction(ISD::VAEND, MVT::Other, Expand);
237
238   // Variable-sized objects.
239   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
240   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
241   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
242
243   // Constant pool entries
244   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
245
246   // BlockAddress
247   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
248
249   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
250   setOperationAction(ISD::ADDC, MVT::i32, Custom);
251   setOperationAction(ISD::ADDE, MVT::i32, Custom);
252   setOperationAction(ISD::SUBC, MVT::i32, Custom);
253   setOperationAction(ISD::SUBE, MVT::i32, Custom);
254   setOperationAction(ISD::ADDC, MVT::i64, Custom);
255   setOperationAction(ISD::ADDE, MVT::i64, Custom);
256   setOperationAction(ISD::SUBC, MVT::i64, Custom);
257   setOperationAction(ISD::SUBE, MVT::i64, Custom);
258
259   // AArch64 lacks both left-rotate and popcount instructions.
260   setOperationAction(ISD::ROTL, MVT::i32, Expand);
261   setOperationAction(ISD::ROTL, MVT::i64, Expand);
262   for (MVT VT : MVT::vector_valuetypes()) {
263     setOperationAction(ISD::ROTL, VT, Expand);
264     setOperationAction(ISD::ROTR, VT, Expand);
265   }
266
267   // AArch64 doesn't have {U|S}MUL_LOHI.
268   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
269   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
270
271   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
272   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
273
274   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
275   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
276   for (MVT VT : MVT::vector_valuetypes()) {
277     setOperationAction(ISD::SDIVREM, VT, Expand);
278     setOperationAction(ISD::UDIVREM, VT, Expand);
279   }
280   setOperationAction(ISD::SREM, MVT::i32, Expand);
281   setOperationAction(ISD::SREM, MVT::i64, Expand);
282   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
283   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
284   setOperationAction(ISD::UREM, MVT::i32, Expand);
285   setOperationAction(ISD::UREM, MVT::i64, Expand);
286
287   // Custom lower Add/Sub/Mul with overflow.
288   setOperationAction(ISD::SADDO, MVT::i32, Custom);
289   setOperationAction(ISD::SADDO, MVT::i64, Custom);
290   setOperationAction(ISD::UADDO, MVT::i32, Custom);
291   setOperationAction(ISD::UADDO, MVT::i64, Custom);
292   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
293   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
294   setOperationAction(ISD::USUBO, MVT::i32, Custom);
295   setOperationAction(ISD::USUBO, MVT::i64, Custom);
296   setOperationAction(ISD::SMULO, MVT::i32, Custom);
297   setOperationAction(ISD::SMULO, MVT::i64, Custom);
298   setOperationAction(ISD::UMULO, MVT::i32, Custom);
299   setOperationAction(ISD::UMULO, MVT::i64, Custom);
300
301   setOperationAction(ISD::FSIN, MVT::f32, Expand);
302   setOperationAction(ISD::FSIN, MVT::f64, Expand);
303   setOperationAction(ISD::FCOS, MVT::f32, Expand);
304   setOperationAction(ISD::FCOS, MVT::f64, Expand);
305   setOperationAction(ISD::FPOW, MVT::f32, Expand);
306   setOperationAction(ISD::FPOW, MVT::f64, Expand);
307   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
308   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
309
310   // f16 is a storage-only type, always promote it to f32.
311   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
312   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
313   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
314   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
315   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
316   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
317   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
318   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
319   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
320   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
321   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
322   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
323   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
324   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
325   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
326   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
327   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
328   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
329   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
330   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
331   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
332   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
333   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
334   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
335   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
336   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
337   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
338   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
339   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
340   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
341   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
342   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
343   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
344   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
345
346   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
347   // known to be safe.
348   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
349   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
350   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
351   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
352   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
353   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
354   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
355   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
356   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
357   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
358   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
359   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
360
361   // Expand all other v4f16 operations.
362   // FIXME: We could generate better code by promoting some operations to
363   // a pair of v4f32s
364   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
365   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
366   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
367   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
368   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
369   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
370   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
371   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
372   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
373   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
374   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
375   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
376   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
377   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
378   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
379   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
380   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
381   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
382   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
383   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
384   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
385   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
386   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
387   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
388   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
389   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
390
391
392   // v8f16 is also a storage-only type, so expand it.
393   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
394   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
395   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
396   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
397   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
398   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
399   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
400   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
401   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
402   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
403   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
404   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
405   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
406   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
407   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
408   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
409   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
410   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
411   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
412   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
413   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
414   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
415   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
416   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
417   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
418   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
419   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
420   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
421   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
422   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
423   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
424
425   // AArch64 has implementations of a lot of rounding-like FP operations.
426   for (MVT Ty : {MVT::f32, MVT::f64}) {
427     setOperationAction(ISD::FFLOOR, Ty, Legal);
428     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
429     setOperationAction(ISD::FCEIL, Ty, Legal);
430     setOperationAction(ISD::FRINT, Ty, Legal);
431     setOperationAction(ISD::FTRUNC, Ty, Legal);
432     setOperationAction(ISD::FROUND, Ty, Legal);
433     setOperationAction(ISD::FMINNUM, Ty, Legal);
434     setOperationAction(ISD::FMAXNUM, Ty, Legal);
435     setOperationAction(ISD::FMINNAN, Ty, Legal);
436     setOperationAction(ISD::FMAXNAN, Ty, Legal);
437   }
438
439   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
440
441   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
442
443   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
444   // This requires the Performance Monitors extension.
445   if (Subtarget->hasPerfMon())
446     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447
448   if (Subtarget->isTargetMachO()) {
449     // For iOS, we don't want to the normal expansion of a libcall to
450     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
451     // traffic.
452     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
453     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
454   } else {
455     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
456     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
457   }
458
459   // Make floating-point constants legal for the large code model, so they don't
460   // become loads from the constant pool.
461   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
462     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
463     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
464   }
465
466   // AArch64 does not have floating-point extending loads, i1 sign-extending
467   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
468   for (MVT VT : MVT::fp_valuetypes()) {
469     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
470     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
471     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
472     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
473   }
474   for (MVT VT : MVT::integer_valuetypes())
475     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
476
477   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
478   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
479   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
480   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
481   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
482   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
483   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
484
485   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
486   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
487
488   // Indexed loads and stores are supported.
489   for (unsigned im = (unsigned)ISD::PRE_INC;
490        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
491     setIndexedLoadAction(im, MVT::i8, Legal);
492     setIndexedLoadAction(im, MVT::i16, Legal);
493     setIndexedLoadAction(im, MVT::i32, Legal);
494     setIndexedLoadAction(im, MVT::i64, Legal);
495     setIndexedLoadAction(im, MVT::f64, Legal);
496     setIndexedLoadAction(im, MVT::f32, Legal);
497     setIndexedLoadAction(im, MVT::f16, Legal);
498     setIndexedStoreAction(im, MVT::i8, Legal);
499     setIndexedStoreAction(im, MVT::i16, Legal);
500     setIndexedStoreAction(im, MVT::i32, Legal);
501     setIndexedStoreAction(im, MVT::i64, Legal);
502     setIndexedStoreAction(im, MVT::f64, Legal);
503     setIndexedStoreAction(im, MVT::f32, Legal);
504     setIndexedStoreAction(im, MVT::f16, Legal);
505   }
506
507   // Trap.
508   setOperationAction(ISD::TRAP, MVT::Other, Legal);
509
510   // We combine OR nodes for bitfield operations.
511   setTargetDAGCombine(ISD::OR);
512
513   // Vector add and sub nodes may conceal a high-half opportunity.
514   // Also, try to fold ADD into CSINC/CSINV..
515   setTargetDAGCombine(ISD::ADD);
516   setTargetDAGCombine(ISD::SUB);
517   setTargetDAGCombine(ISD::SRL);
518   setTargetDAGCombine(ISD::XOR);
519   setTargetDAGCombine(ISD::SINT_TO_FP);
520   setTargetDAGCombine(ISD::UINT_TO_FP);
521
522   setTargetDAGCombine(ISD::FP_TO_SINT);
523   setTargetDAGCombine(ISD::FP_TO_UINT);
524   setTargetDAGCombine(ISD::FDIV);
525
526   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
527
528   setTargetDAGCombine(ISD::ANY_EXTEND);
529   setTargetDAGCombine(ISD::ZERO_EXTEND);
530   setTargetDAGCombine(ISD::SIGN_EXTEND);
531   setTargetDAGCombine(ISD::BITCAST);
532   setTargetDAGCombine(ISD::CONCAT_VECTORS);
533   setTargetDAGCombine(ISD::STORE);
534   if (Subtarget->supportsAddressTopByteIgnored())
535     setTargetDAGCombine(ISD::LOAD);
536
537   setTargetDAGCombine(ISD::MUL);
538
539   setTargetDAGCombine(ISD::SELECT);
540   setTargetDAGCombine(ISD::VSELECT);
541
542   setTargetDAGCombine(ISD::INTRINSIC_VOID);
543   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
544   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
545   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
546
547   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
548   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
549   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
550
551   setStackPointerRegisterToSaveRestore(AArch64::SP);
552
553   setSchedulingPreference(Sched::Hybrid);
554
555   // Enable TBZ/TBNZ
556   MaskAndBranchFoldingIsLegal = true;
557   EnableExtLdPromotion = true;
558
559   // Set required alignment.
560   setMinFunctionAlignment(2);
561   // Set preferred alignments.
562   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
563   setPrefLoopAlignment(STI.getPrefLoopAlignment());
564
565   // Only change the limit for entries in a jump table if specified by
566   // the subtarget, but not at the command line.
567   unsigned MaxJT = STI.getMaximumJumpTableSize();
568   if (MaxJT && getMaximumJumpTableSize() == 0)
569     setMaximumJumpTableSize(MaxJT);
570
571   setHasExtractBitsInsn(true);
572
573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
574
575   if (Subtarget->hasNEON()) {
576     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
577     // silliness like this:
578     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
579     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
580     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
581     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
582     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
583     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
584     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
585     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
586     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
587     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
588     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
589     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
590     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
591     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
592     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
593     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
594     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
595     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
596     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
597     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
598     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
599     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
600     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
601     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
602     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
603
604     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
605     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
606     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
607     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
608     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
609
610     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
611
612     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
613     // elements smaller than i32, so promote the input to i32 first.
614     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
615     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
616     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
617     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
618     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
619     // -> v8f16 conversions.
620     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
621     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
622     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
623     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
624     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
625     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
626     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
627     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
628     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
629     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
630     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
631     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
632     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
633
634     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
635     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
636
637     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
638     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
639     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
640     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
641     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
642     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
643     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
644     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
645
646     // AArch64 doesn't have MUL.2d:
647     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
648     // Custom handling for some quad-vector types to detect MULL.
649     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
650     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
651     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
652
653     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
654     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
655     // Likewise, narrowing and extending vector loads/stores aren't handled
656     // directly.
657     for (MVT VT : MVT::vector_valuetypes()) {
658       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
659
660       setOperationAction(ISD::MULHS, VT, Expand);
661       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
662       setOperationAction(ISD::MULHU, VT, Expand);
663       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
664
665       setOperationAction(ISD::BSWAP, VT, Expand);
666
667       for (MVT InnerVT : MVT::vector_valuetypes()) {
668         setTruncStoreAction(VT, InnerVT, Expand);
669         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
670         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
671         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
672       }
673     }
674
675     // AArch64 has implementations of a lot of rounding-like FP operations.
676     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
677       setOperationAction(ISD::FFLOOR, Ty, Legal);
678       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
679       setOperationAction(ISD::FCEIL, Ty, Legal);
680       setOperationAction(ISD::FRINT, Ty, Legal);
681       setOperationAction(ISD::FTRUNC, Ty, Legal);
682       setOperationAction(ISD::FROUND, Ty, Legal);
683     }
684   }
685
686   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
687 }
688
689 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
690   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
691     setOperationAction(ISD::LOAD, VT, Promote);
692     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
693
694     setOperationAction(ISD::STORE, VT, Promote);
695     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
696   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
697     setOperationAction(ISD::LOAD, VT, Promote);
698     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
699
700     setOperationAction(ISD::STORE, VT, Promote);
701     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
702   }
703
704   // Mark vector float intrinsics as expand.
705   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
706     setOperationAction(ISD::FSIN, VT, Expand);
707     setOperationAction(ISD::FCOS, VT, Expand);
708     setOperationAction(ISD::FPOWI, VT, Expand);
709     setOperationAction(ISD::FPOW, VT, Expand);
710     setOperationAction(ISD::FLOG, VT, Expand);
711     setOperationAction(ISD::FLOG2, VT, Expand);
712     setOperationAction(ISD::FLOG10, VT, Expand);
713     setOperationAction(ISD::FEXP, VT, Expand);
714     setOperationAction(ISD::FEXP2, VT, Expand);
715
716     // But we do support custom-lowering for FCOPYSIGN.
717     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
718   }
719
720   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
721   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
722   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
723   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
724   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
725   setOperationAction(ISD::SRA, VT, Custom);
726   setOperationAction(ISD::SRL, VT, Custom);
727   setOperationAction(ISD::SHL, VT, Custom);
728   setOperationAction(ISD::AND, VT, Custom);
729   setOperationAction(ISD::OR, VT, Custom);
730   setOperationAction(ISD::SETCC, VT, Custom);
731   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
732
733   setOperationAction(ISD::SELECT, VT, Expand);
734   setOperationAction(ISD::SELECT_CC, VT, Expand);
735   setOperationAction(ISD::VSELECT, VT, Expand);
736   for (MVT InnerVT : MVT::all_valuetypes())
737     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
738
739   // CNT supports only B element sizes.
740   if (VT != MVT::v8i8 && VT != MVT::v16i8)
741     setOperationAction(ISD::CTPOP, VT, Expand);
742
743   setOperationAction(ISD::UDIV, VT, Expand);
744   setOperationAction(ISD::SDIV, VT, Expand);
745   setOperationAction(ISD::UREM, VT, Expand);
746   setOperationAction(ISD::SREM, VT, Expand);
747   setOperationAction(ISD::FREM, VT, Expand);
748
749   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
750   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
751
752   // [SU][MIN|MAX] are available for all NEON types apart from i64.
753   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
754     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
755       setOperationAction(Opcode, VT, Legal);
756
757   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
758   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
759     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
760                             ISD::FMINNUM, ISD::FMAXNUM})
761       setOperationAction(Opcode, VT, Legal);
762
763   if (Subtarget->isLittleEndian()) {
764     for (unsigned im = (unsigned)ISD::PRE_INC;
765          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
766       setIndexedLoadAction(im, VT, Legal);
767       setIndexedStoreAction(im, VT, Legal);
768     }
769   }
770 }
771
772 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
773   addRegisterClass(VT, &AArch64::FPR64RegClass);
774   addTypeForNEON(VT, MVT::v2i32);
775 }
776
777 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
778   addRegisterClass(VT, &AArch64::FPR128RegClass);
779   addTypeForNEON(VT, MVT::v4i32);
780 }
781
782 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
783                                               EVT VT) const {
784   if (!VT.isVector())
785     return MVT::i32;
786   return VT.changeVectorElementTypeToInteger();
787 }
788
789 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
790 /// Mask are known to be either zero or one and return them in the
791 /// KnownZero/KnownOne bitsets.
792 void AArch64TargetLowering::computeKnownBitsForTargetNode(
793     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
794     const SelectionDAG &DAG, unsigned Depth) const {
795   switch (Op.getOpcode()) {
796   default:
797     break;
798   case AArch64ISD::CSEL: {
799     APInt KnownZero2, KnownOne2;
800     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
801     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
802     KnownZero &= KnownZero2;
803     KnownOne &= KnownOne2;
804     break;
805   }
806   case ISD::INTRINSIC_W_CHAIN: {
807     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
808     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
809     switch (IntID) {
810     default: return;
811     case Intrinsic::aarch64_ldaxr:
812     case Intrinsic::aarch64_ldxr: {
813       unsigned BitWidth = KnownOne.getBitWidth();
814       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
815       unsigned MemBits = VT.getScalarSizeInBits();
816       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
817       return;
818     }
819     }
820     break;
821   }
822   case ISD::INTRINSIC_WO_CHAIN:
823   case ISD::INTRINSIC_VOID: {
824     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
825     switch (IntNo) {
826     default:
827       break;
828     case Intrinsic::aarch64_neon_umaxv:
829     case Intrinsic::aarch64_neon_uminv: {
830       // Figure out the datatype of the vector operand. The UMINV instruction
831       // will zero extend the result, so we can mark as known zero all the
832       // bits larger than the element datatype. 32-bit or larget doesn't need
833       // this as those are legal types and will be handled by isel directly.
834       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
835       unsigned BitWidth = KnownZero.getBitWidth();
836       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
837         assert(BitWidth >= 8 && "Unexpected width!");
838         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
839         KnownZero |= Mask;
840       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
841         assert(BitWidth >= 16 && "Unexpected width!");
842         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
843         KnownZero |= Mask;
844       }
845       break;
846     } break;
847     }
848   }
849   }
850 }
851
852 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
853                                                   EVT) const {
854   return MVT::i64;
855 }
856
857 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
858                                                            unsigned AddrSpace,
859                                                            unsigned Align,
860                                                            bool *Fast) const {
861   if (Subtarget->requiresStrictAlign())
862     return false;
863
864   if (Fast) {
865     // Some CPUs are fine with unaligned stores except for 128-bit ones.
866     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
867             // See comments in performSTORECombine() for more details about
868             // these conditions.
869
870             // Code that uses clang vector extensions can mark that it
871             // wants unaligned accesses to be treated as fast by
872             // underspecifying alignment to be 1 or 2.
873             Align <= 2 ||
874
875             // Disregard v2i64. Memcpy lowering produces those and splitting
876             // them regresses performance on micro-benchmarks and olden/bh.
877             VT == MVT::v2i64;
878   }
879   return true;
880 }
881
882 FastISel *
883 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
884                                       const TargetLibraryInfo *libInfo) const {
885   return AArch64::createFastISel(funcInfo, libInfo);
886 }
887
888 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
889   switch ((AArch64ISD::NodeType)Opcode) {
890   case AArch64ISD::FIRST_NUMBER:      break;
891   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
892   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
893   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
894   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
895   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
896   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
897   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
898   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
899   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
900   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
901   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
902   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
903   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
904   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
905   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
906   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
907   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
908   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
909   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
910   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
911   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
912   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
913   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
914   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
915   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
916   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
917   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
918   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
919   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
920   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
921   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
922   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
923   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
924   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
925   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
926   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
927   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
928   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
929   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
930   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
931   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
932   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
933   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
934   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
935   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
936   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
937   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
938   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
939   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
940   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
941   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
942   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
943   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
944   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
945   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
946   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
947   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
948   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
949   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
950   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
951   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
952   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
953   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
954   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
955   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
956   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
957   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
958   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
959   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
960   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
961   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
962   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
963   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
964   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
965   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
966   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
967   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
968   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
969   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
970   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
971   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
972   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
973   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
974   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
975   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
976   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
977   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
978   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
979   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
980   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
981   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
982   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
983   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
984   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
985   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
986   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
987   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
988   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
989   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
990   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
991   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
992   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
993   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
994   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
995   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
996   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
997   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
998   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
999   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1000   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1001   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1002   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1003   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1004   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1005   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1006   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1007   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1008   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1009   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1010   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1011   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1012   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1013   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1014   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1015   }
1016   return nullptr;
1017 }
1018
1019 MachineBasicBlock *
1020 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1021                                     MachineBasicBlock *MBB) const {
1022   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1023   // phi node:
1024
1025   // OrigBB:
1026   //     [... previous instrs leading to comparison ...]
1027   //     b.ne TrueBB
1028   //     b EndBB
1029   // TrueBB:
1030   //     ; Fallthrough
1031   // EndBB:
1032   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1033
1034   MachineFunction *MF = MBB->getParent();
1035   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1036   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1037   DebugLoc DL = MI.getDebugLoc();
1038   MachineFunction::iterator It = ++MBB->getIterator();
1039
1040   unsigned DestReg = MI.getOperand(0).getReg();
1041   unsigned IfTrueReg = MI.getOperand(1).getReg();
1042   unsigned IfFalseReg = MI.getOperand(2).getReg();
1043   unsigned CondCode = MI.getOperand(3).getImm();
1044   bool NZCVKilled = MI.getOperand(4).isKill();
1045
1046   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048   MF->insert(It, TrueBB);
1049   MF->insert(It, EndBB);
1050
1051   // Transfer rest of current basic-block to EndBB
1052   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1053                 MBB->end());
1054   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1055
1056   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1057   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1058   MBB->addSuccessor(TrueBB);
1059   MBB->addSuccessor(EndBB);
1060
1061   // TrueBB falls through to the end.
1062   TrueBB->addSuccessor(EndBB);
1063
1064   if (!NZCVKilled) {
1065     TrueBB->addLiveIn(AArch64::NZCV);
1066     EndBB->addLiveIn(AArch64::NZCV);
1067   }
1068
1069   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1070       .addReg(IfTrueReg)
1071       .addMBB(TrueBB)
1072       .addReg(IfFalseReg)
1073       .addMBB(MBB);
1074
1075   MI.eraseFromParent();
1076   return EndBB;
1077 }
1078
1079 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1080     MachineInstr &MI, MachineBasicBlock *BB) const {
1081   switch (MI.getOpcode()) {
1082   default:
1083 #ifndef NDEBUG
1084     MI.dump();
1085 #endif
1086     llvm_unreachable("Unexpected instruction for custom inserter!");
1087
1088   case AArch64::F128CSEL:
1089     return EmitF128CSEL(MI, BB);
1090
1091   case TargetOpcode::STACKMAP:
1092   case TargetOpcode::PATCHPOINT:
1093     return emitPatchPoint(MI, BB);
1094   }
1095 }
1096
1097 //===----------------------------------------------------------------------===//
1098 // AArch64 Lowering private implementation.
1099 //===----------------------------------------------------------------------===//
1100
1101 //===----------------------------------------------------------------------===//
1102 // Lowering Code
1103 //===----------------------------------------------------------------------===//
1104
1105 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1106 /// CC
1107 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1108   switch (CC) {
1109   default:
1110     llvm_unreachable("Unknown condition code!");
1111   case ISD::SETNE:
1112     return AArch64CC::NE;
1113   case ISD::SETEQ:
1114     return AArch64CC::EQ;
1115   case ISD::SETGT:
1116     return AArch64CC::GT;
1117   case ISD::SETGE:
1118     return AArch64CC::GE;
1119   case ISD::SETLT:
1120     return AArch64CC::LT;
1121   case ISD::SETLE:
1122     return AArch64CC::LE;
1123   case ISD::SETUGT:
1124     return AArch64CC::HI;
1125   case ISD::SETUGE:
1126     return AArch64CC::HS;
1127   case ISD::SETULT:
1128     return AArch64CC::LO;
1129   case ISD::SETULE:
1130     return AArch64CC::LS;
1131   }
1132 }
1133
1134 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1135 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1136                                   AArch64CC::CondCode &CondCode,
1137                                   AArch64CC::CondCode &CondCode2) {
1138   CondCode2 = AArch64CC::AL;
1139   switch (CC) {
1140   default:
1141     llvm_unreachable("Unknown FP condition!");
1142   case ISD::SETEQ:
1143   case ISD::SETOEQ:
1144     CondCode = AArch64CC::EQ;
1145     break;
1146   case ISD::SETGT:
1147   case ISD::SETOGT:
1148     CondCode = AArch64CC::GT;
1149     break;
1150   case ISD::SETGE:
1151   case ISD::SETOGE:
1152     CondCode = AArch64CC::GE;
1153     break;
1154   case ISD::SETOLT:
1155     CondCode = AArch64CC::MI;
1156     break;
1157   case ISD::SETOLE:
1158     CondCode = AArch64CC::LS;
1159     break;
1160   case ISD::SETONE:
1161     CondCode = AArch64CC::MI;
1162     CondCode2 = AArch64CC::GT;
1163     break;
1164   case ISD::SETO:
1165     CondCode = AArch64CC::VC;
1166     break;
1167   case ISD::SETUO:
1168     CondCode = AArch64CC::VS;
1169     break;
1170   case ISD::SETUEQ:
1171     CondCode = AArch64CC::EQ;
1172     CondCode2 = AArch64CC::VS;
1173     break;
1174   case ISD::SETUGT:
1175     CondCode = AArch64CC::HI;
1176     break;
1177   case ISD::SETUGE:
1178     CondCode = AArch64CC::PL;
1179     break;
1180   case ISD::SETLT:
1181   case ISD::SETULT:
1182     CondCode = AArch64CC::LT;
1183     break;
1184   case ISD::SETLE:
1185   case ISD::SETULE:
1186     CondCode = AArch64CC::LE;
1187     break;
1188   case ISD::SETNE:
1189   case ISD::SETUNE:
1190     CondCode = AArch64CC::NE;
1191     break;
1192   }
1193 }
1194
1195 /// Convert a DAG fp condition code to an AArch64 CC.
1196 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1197 /// should be AND'ed instead of OR'ed.
1198 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1199                                      AArch64CC::CondCode &CondCode,
1200                                      AArch64CC::CondCode &CondCode2) {
1201   CondCode2 = AArch64CC::AL;
1202   switch (CC) {
1203   default:
1204     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1205     assert(CondCode2 == AArch64CC::AL);
1206     break;
1207   case ISD::SETONE:
1208     // (a one b)
1209     // == ((a olt b) || (a ogt b))
1210     // == ((a ord b) && (a une b))
1211     CondCode = AArch64CC::VC;
1212     CondCode2 = AArch64CC::NE;
1213     break;
1214   case ISD::SETUEQ:
1215     // (a ueq b)
1216     // == ((a uno b) || (a oeq b))
1217     // == ((a ule b) && (a uge b))
1218     CondCode = AArch64CC::PL;
1219     CondCode2 = AArch64CC::LE;
1220     break;
1221   }
1222 }
1223
1224 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1225 /// CC usable with the vector instructions. Fewer operations are available
1226 /// without a real NZCV register, so we have to use less efficient combinations
1227 /// to get the same effect.
1228 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1229                                         AArch64CC::CondCode &CondCode,
1230                                         AArch64CC::CondCode &CondCode2,
1231                                         bool &Invert) {
1232   Invert = false;
1233   switch (CC) {
1234   default:
1235     // Mostly the scalar mappings work fine.
1236     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1237     break;
1238   case ISD::SETUO:
1239     Invert = true;
1240     LLVM_FALLTHROUGH;
1241   case ISD::SETO:
1242     CondCode = AArch64CC::MI;
1243     CondCode2 = AArch64CC::GE;
1244     break;
1245   case ISD::SETUEQ:
1246   case ISD::SETULT:
1247   case ISD::SETULE:
1248   case ISD::SETUGT:
1249   case ISD::SETUGE:
1250     // All of the compare-mask comparisons are ordered, but we can switch
1251     // between the two by a double inversion. E.g. ULE == !OGT.
1252     Invert = true;
1253     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1254     break;
1255   }
1256 }
1257
1258 static bool isLegalArithImmed(uint64_t C) {
1259   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1260   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1261 }
1262
1263 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1264                               const SDLoc &dl, SelectionDAG &DAG) {
1265   EVT VT = LHS.getValueType();
1266
1267   if (VT.isFloatingPoint()) {
1268     assert(VT != MVT::f128);
1269     if (VT == MVT::f16) {
1270       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1271       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1272       VT = MVT::f32;
1273     }
1274     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1275   }
1276
1277   // The CMP instruction is just an alias for SUBS, and representing it as
1278   // SUBS means that it's possible to get CSE with subtract operations.
1279   // A later phase can perform the optimization of setting the destination
1280   // register to WZR/XZR if it ends up being unused.
1281   unsigned Opcode = AArch64ISD::SUBS;
1282
1283   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1284       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1285     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1286     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1287     // can be set differently by this operation. It comes down to whether
1288     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1289     // everything is fine. If not then the optimization is wrong. Thus general
1290     // comparisons are only valid if op2 != 0.
1291
1292     // So, finally, the only LLVM-native comparisons that don't mention C and V
1293     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1294     // the absence of information about op2.
1295     Opcode = AArch64ISD::ADDS;
1296     RHS = RHS.getOperand(1);
1297   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1298              !isUnsignedIntSetCC(CC)) {
1299     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1300     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1301     // of the signed comparisons.
1302     Opcode = AArch64ISD::ANDS;
1303     RHS = LHS.getOperand(1);
1304     LHS = LHS.getOperand(0);
1305   }
1306
1307   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1308       .getValue(1);
1309 }
1310
1311 /// \defgroup AArch64CCMP CMP;CCMP matching
1312 ///
1313 /// These functions deal with the formation of CMP;CCMP;... sequences.
1314 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1315 /// a comparison. They set the NZCV flags to a predefined value if their
1316 /// predicate is false. This allows to express arbitrary conjunctions, for
1317 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1318 /// expressed as:
1319 ///   cmp A
1320 ///   ccmp B, inv(CB), CA
1321 ///   check for CB flags
1322 ///
1323 /// In general we can create code for arbitrary "... (and (and A B) C)"
1324 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1325 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1326 /// negation operations:
1327 /// We can negate the results of a single comparison by inverting the flags
1328 /// used when the predicate fails and inverting the flags tested in the next
1329 /// instruction; We can also negate the results of the whole previous
1330 /// conditional compare sequence by inverting the flags tested in the next
1331 /// instruction. However there is no way to negate the result of a partial
1332 /// sequence.
1333 ///
1334 /// Therefore on encountering an "or" expression we can negate the subtree on
1335 /// one side and have to be able to push the negate to the leafs of the subtree
1336 /// on the other side (see also the comments in code). As complete example:
1337 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1338 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1339 /// is transformed to
1340 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1341 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1342 /// and implemented as:
1343 ///   cmp C
1344 ///   ccmp D, inv(CD), CC
1345 ///   ccmp A, CA, inv(CD)
1346 ///   ccmp B, CB, inv(CA)
1347 ///   check for CB flags
1348 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1349 /// by conditional compare sequences.
1350 /// @{
1351
1352 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1353 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1354                                          ISD::CondCode CC, SDValue CCOp,
1355                                          AArch64CC::CondCode Predicate,
1356                                          AArch64CC::CondCode OutCC,
1357                                          const SDLoc &DL, SelectionDAG &DAG) {
1358   unsigned Opcode = 0;
1359   if (LHS.getValueType().isFloatingPoint()) {
1360     assert(LHS.getValueType() != MVT::f128);
1361     if (LHS.getValueType() == MVT::f16) {
1362       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1363       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1364     }
1365     Opcode = AArch64ISD::FCCMP;
1366   } else if (RHS.getOpcode() == ISD::SUB) {
1367     SDValue SubOp0 = RHS.getOperand(0);
1368     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1369       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1370       Opcode = AArch64ISD::CCMN;
1371       RHS = RHS.getOperand(1);
1372     }
1373   }
1374   if (Opcode == 0)
1375     Opcode = AArch64ISD::CCMP;
1376
1377   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1378   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1379   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1380   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1381   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1382 }
1383
1384 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1385 /// CanPushNegate is set to true if we can push a negate operation through
1386 /// the tree in a was that we are left with AND operations and negate operations
1387 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1388 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1389 /// brought into such a form.
1390 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1391                                          unsigned Depth = 0) {
1392   if (!Val.hasOneUse())
1393     return false;
1394   unsigned Opcode = Val->getOpcode();
1395   if (Opcode == ISD::SETCC) {
1396     if (Val->getOperand(0).getValueType() == MVT::f128)
1397       return false;
1398     CanNegate = true;
1399     return true;
1400   }
1401   // Protect against exponential runtime and stack overflow.
1402   if (Depth > 6)
1403     return false;
1404   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1405     SDValue O0 = Val->getOperand(0);
1406     SDValue O1 = Val->getOperand(1);
1407     bool CanNegateL;
1408     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1409       return false;
1410     bool CanNegateR;
1411     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1412       return false;
1413
1414     if (Opcode == ISD::OR) {
1415       // For an OR expression we need to be able to negate at least one side or
1416       // we cannot do the transformation at all.
1417       if (!CanNegateL && !CanNegateR)
1418         return false;
1419       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1420       // can negate the x and y subtrees.
1421       CanNegate = CanNegateL && CanNegateR;
1422     } else {
1423       // If the operands are OR expressions then we finally need to negate their
1424       // outputs, we can only do that for the operand with emitted last by
1425       // negating OutCC, not for both operands.
1426       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1427       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1428       if (NeedsNegOutL && NeedsNegOutR)
1429         return false;
1430       // We cannot negate an AND operation (it would become an OR),
1431       CanNegate = false;
1432     }
1433     return true;
1434   }
1435   return false;
1436 }
1437
1438 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1439 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1440 /// Tries to transform the given i1 producing node @p Val to a series compare
1441 /// and conditional compare operations. @returns an NZCV flags producing node
1442 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1443 /// transformation was not possible.
1444 /// On recursive invocations @p PushNegate may be set to true to have negation
1445 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1446 /// for the comparisons in the current subtree; @p Depth limits the search
1447 /// depth to avoid stack overflow.
1448 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1449     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1450     AArch64CC::CondCode Predicate) {
1451   // We're at a tree leaf, produce a conditional comparison operation.
1452   unsigned Opcode = Val->getOpcode();
1453   if (Opcode == ISD::SETCC) {
1454     SDValue LHS = Val->getOperand(0);
1455     SDValue RHS = Val->getOperand(1);
1456     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1457     bool isInteger = LHS.getValueType().isInteger();
1458     if (Negate)
1459       CC = getSetCCInverse(CC, isInteger);
1460     SDLoc DL(Val);
1461     // Determine OutCC and handle FP special case.
1462     if (isInteger) {
1463       OutCC = changeIntCCToAArch64CC(CC);
1464     } else {
1465       assert(LHS.getValueType().isFloatingPoint());
1466       AArch64CC::CondCode ExtraCC;
1467       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1468       // Some floating point conditions can't be tested with a single condition
1469       // code. Construct an additional comparison in this case.
1470       if (ExtraCC != AArch64CC::AL) {
1471         SDValue ExtraCmp;
1472         if (!CCOp.getNode())
1473           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1474         else
1475           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1476                                                ExtraCC, DL, DAG);
1477         CCOp = ExtraCmp;
1478         Predicate = ExtraCC;
1479       }
1480     }
1481
1482     // Produce a normal comparison if we are first in the chain
1483     if (!CCOp)
1484       return emitComparison(LHS, RHS, CC, DL, DAG);
1485     // Otherwise produce a ccmp.
1486     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1487                                      DAG);
1488   }
1489   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1490          "Valid conjunction/disjunction tree");
1491
1492   // Check if both sides can be transformed.
1493   SDValue LHS = Val->getOperand(0);
1494   SDValue RHS = Val->getOperand(1);
1495
1496   // In case of an OR we need to negate our operands and the result.
1497   // (A v B) <=> not(not(A) ^ not(B))
1498   bool NegateOpsAndResult = Opcode == ISD::OR;
1499   // We can negate the results of all previous operations by inverting the
1500   // predicate flags giving us a free negation for one side. The other side
1501   // must be negatable by itself.
1502   if (NegateOpsAndResult) {
1503     // See which side we can negate.
1504     bool CanNegateL;
1505     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1506     assert(isValidL && "Valid conjunction/disjunction tree");
1507     (void)isValidL;
1508
1509 #ifndef NDEBUG
1510     bool CanNegateR;
1511     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1512     assert(isValidR && "Valid conjunction/disjunction tree");
1513     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1514 #endif
1515
1516     // Order the side which we cannot negate to RHS so we can emit it first.
1517     if (!CanNegateL)
1518       std::swap(LHS, RHS);
1519   } else {
1520     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1521     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1522            "Valid conjunction/disjunction tree");
1523     // Order the side where we need to negate the output flags to RHS so it
1524     // gets emitted first.
1525     if (NeedsNegOutL)
1526       std::swap(LHS, RHS);
1527   }
1528
1529   // Emit RHS. If we want to negate the tree we only need to push a negate
1530   // through if we are already in a PushNegate case, otherwise we can negate
1531   // the "flags to test" afterwards.
1532   AArch64CC::CondCode RHSCC;
1533   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1534                                                    CCOp, Predicate);
1535   if (NegateOpsAndResult && !Negate)
1536     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1537   // Emit LHS. We may need to negate it.
1538   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1539                                                    NegateOpsAndResult, CmpR,
1540                                                    RHSCC);
1541   // If we transformed an OR to and AND then we have to negate the result
1542   // (or absorb the Negate parameter).
1543   if (NegateOpsAndResult && !Negate)
1544     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1545   return CmpL;
1546 }
1547
1548 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1549 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1550 /// \see emitConjunctionDisjunctionTreeRec().
1551 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1552                                               AArch64CC::CondCode &OutCC) {
1553   bool CanNegate;
1554   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1555     return SDValue();
1556
1557   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1558                                            AArch64CC::AL);
1559 }
1560
1561 /// @}
1562
1563 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1564                              SDValue &AArch64cc, SelectionDAG &DAG,
1565                              const SDLoc &dl) {
1566   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1567     EVT VT = RHS.getValueType();
1568     uint64_t C = RHSC->getZExtValue();
1569     if (!isLegalArithImmed(C)) {
1570       // Constant does not fit, try adjusting it by one?
1571       switch (CC) {
1572       default:
1573         break;
1574       case ISD::SETLT:
1575       case ISD::SETGE:
1576         if ((VT == MVT::i32 && C != 0x80000000 &&
1577              isLegalArithImmed((uint32_t)(C - 1))) ||
1578             (VT == MVT::i64 && C != 0x80000000ULL &&
1579              isLegalArithImmed(C - 1ULL))) {
1580           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1581           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1582           RHS = DAG.getConstant(C, dl, VT);
1583         }
1584         break;
1585       case ISD::SETULT:
1586       case ISD::SETUGE:
1587         if ((VT == MVT::i32 && C != 0 &&
1588              isLegalArithImmed((uint32_t)(C - 1))) ||
1589             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1590           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1591           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1592           RHS = DAG.getConstant(C, dl, VT);
1593         }
1594         break;
1595       case ISD::SETLE:
1596       case ISD::SETGT:
1597         if ((VT == MVT::i32 && C != INT32_MAX &&
1598              isLegalArithImmed((uint32_t)(C + 1))) ||
1599             (VT == MVT::i64 && C != INT64_MAX &&
1600              isLegalArithImmed(C + 1ULL))) {
1601           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1602           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1603           RHS = DAG.getConstant(C, dl, VT);
1604         }
1605         break;
1606       case ISD::SETULE:
1607       case ISD::SETUGT:
1608         if ((VT == MVT::i32 && C != UINT32_MAX &&
1609              isLegalArithImmed((uint32_t)(C + 1))) ||
1610             (VT == MVT::i64 && C != UINT64_MAX &&
1611              isLegalArithImmed(C + 1ULL))) {
1612           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1613           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1614           RHS = DAG.getConstant(C, dl, VT);
1615         }
1616         break;
1617       }
1618     }
1619   }
1620   SDValue Cmp;
1621   AArch64CC::CondCode AArch64CC;
1622   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1623     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1624
1625     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1626     // For the i8 operand, the largest immediate is 255, so this can be easily
1627     // encoded in the compare instruction. For the i16 operand, however, the
1628     // largest immediate cannot be encoded in the compare.
1629     // Therefore, use a sign extending load and cmn to avoid materializing the
1630     // -1 constant. For example,
1631     // movz w1, #65535
1632     // ldrh w0, [x0, #0]
1633     // cmp w0, w1
1634     // >
1635     // ldrsh w0, [x0, #0]
1636     // cmn w0, #1
1637     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1638     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1639     // ensure both the LHS and RHS are truly zero extended and to make sure the
1640     // transformation is profitable.
1641     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1642         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1643         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1644         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1645       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1646       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1647         SDValue SExt =
1648             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1649                         DAG.getValueType(MVT::i16));
1650         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1651                                                    RHS.getValueType()),
1652                              CC, dl, DAG);
1653         AArch64CC = changeIntCCToAArch64CC(CC);
1654       }
1655     }
1656
1657     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1658       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1659         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1660           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1661       }
1662     }
1663   }
1664
1665   if (!Cmp) {
1666     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1667     AArch64CC = changeIntCCToAArch64CC(CC);
1668   }
1669   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1670   return Cmp;
1671 }
1672
1673 static std::pair<SDValue, SDValue>
1674 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1675   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1676          "Unsupported value type");
1677   SDValue Value, Overflow;
1678   SDLoc DL(Op);
1679   SDValue LHS = Op.getOperand(0);
1680   SDValue RHS = Op.getOperand(1);
1681   unsigned Opc = 0;
1682   switch (Op.getOpcode()) {
1683   default:
1684     llvm_unreachable("Unknown overflow instruction!");
1685   case ISD::SADDO:
1686     Opc = AArch64ISD::ADDS;
1687     CC = AArch64CC::VS;
1688     break;
1689   case ISD::UADDO:
1690     Opc = AArch64ISD::ADDS;
1691     CC = AArch64CC::HS;
1692     break;
1693   case ISD::SSUBO:
1694     Opc = AArch64ISD::SUBS;
1695     CC = AArch64CC::VS;
1696     break;
1697   case ISD::USUBO:
1698     Opc = AArch64ISD::SUBS;
1699     CC = AArch64CC::LO;
1700     break;
1701   // Multiply needs a little bit extra work.
1702   case ISD::SMULO:
1703   case ISD::UMULO: {
1704     CC = AArch64CC::NE;
1705     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1706     if (Op.getValueType() == MVT::i32) {
1707       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1708       // For a 32 bit multiply with overflow check we want the instruction
1709       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1710       // need to generate the following pattern:
1711       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1712       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1713       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1714       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1715       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1716                                 DAG.getConstant(0, DL, MVT::i64));
1717       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1718       // operation. We need to clear out the upper 32 bits, because we used a
1719       // widening multiply that wrote all 64 bits. In the end this should be a
1720       // noop.
1721       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1722       if (IsSigned) {
1723         // The signed overflow check requires more than just a simple check for
1724         // any bit set in the upper 32 bits of the result. These bits could be
1725         // just the sign bits of a negative number. To perform the overflow
1726         // check we have to arithmetic shift right the 32nd bit of the result by
1727         // 31 bits. Then we compare the result to the upper 32 bits.
1728         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1729                                         DAG.getConstant(32, DL, MVT::i64));
1730         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1731         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1732                                         DAG.getConstant(31, DL, MVT::i64));
1733         // It is important that LowerBits is last, otherwise the arithmetic
1734         // shift will not be folded into the compare (SUBS).
1735         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1736         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1737                        .getValue(1);
1738       } else {
1739         // The overflow check for unsigned multiply is easy. We only need to
1740         // check if any of the upper 32 bits are set. This can be done with a
1741         // CMP (shifted register). For that we need to generate the following
1742         // pattern:
1743         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1744         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1745                                         DAG.getConstant(32, DL, MVT::i64));
1746         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1747         Overflow =
1748             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1749                         DAG.getConstant(0, DL, MVT::i64),
1750                         UpperBits).getValue(1);
1751       }
1752       break;
1753     }
1754     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1755     // For the 64 bit multiply
1756     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1757     if (IsSigned) {
1758       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1759       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1760                                       DAG.getConstant(63, DL, MVT::i64));
1761       // It is important that LowerBits is last, otherwise the arithmetic
1762       // shift will not be folded into the compare (SUBS).
1763       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1764       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1765                      .getValue(1);
1766     } else {
1767       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1768       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1769       Overflow =
1770           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1771                       DAG.getConstant(0, DL, MVT::i64),
1772                       UpperBits).getValue(1);
1773     }
1774     break;
1775   }
1776   } // switch (...)
1777
1778   if (Opc) {
1779     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1780
1781     // Emit the AArch64 operation with overflow check.
1782     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1783     Overflow = Value.getValue(1);
1784   }
1785   return std::make_pair(Value, Overflow);
1786 }
1787
1788 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1789                                              RTLIB::Libcall Call) const {
1790   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1791   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1792 }
1793
1794 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1795   SDValue Sel = Op.getOperand(0);
1796   SDValue Other = Op.getOperand(1);
1797
1798   // If neither operand is a SELECT_CC, give up.
1799   if (Sel.getOpcode() != ISD::SELECT_CC)
1800     std::swap(Sel, Other);
1801   if (Sel.getOpcode() != ISD::SELECT_CC)
1802     return Op;
1803
1804   // The folding we want to perform is:
1805   // (xor x, (select_cc a, b, cc, 0, -1) )
1806   //   -->
1807   // (csel x, (xor x, -1), cc ...)
1808   //
1809   // The latter will get matched to a CSINV instruction.
1810
1811   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1812   SDValue LHS = Sel.getOperand(0);
1813   SDValue RHS = Sel.getOperand(1);
1814   SDValue TVal = Sel.getOperand(2);
1815   SDValue FVal = Sel.getOperand(3);
1816   SDLoc dl(Sel);
1817
1818   // FIXME: This could be generalized to non-integer comparisons.
1819   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1820     return Op;
1821
1822   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1823   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1824
1825   // The values aren't constants, this isn't the pattern we're looking for.
1826   if (!CFVal || !CTVal)
1827     return Op;
1828
1829   // We can commute the SELECT_CC by inverting the condition.  This
1830   // might be needed to make this fit into a CSINV pattern.
1831   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1832     std::swap(TVal, FVal);
1833     std::swap(CTVal, CFVal);
1834     CC = ISD::getSetCCInverse(CC, true);
1835   }
1836
1837   // If the constants line up, perform the transform!
1838   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1839     SDValue CCVal;
1840     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1841
1842     FVal = Other;
1843     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1844                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1845
1846     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1847                        CCVal, Cmp);
1848   }
1849
1850   return Op;
1851 }
1852
1853 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1854   EVT VT = Op.getValueType();
1855
1856   // Let legalize expand this if it isn't a legal type yet.
1857   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1858     return SDValue();
1859
1860   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1861
1862   unsigned Opc;
1863   bool ExtraOp = false;
1864   switch (Op.getOpcode()) {
1865   default:
1866     llvm_unreachable("Invalid code");
1867   case ISD::ADDC:
1868     Opc = AArch64ISD::ADDS;
1869     break;
1870   case ISD::SUBC:
1871     Opc = AArch64ISD::SUBS;
1872     break;
1873   case ISD::ADDE:
1874     Opc = AArch64ISD::ADCS;
1875     ExtraOp = true;
1876     break;
1877   case ISD::SUBE:
1878     Opc = AArch64ISD::SBCS;
1879     ExtraOp = true;
1880     break;
1881   }
1882
1883   if (!ExtraOp)
1884     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1885   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1886                      Op.getOperand(2));
1887 }
1888
1889 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1890   // Let legalize expand this if it isn't a legal type yet.
1891   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1892     return SDValue();
1893
1894   SDLoc dl(Op);
1895   AArch64CC::CondCode CC;
1896   // The actual operation that sets the overflow or carry flag.
1897   SDValue Value, Overflow;
1898   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1899
1900   // We use 0 and 1 as false and true values.
1901   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1902   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1903
1904   // We use an inverted condition, because the conditional select is inverted
1905   // too. This will allow it to be selected to a single instruction:
1906   // CSINC Wd, WZR, WZR, invert(cond).
1907   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1908   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1909                          CCVal, Overflow);
1910
1911   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1912   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1913 }
1914
1915 // Prefetch operands are:
1916 // 1: Address to prefetch
1917 // 2: bool isWrite
1918 // 3: int locality (0 = no locality ... 3 = extreme locality)
1919 // 4: bool isDataCache
1920 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1921   SDLoc DL(Op);
1922   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1923   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1924   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1925
1926   bool IsStream = !Locality;
1927   // When the locality number is set
1928   if (Locality) {
1929     // The front-end should have filtered out the out-of-range values
1930     assert(Locality <= 3 && "Prefetch locality out-of-range");
1931     // The locality degree is the opposite of the cache speed.
1932     // Put the number the other way around.
1933     // The encoding starts at 0 for level 1
1934     Locality = 3 - Locality;
1935   }
1936
1937   // built the mask value encoding the expected behavior.
1938   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1939                    (!IsData << 3) |     // IsDataCache bit
1940                    (Locality << 1) |    // Cache level bits
1941                    (unsigned)IsStream;  // Stream bit
1942   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1943                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1944 }
1945
1946 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1947                                               SelectionDAG &DAG) const {
1948   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1949
1950   RTLIB::Libcall LC;
1951   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1952
1953   return LowerF128Call(Op, DAG, LC);
1954 }
1955
1956 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1957                                              SelectionDAG &DAG) const {
1958   if (Op.getOperand(0).getValueType() != MVT::f128) {
1959     // It's legal except when f128 is involved
1960     return Op;
1961   }
1962
1963   RTLIB::Libcall LC;
1964   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1965
1966   // FP_ROUND node has a second operand indicating whether it is known to be
1967   // precise. That doesn't take part in the LibCall so we can't directly use
1968   // LowerF128Call.
1969   SDValue SrcVal = Op.getOperand(0);
1970   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1971                      SDLoc(Op)).first;
1972 }
1973
1974 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1975   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1976   // Any additional optimization in this function should be recorded
1977   // in the cost tables.
1978   EVT InVT = Op.getOperand(0).getValueType();
1979   EVT VT = Op.getValueType();
1980   unsigned NumElts = InVT.getVectorNumElements();
1981
1982   // f16 vectors are promoted to f32 before a conversion.
1983   if (InVT.getVectorElementType() == MVT::f16) {
1984     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1985     SDLoc dl(Op);
1986     return DAG.getNode(
1987         Op.getOpcode(), dl, Op.getValueType(),
1988         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1989   }
1990
1991   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1992     SDLoc dl(Op);
1993     SDValue Cv =
1994         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1995                     Op.getOperand(0));
1996     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1997   }
1998
1999   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2000     SDLoc dl(Op);
2001     MVT ExtVT =
2002         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2003                          VT.getVectorNumElements());
2004     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2005     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2006   }
2007
2008   // Type changing conversions are illegal.
2009   return Op;
2010 }
2011
2012 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2013                                               SelectionDAG &DAG) const {
2014   if (Op.getOperand(0).getValueType().isVector())
2015     return LowerVectorFP_TO_INT(Op, DAG);
2016
2017   // f16 conversions are promoted to f32.
2018   if (Op.getOperand(0).getValueType() == MVT::f16) {
2019     SDLoc dl(Op);
2020     return DAG.getNode(
2021         Op.getOpcode(), dl, Op.getValueType(),
2022         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2023   }
2024
2025   if (Op.getOperand(0).getValueType() != MVT::f128) {
2026     // It's legal except when f128 is involved
2027     return Op;
2028   }
2029
2030   RTLIB::Libcall LC;
2031   if (Op.getOpcode() == ISD::FP_TO_SINT)
2032     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2033   else
2034     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2035
2036   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2037   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2038 }
2039
2040 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2041   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2042   // Any additional optimization in this function should be recorded
2043   // in the cost tables.
2044   EVT VT = Op.getValueType();
2045   SDLoc dl(Op);
2046   SDValue In = Op.getOperand(0);
2047   EVT InVT = In.getValueType();
2048
2049   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2050     MVT CastVT =
2051         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2052                          InVT.getVectorNumElements());
2053     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2054     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2055   }
2056
2057   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2058     unsigned CastOpc =
2059         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2060     EVT CastVT = VT.changeVectorElementTypeToInteger();
2061     In = DAG.getNode(CastOpc, dl, CastVT, In);
2062     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2063   }
2064
2065   return Op;
2066 }
2067
2068 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2069                                             SelectionDAG &DAG) const {
2070   if (Op.getValueType().isVector())
2071     return LowerVectorINT_TO_FP(Op, DAG);
2072
2073   // f16 conversions are promoted to f32.
2074   if (Op.getValueType() == MVT::f16) {
2075     SDLoc dl(Op);
2076     return DAG.getNode(
2077         ISD::FP_ROUND, dl, MVT::f16,
2078         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2079         DAG.getIntPtrConstant(0, dl));
2080   }
2081
2082   // i128 conversions are libcalls.
2083   if (Op.getOperand(0).getValueType() == MVT::i128)
2084     return SDValue();
2085
2086   // Other conversions are legal, unless it's to the completely software-based
2087   // fp128.
2088   if (Op.getValueType() != MVT::f128)
2089     return Op;
2090
2091   RTLIB::Libcall LC;
2092   if (Op.getOpcode() == ISD::SINT_TO_FP)
2093     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2094   else
2095     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2096
2097   return LowerF128Call(Op, DAG, LC);
2098 }
2099
2100 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2101                                             SelectionDAG &DAG) const {
2102   // For iOS, we want to call an alternative entry point: __sincos_stret,
2103   // which returns the values in two S / D registers.
2104   SDLoc dl(Op);
2105   SDValue Arg = Op.getOperand(0);
2106   EVT ArgVT = Arg.getValueType();
2107   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2108
2109   ArgListTy Args;
2110   ArgListEntry Entry;
2111
2112   Entry.Node = Arg;
2113   Entry.Ty = ArgTy;
2114   Entry.isSExt = false;
2115   Entry.isZExt = false;
2116   Args.push_back(Entry);
2117
2118   const char *LibcallName =
2119       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2120   SDValue Callee =
2121       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2122
2123   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2124   TargetLowering::CallLoweringInfo CLI(DAG);
2125   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2126     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2127
2128   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2129   return CallResult.first;
2130 }
2131
2132 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2133   if (Op.getValueType() != MVT::f16)
2134     return SDValue();
2135
2136   assert(Op.getOperand(0).getValueType() == MVT::i16);
2137   SDLoc DL(Op);
2138
2139   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2140   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2141   return SDValue(
2142       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2143                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2144       0);
2145 }
2146
2147 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2148   if (OrigVT.getSizeInBits() >= 64)
2149     return OrigVT;
2150
2151   assert(OrigVT.isSimple() && "Expecting a simple value type");
2152
2153   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2154   switch (OrigSimpleTy) {
2155   default: llvm_unreachable("Unexpected Vector Type");
2156   case MVT::v2i8:
2157   case MVT::v2i16:
2158      return MVT::v2i32;
2159   case MVT::v4i8:
2160     return  MVT::v4i16;
2161   }
2162 }
2163
2164 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2165                                                  const EVT &OrigTy,
2166                                                  const EVT &ExtTy,
2167                                                  unsigned ExtOpcode) {
2168   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2169   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2170   // 64-bits we need to insert a new extension so that it will be 64-bits.
2171   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2172   if (OrigTy.getSizeInBits() >= 64)
2173     return N;
2174
2175   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2176   EVT NewVT = getExtensionTo64Bits(OrigTy);
2177
2178   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2179 }
2180
2181 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2182                                    bool isSigned) {
2183   EVT VT = N->getValueType(0);
2184
2185   if (N->getOpcode() != ISD::BUILD_VECTOR)
2186     return false;
2187
2188   for (const SDValue &Elt : N->op_values()) {
2189     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2190       unsigned EltSize = VT.getScalarSizeInBits();
2191       unsigned HalfSize = EltSize / 2;
2192       if (isSigned) {
2193         if (!isIntN(HalfSize, C->getSExtValue()))
2194           return false;
2195       } else {
2196         if (!isUIntN(HalfSize, C->getZExtValue()))
2197           return false;
2198       }
2199       continue;
2200     }
2201     return false;
2202   }
2203
2204   return true;
2205 }
2206
2207 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2208   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2209     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2210                                              N->getOperand(0)->getValueType(0),
2211                                              N->getValueType(0),
2212                                              N->getOpcode());
2213
2214   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2215   EVT VT = N->getValueType(0);
2216   SDLoc dl(N);
2217   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2218   unsigned NumElts = VT.getVectorNumElements();
2219   MVT TruncVT = MVT::getIntegerVT(EltSize);
2220   SmallVector<SDValue, 8> Ops;
2221   for (unsigned i = 0; i != NumElts; ++i) {
2222     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2223     const APInt &CInt = C->getAPIntValue();
2224     // Element types smaller than 32 bits are not legal, so use i32 elements.
2225     // The values are implicitly truncated so sext vs. zext doesn't matter.
2226     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2227   }
2228   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2229 }
2230
2231 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2232   if (N->getOpcode() == ISD::SIGN_EXTEND)
2233     return true;
2234   if (isExtendedBUILD_VECTOR(N, DAG, true))
2235     return true;
2236   return false;
2237 }
2238
2239 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2240   if (N->getOpcode() == ISD::ZERO_EXTEND)
2241     return true;
2242   if (isExtendedBUILD_VECTOR(N, DAG, false))
2243     return true;
2244   return false;
2245 }
2246
2247 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2248   unsigned Opcode = N->getOpcode();
2249   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2250     SDNode *N0 = N->getOperand(0).getNode();
2251     SDNode *N1 = N->getOperand(1).getNode();
2252     return N0->hasOneUse() && N1->hasOneUse() &&
2253       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2254   }
2255   return false;
2256 }
2257
2258 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2259   unsigned Opcode = N->getOpcode();
2260   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2261     SDNode *N0 = N->getOperand(0).getNode();
2262     SDNode *N1 = N->getOperand(1).getNode();
2263     return N0->hasOneUse() && N1->hasOneUse() &&
2264       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2265   }
2266   return false;
2267 }
2268
2269 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2270   // Multiplications are only custom-lowered for 128-bit vectors so that
2271   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2272   EVT VT = Op.getValueType();
2273   assert(VT.is128BitVector() && VT.isInteger() &&
2274          "unexpected type for custom-lowering ISD::MUL");
2275   SDNode *N0 = Op.getOperand(0).getNode();
2276   SDNode *N1 = Op.getOperand(1).getNode();
2277   unsigned NewOpc = 0;
2278   bool isMLA = false;
2279   bool isN0SExt = isSignExtended(N0, DAG);
2280   bool isN1SExt = isSignExtended(N1, DAG);
2281   if (isN0SExt && isN1SExt)
2282     NewOpc = AArch64ISD::SMULL;
2283   else {
2284     bool isN0ZExt = isZeroExtended(N0, DAG);
2285     bool isN1ZExt = isZeroExtended(N1, DAG);
2286     if (isN0ZExt && isN1ZExt)
2287       NewOpc = AArch64ISD::UMULL;
2288     else if (isN1SExt || isN1ZExt) {
2289       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2290       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2291       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2292         NewOpc = AArch64ISD::SMULL;
2293         isMLA = true;
2294       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2295         NewOpc =  AArch64ISD::UMULL;
2296         isMLA = true;
2297       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2298         std::swap(N0, N1);
2299         NewOpc =  AArch64ISD::UMULL;
2300         isMLA = true;
2301       }
2302     }
2303
2304     if (!NewOpc) {
2305       if (VT == MVT::v2i64)
2306         // Fall through to expand this.  It is not legal.
2307         return SDValue();
2308       else
2309         // Other vector multiplications are legal.
2310         return Op;
2311     }
2312   }
2313
2314   // Legalize to a S/UMULL instruction
2315   SDLoc DL(Op);
2316   SDValue Op0;
2317   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2318   if (!isMLA) {
2319     Op0 = skipExtensionForVectorMULL(N0, DAG);
2320     assert(Op0.getValueType().is64BitVector() &&
2321            Op1.getValueType().is64BitVector() &&
2322            "unexpected types for extended operands to VMULL");
2323     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2324   }
2325   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2326   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2327   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2328   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2329   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2330   EVT Op1VT = Op1.getValueType();
2331   return DAG.getNode(N0->getOpcode(), DL, VT,
2332                      DAG.getNode(NewOpc, DL, VT,
2333                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2334                      DAG.getNode(NewOpc, DL, VT,
2335                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2336 }
2337
2338 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2339                                                      SelectionDAG &DAG) const {
2340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341   SDLoc dl(Op);
2342   switch (IntNo) {
2343   default: return SDValue();    // Don't custom lower most intrinsics.
2344   case Intrinsic::thread_pointer: {
2345     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2346     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2347   }
2348   case Intrinsic::aarch64_neon_smax:
2349     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2350                        Op.getOperand(1), Op.getOperand(2));
2351   case Intrinsic::aarch64_neon_umax:
2352     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2353                        Op.getOperand(1), Op.getOperand(2));
2354   case Intrinsic::aarch64_neon_smin:
2355     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2356                        Op.getOperand(1), Op.getOperand(2));
2357   case Intrinsic::aarch64_neon_umin:
2358     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2359                        Op.getOperand(1), Op.getOperand(2));
2360   }
2361 }
2362
2363 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2364                                               SelectionDAG &DAG) const {
2365   switch (Op.getOpcode()) {
2366   default:
2367     llvm_unreachable("unimplemented operand");
2368     return SDValue();
2369   case ISD::BITCAST:
2370     return LowerBITCAST(Op, DAG);
2371   case ISD::GlobalAddress:
2372     return LowerGlobalAddress(Op, DAG);
2373   case ISD::GlobalTLSAddress:
2374     return LowerGlobalTLSAddress(Op, DAG);
2375   case ISD::SETCC:
2376     return LowerSETCC(Op, DAG);
2377   case ISD::BR_CC:
2378     return LowerBR_CC(Op, DAG);
2379   case ISD::SELECT:
2380     return LowerSELECT(Op, DAG);
2381   case ISD::SELECT_CC:
2382     return LowerSELECT_CC(Op, DAG);
2383   case ISD::JumpTable:
2384     return LowerJumpTable(Op, DAG);
2385   case ISD::ConstantPool:
2386     return LowerConstantPool(Op, DAG);
2387   case ISD::BlockAddress:
2388     return LowerBlockAddress(Op, DAG);
2389   case ISD::VASTART:
2390     return LowerVASTART(Op, DAG);
2391   case ISD::VACOPY:
2392     return LowerVACOPY(Op, DAG);
2393   case ISD::VAARG:
2394     return LowerVAARG(Op, DAG);
2395   case ISD::ADDC:
2396   case ISD::ADDE:
2397   case ISD::SUBC:
2398   case ISD::SUBE:
2399     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2400   case ISD::SADDO:
2401   case ISD::UADDO:
2402   case ISD::SSUBO:
2403   case ISD::USUBO:
2404   case ISD::SMULO:
2405   case ISD::UMULO:
2406     return LowerXALUO(Op, DAG);
2407   case ISD::FADD:
2408     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2409   case ISD::FSUB:
2410     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2411   case ISD::FMUL:
2412     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2413   case ISD::FDIV:
2414     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2415   case ISD::FP_ROUND:
2416     return LowerFP_ROUND(Op, DAG);
2417   case ISD::FP_EXTEND:
2418     return LowerFP_EXTEND(Op, DAG);
2419   case ISD::FRAMEADDR:
2420     return LowerFRAMEADDR(Op, DAG);
2421   case ISD::RETURNADDR:
2422     return LowerRETURNADDR(Op, DAG);
2423   case ISD::INSERT_VECTOR_ELT:
2424     return LowerINSERT_VECTOR_ELT(Op, DAG);
2425   case ISD::EXTRACT_VECTOR_ELT:
2426     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2427   case ISD::BUILD_VECTOR:
2428     return LowerBUILD_VECTOR(Op, DAG);
2429   case ISD::VECTOR_SHUFFLE:
2430     return LowerVECTOR_SHUFFLE(Op, DAG);
2431   case ISD::EXTRACT_SUBVECTOR:
2432     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2433   case ISD::SRA:
2434   case ISD::SRL:
2435   case ISD::SHL:
2436     return LowerVectorSRA_SRL_SHL(Op, DAG);
2437   case ISD::SHL_PARTS:
2438     return LowerShiftLeftParts(Op, DAG);
2439   case ISD::SRL_PARTS:
2440   case ISD::SRA_PARTS:
2441     return LowerShiftRightParts(Op, DAG);
2442   case ISD::CTPOP:
2443     return LowerCTPOP(Op, DAG);
2444   case ISD::FCOPYSIGN:
2445     return LowerFCOPYSIGN(Op, DAG);
2446   case ISD::AND:
2447     return LowerVectorAND(Op, DAG);
2448   case ISD::OR:
2449     return LowerVectorOR(Op, DAG);
2450   case ISD::XOR:
2451     return LowerXOR(Op, DAG);
2452   case ISD::PREFETCH:
2453     return LowerPREFETCH(Op, DAG);
2454   case ISD::SINT_TO_FP:
2455   case ISD::UINT_TO_FP:
2456     return LowerINT_TO_FP(Op, DAG);
2457   case ISD::FP_TO_SINT:
2458   case ISD::FP_TO_UINT:
2459     return LowerFP_TO_INT(Op, DAG);
2460   case ISD::FSINCOS:
2461     return LowerFSINCOS(Op, DAG);
2462   case ISD::MUL:
2463     return LowerMUL(Op, DAG);
2464   case ISD::INTRINSIC_WO_CHAIN:
2465     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2466   }
2467 }
2468
2469 //===----------------------------------------------------------------------===//
2470 //                      Calling Convention Implementation
2471 //===----------------------------------------------------------------------===//
2472
2473 #include "AArch64GenCallingConv.inc"
2474
2475 /// Selects the correct CCAssignFn for a given CallingConvention value.
2476 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2477                                                      bool IsVarArg) const {
2478   switch (CC) {
2479   default:
2480     llvm_unreachable("Unsupported calling convention.");
2481   case CallingConv::WebKit_JS:
2482     return CC_AArch64_WebKit_JS;
2483   case CallingConv::GHC:
2484     return CC_AArch64_GHC;
2485   case CallingConv::C:
2486   case CallingConv::Fast:
2487   case CallingConv::PreserveMost:
2488   case CallingConv::CXX_FAST_TLS:
2489   case CallingConv::Swift:
2490     if (!Subtarget->isTargetDarwin())
2491       return CC_AArch64_AAPCS;
2492     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2493   }
2494 }
2495
2496 CCAssignFn *
2497 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2498   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2499                                       : RetCC_AArch64_AAPCS;
2500 }
2501
2502 SDValue AArch64TargetLowering::LowerFormalArguments(
2503     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2504     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2505     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2506   MachineFunction &MF = DAG.getMachineFunction();
2507   MachineFrameInfo &MFI = MF.getFrameInfo();
2508
2509   // Assign locations to all of the incoming arguments.
2510   SmallVector<CCValAssign, 16> ArgLocs;
2511   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2512                  *DAG.getContext());
2513
2514   // At this point, Ins[].VT may already be promoted to i32. To correctly
2515   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2516   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2517   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2518   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2519   // LocVT.
2520   unsigned NumArgs = Ins.size();
2521   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2522   unsigned CurArgIdx = 0;
2523   for (unsigned i = 0; i != NumArgs; ++i) {
2524     MVT ValVT = Ins[i].VT;
2525     if (Ins[i].isOrigArg()) {
2526       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2527       CurArgIdx = Ins[i].getOrigArgIndex();
2528
2529       // Get type of the original argument.
2530       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2531                                   /*AllowUnknown*/ true);
2532       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2533       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2534       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2535         ValVT = MVT::i8;
2536       else if (ActualMVT == MVT::i16)
2537         ValVT = MVT::i16;
2538     }
2539     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2540     bool Res =
2541         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2542     assert(!Res && "Call operand has unhandled type");
2543     (void)Res;
2544   }
2545   assert(ArgLocs.size() == Ins.size());
2546   SmallVector<SDValue, 16> ArgValues;
2547   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2548     CCValAssign &VA = ArgLocs[i];
2549
2550     if (Ins[i].Flags.isByVal()) {
2551       // Byval is used for HFAs in the PCS, but the system should work in a
2552       // non-compliant manner for larger structs.
2553       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2554       int Size = Ins[i].Flags.getByValSize();
2555       unsigned NumRegs = (Size + 7) / 8;
2556
2557       // FIXME: This works on big-endian for composite byvals, which are the common
2558       // case. It should also work for fundamental types too.
2559       unsigned FrameIdx =
2560         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2561       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2562       InVals.push_back(FrameIdxN);
2563
2564       continue;
2565     }
2566
2567     if (VA.isRegLoc()) {
2568       // Arguments stored in registers.
2569       EVT RegVT = VA.getLocVT();
2570
2571       SDValue ArgValue;
2572       const TargetRegisterClass *RC;
2573
2574       if (RegVT == MVT::i32)
2575         RC = &AArch64::GPR32RegClass;
2576       else if (RegVT == MVT::i64)
2577         RC = &AArch64::GPR64RegClass;
2578       else if (RegVT == MVT::f16)
2579         RC = &AArch64::FPR16RegClass;
2580       else if (RegVT == MVT::f32)
2581         RC = &AArch64::FPR32RegClass;
2582       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2583         RC = &AArch64::FPR64RegClass;
2584       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2585         RC = &AArch64::FPR128RegClass;
2586       else
2587         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2588
2589       // Transform the arguments in physical registers into virtual ones.
2590       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2591       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2592
2593       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2594       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2595       // truncate to the right size.
2596       switch (VA.getLocInfo()) {
2597       default:
2598         llvm_unreachable("Unknown loc info!");
2599       case CCValAssign::Full:
2600         break;
2601       case CCValAssign::BCvt:
2602         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2603         break;
2604       case CCValAssign::AExt:
2605       case CCValAssign::SExt:
2606       case CCValAssign::ZExt:
2607         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2608         // nodes after our lowering.
2609         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2610         break;
2611       }
2612
2613       InVals.push_back(ArgValue);
2614
2615     } else { // VA.isRegLoc()
2616       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2617       unsigned ArgOffset = VA.getLocMemOffset();
2618       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2619
2620       uint32_t BEAlign = 0;
2621       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2622           !Ins[i].Flags.isInConsecutiveRegs())
2623         BEAlign = 8 - ArgSize;
2624
2625       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2626
2627       // Create load nodes to retrieve arguments from the stack.
2628       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2629       SDValue ArgValue;
2630
2631       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2632       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2633       MVT MemVT = VA.getValVT();
2634
2635       switch (VA.getLocInfo()) {
2636       default:
2637         break;
2638       case CCValAssign::BCvt:
2639         MemVT = VA.getLocVT();
2640         break;
2641       case CCValAssign::SExt:
2642         ExtType = ISD::SEXTLOAD;
2643         break;
2644       case CCValAssign::ZExt:
2645         ExtType = ISD::ZEXTLOAD;
2646         break;
2647       case CCValAssign::AExt:
2648         ExtType = ISD::EXTLOAD;
2649         break;
2650       }
2651
2652       ArgValue = DAG.getExtLoad(
2653           ExtType, DL, VA.getLocVT(), Chain, FIN,
2654           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2655           MemVT);
2656
2657       InVals.push_back(ArgValue);
2658     }
2659   }
2660
2661   // varargs
2662   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2663   if (isVarArg) {
2664     if (!Subtarget->isTargetDarwin()) {
2665       // The AAPCS variadic function ABI is identical to the non-variadic
2666       // one. As a result there may be more arguments in registers and we should
2667       // save them for future reference.
2668       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2669     }
2670
2671     // This will point to the next argument passed via stack.
2672     unsigned StackOffset = CCInfo.getNextStackOffset();
2673     // We currently pass all varargs at 8-byte alignment.
2674     StackOffset = ((StackOffset + 7) & ~7);
2675     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2676   }
2677
2678   unsigned StackArgSize = CCInfo.getNextStackOffset();
2679   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2680   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2681     // This is a non-standard ABI so by fiat I say we're allowed to make full
2682     // use of the stack area to be popped, which must be aligned to 16 bytes in
2683     // any case:
2684     StackArgSize = alignTo(StackArgSize, 16);
2685
2686     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2687     // a multiple of 16.
2688     FuncInfo->setArgumentStackToRestore(StackArgSize);
2689
2690     // This realignment carries over to the available bytes below. Our own
2691     // callers will guarantee the space is free by giving an aligned value to
2692     // CALLSEQ_START.
2693   }
2694   // Even if we're not expected to free up the space, it's useful to know how
2695   // much is there while considering tail calls (because we can reuse it).
2696   FuncInfo->setBytesInStackArgArea(StackArgSize);
2697
2698   return Chain;
2699 }
2700
2701 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2702                                                 SelectionDAG &DAG,
2703                                                 const SDLoc &DL,
2704                                                 SDValue &Chain) const {
2705   MachineFunction &MF = DAG.getMachineFunction();
2706   MachineFrameInfo &MFI = MF.getFrameInfo();
2707   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2708   auto PtrVT = getPointerTy(DAG.getDataLayout());
2709
2710   SmallVector<SDValue, 8> MemOps;
2711
2712   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2713                                           AArch64::X3, AArch64::X4, AArch64::X5,
2714                                           AArch64::X6, AArch64::X7 };
2715   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2716   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2717
2718   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2719   int GPRIdx = 0;
2720   if (GPRSaveSize != 0) {
2721     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2722
2723     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2724
2725     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2726       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2727       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2728       SDValue Store = DAG.getStore(
2729           Val.getValue(1), DL, Val, FIN,
2730           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2731       MemOps.push_back(Store);
2732       FIN =
2733           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2734     }
2735   }
2736   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2737   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2738
2739   if (Subtarget->hasFPARMv8()) {
2740     static const MCPhysReg FPRArgRegs[] = {
2741         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2742         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2743     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2744     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2745
2746     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2747     int FPRIdx = 0;
2748     if (FPRSaveSize != 0) {
2749       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2750
2751       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2752
2753       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2754         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2755         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2756
2757         SDValue Store = DAG.getStore(
2758             Val.getValue(1), DL, Val, FIN,
2759             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2760         MemOps.push_back(Store);
2761         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2762                           DAG.getConstant(16, DL, PtrVT));
2763       }
2764     }
2765     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2766     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2767   }
2768
2769   if (!MemOps.empty()) {
2770     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2771   }
2772 }
2773
2774 /// LowerCallResult - Lower the result values of a call into the
2775 /// appropriate copies out of appropriate physical registers.
2776 SDValue AArch64TargetLowering::LowerCallResult(
2777     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2778     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2779     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2780     SDValue ThisVal) const {
2781   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2782                           ? RetCC_AArch64_WebKit_JS
2783                           : RetCC_AArch64_AAPCS;
2784   // Assign locations to each value returned by this call.
2785   SmallVector<CCValAssign, 16> RVLocs;
2786   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2787                  *DAG.getContext());
2788   CCInfo.AnalyzeCallResult(Ins, RetCC);
2789
2790   // Copy all of the result registers out of their specified physreg.
2791   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2792     CCValAssign VA = RVLocs[i];
2793
2794     // Pass 'this' value directly from the argument to return value, to avoid
2795     // reg unit interference
2796     if (i == 0 && isThisReturn) {
2797       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2798              "unexpected return calling convention register assignment");
2799       InVals.push_back(ThisVal);
2800       continue;
2801     }
2802
2803     SDValue Val =
2804         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2805     Chain = Val.getValue(1);
2806     InFlag = Val.getValue(2);
2807
2808     switch (VA.getLocInfo()) {
2809     default:
2810       llvm_unreachable("Unknown loc info!");
2811     case CCValAssign::Full:
2812       break;
2813     case CCValAssign::BCvt:
2814       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2815       break;
2816     }
2817
2818     InVals.push_back(Val);
2819   }
2820
2821   return Chain;
2822 }
2823
2824 /// Return true if the calling convention is one that we can guarantee TCO for.
2825 static bool canGuaranteeTCO(CallingConv::ID CC) {
2826   return CC == CallingConv::Fast;
2827 }
2828
2829 /// Return true if we might ever do TCO for calls with this calling convention.
2830 static bool mayTailCallThisCC(CallingConv::ID CC) {
2831   switch (CC) {
2832   case CallingConv::C:
2833   case CallingConv::PreserveMost:
2834   case CallingConv::Swift:
2835     return true;
2836   default:
2837     return canGuaranteeTCO(CC);
2838   }
2839 }
2840
2841 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2842     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2843     const SmallVectorImpl<ISD::OutputArg> &Outs,
2844     const SmallVectorImpl<SDValue> &OutVals,
2845     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2846   if (!mayTailCallThisCC(CalleeCC))
2847     return false;
2848
2849   MachineFunction &MF = DAG.getMachineFunction();
2850   const Function *CallerF = MF.getFunction();
2851   CallingConv::ID CallerCC = CallerF->getCallingConv();
2852   bool CCMatch = CallerCC == CalleeCC;
2853
2854   // Byval parameters hand the function a pointer directly into the stack area
2855   // we want to reuse during a tail call. Working around this *is* possible (see
2856   // X86) but less efficient and uglier in LowerCall.
2857   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2858                                     e = CallerF->arg_end();
2859        i != e; ++i)
2860     if (i->hasByValAttr())
2861       return false;
2862
2863   if (getTargetMachine().Options.GuaranteedTailCallOpt)
2864     return canGuaranteeTCO(CalleeCC) && CCMatch;
2865
2866   // Externally-defined functions with weak linkage should not be
2867   // tail-called on AArch64 when the OS does not support dynamic
2868   // pre-emption of symbols, as the AAELF spec requires normal calls
2869   // to undefined weak functions to be replaced with a NOP or jump to the
2870   // next instruction. The behaviour of branch instructions in this
2871   // situation (as used for tail calls) is implementation-defined, so we
2872   // cannot rely on the linker replacing the tail call with a return.
2873   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2874     const GlobalValue *GV = G->getGlobal();
2875     const Triple &TT = getTargetMachine().getTargetTriple();
2876     if (GV->hasExternalWeakLinkage() &&
2877         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2878       return false;
2879   }
2880
2881   // Now we search for cases where we can use a tail call without changing the
2882   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2883   // concept.
2884
2885   // I want anyone implementing a new calling convention to think long and hard
2886   // about this assert.
2887   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2888          "Unexpected variadic calling convention");
2889
2890   LLVMContext &C = *DAG.getContext();
2891   if (isVarArg && !Outs.empty()) {
2892     // At least two cases here: if caller is fastcc then we can't have any
2893     // memory arguments (we'd be expected to clean up the stack afterwards). If
2894     // caller is C then we could potentially use its argument area.
2895
2896     // FIXME: for now we take the most conservative of these in both cases:
2897     // disallow all variadic memory operands.
2898     SmallVector<CCValAssign, 16> ArgLocs;
2899     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2900
2901     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2902     for (const CCValAssign &ArgLoc : ArgLocs)
2903       if (!ArgLoc.isRegLoc())
2904         return false;
2905   }
2906
2907   // Check that the call results are passed in the same way.
2908   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2909                                   CCAssignFnForCall(CalleeCC, isVarArg),
2910                                   CCAssignFnForCall(CallerCC, isVarArg)))
2911     return false;
2912   // The callee has to preserve all registers the caller needs to preserve.
2913   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2914   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2915   if (!CCMatch) {
2916     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2917     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2918       return false;
2919   }
2920
2921   // Nothing more to check if the callee is taking no arguments
2922   if (Outs.empty())
2923     return true;
2924
2925   SmallVector<CCValAssign, 16> ArgLocs;
2926   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2927
2928   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2929
2930   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2931
2932   // If the stack arguments for this call do not fit into our own save area then
2933   // the call cannot be made tail.
2934   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2935     return false;
2936
2937   const MachineRegisterInfo &MRI = MF.getRegInfo();
2938   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2939     return false;
2940
2941   return true;
2942 }
2943
2944 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2945                                                    SelectionDAG &DAG,
2946                                                    MachineFrameInfo &MFI,
2947                                                    int ClobberedFI) const {
2948   SmallVector<SDValue, 8> ArgChains;
2949   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2950   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2951
2952   // Include the original chain at the beginning of the list. When this is
2953   // used by target LowerCall hooks, this helps legalize find the
2954   // CALLSEQ_BEGIN node.
2955   ArgChains.push_back(Chain);
2956
2957   // Add a chain value for each stack argument corresponding
2958   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2959                             UE = DAG.getEntryNode().getNode()->use_end();
2960        U != UE; ++U)
2961     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2962       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2963         if (FI->getIndex() < 0) {
2964           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2965           int64_t InLastByte = InFirstByte;
2966           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2967
2968           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2969               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2970             ArgChains.push_back(SDValue(L, 1));
2971         }
2972
2973   // Build a tokenfactor for all the chains.
2974   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2975 }
2976
2977 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2978                                                    bool TailCallOpt) const {
2979   return CallCC == CallingConv::Fast && TailCallOpt;
2980 }
2981
2982 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2983 /// and add input and output parameter nodes.
2984 SDValue
2985 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2986                                  SmallVectorImpl<SDValue> &InVals) const {
2987   SelectionDAG &DAG = CLI.DAG;
2988   SDLoc &DL = CLI.DL;
2989   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2990   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2991   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2992   SDValue Chain = CLI.Chain;
2993   SDValue Callee = CLI.Callee;
2994   bool &IsTailCall = CLI.IsTailCall;
2995   CallingConv::ID CallConv = CLI.CallConv;
2996   bool IsVarArg = CLI.IsVarArg;
2997
2998   MachineFunction &MF = DAG.getMachineFunction();
2999   bool IsThisReturn = false;
3000
3001   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3002   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3003   bool IsSibCall = false;
3004
3005   if (IsTailCall) {
3006     // Check if it's really possible to do a tail call.
3007     IsTailCall = isEligibleForTailCallOptimization(
3008         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3009     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3010       report_fatal_error("failed to perform tail call elimination on a call "
3011                          "site marked musttail");
3012
3013     // A sibling call is one where we're under the usual C ABI and not planning
3014     // to change that but can still do a tail call:
3015     if (!TailCallOpt && IsTailCall)
3016       IsSibCall = true;
3017
3018     if (IsTailCall)
3019       ++NumTailCalls;
3020   }
3021
3022   // Analyze operands of the call, assigning locations to each operand.
3023   SmallVector<CCValAssign, 16> ArgLocs;
3024   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3025                  *DAG.getContext());
3026
3027   if (IsVarArg) {
3028     // Handle fixed and variable vector arguments differently.
3029     // Variable vector arguments always go into memory.
3030     unsigned NumArgs = Outs.size();
3031
3032     for (unsigned i = 0; i != NumArgs; ++i) {
3033       MVT ArgVT = Outs[i].VT;
3034       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3035       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3036                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3037       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3038       assert(!Res && "Call operand has unhandled type");
3039       (void)Res;
3040     }
3041   } else {
3042     // At this point, Outs[].VT may already be promoted to i32. To correctly
3043     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3044     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3045     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3046     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3047     // LocVT.
3048     unsigned NumArgs = Outs.size();
3049     for (unsigned i = 0; i != NumArgs; ++i) {
3050       MVT ValVT = Outs[i].VT;
3051       // Get type of the original argument.
3052       EVT ActualVT = getValueType(DAG.getDataLayout(),
3053                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3054                                   /*AllowUnknown*/ true);
3055       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3056       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3057       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3058       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3059         ValVT = MVT::i8;
3060       else if (ActualMVT == MVT::i16)
3061         ValVT = MVT::i16;
3062
3063       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3064       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3065       assert(!Res && "Call operand has unhandled type");
3066       (void)Res;
3067     }
3068   }
3069
3070   // Get a count of how many bytes are to be pushed on the stack.
3071   unsigned NumBytes = CCInfo.getNextStackOffset();
3072
3073   if (IsSibCall) {
3074     // Since we're not changing the ABI to make this a tail call, the memory
3075     // operands are already available in the caller's incoming argument space.
3076     NumBytes = 0;
3077   }
3078
3079   // FPDiff is the byte offset of the call's argument area from the callee's.
3080   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3081   // by this amount for a tail call. In a sibling call it must be 0 because the
3082   // caller will deallocate the entire stack and the callee still expects its
3083   // arguments to begin at SP+0. Completely unused for non-tail calls.
3084   int FPDiff = 0;
3085
3086   if (IsTailCall && !IsSibCall) {
3087     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3088
3089     // Since callee will pop argument stack as a tail call, we must keep the
3090     // popped size 16-byte aligned.
3091     NumBytes = alignTo(NumBytes, 16);
3092
3093     // FPDiff will be negative if this tail call requires more space than we
3094     // would automatically have in our incoming argument space. Positive if we
3095     // can actually shrink the stack.
3096     FPDiff = NumReusableBytes - NumBytes;
3097
3098     // The stack pointer must be 16-byte aligned at all times it's used for a
3099     // memory operation, which in practice means at *all* times and in
3100     // particular across call boundaries. Therefore our own arguments started at
3101     // a 16-byte aligned SP and the delta applied for the tail call should
3102     // satisfy the same constraint.
3103     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3104   }
3105
3106   // Adjust the stack pointer for the new arguments...
3107   // These operations are automatically eliminated by the prolog/epilog pass
3108   if (!IsSibCall)
3109     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3110                                                               true),
3111                                  DL);
3112
3113   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3114                                         getPointerTy(DAG.getDataLayout()));
3115
3116   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3117   SmallVector<SDValue, 8> MemOpChains;
3118   auto PtrVT = getPointerTy(DAG.getDataLayout());
3119
3120   // Walk the register/memloc assignments, inserting copies/loads.
3121   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3122        ++i, ++realArgIdx) {
3123     CCValAssign &VA = ArgLocs[i];
3124     SDValue Arg = OutVals[realArgIdx];
3125     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3126
3127     // Promote the value if needed.
3128     switch (VA.getLocInfo()) {
3129     default:
3130       llvm_unreachable("Unknown loc info!");
3131     case CCValAssign::Full:
3132       break;
3133     case CCValAssign::SExt:
3134       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3135       break;
3136     case CCValAssign::ZExt:
3137       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3138       break;
3139     case CCValAssign::AExt:
3140       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3141         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3142         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3143         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3144       }
3145       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3146       break;
3147     case CCValAssign::BCvt:
3148       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3149       break;
3150     case CCValAssign::FPExt:
3151       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3152       break;
3153     }
3154
3155     if (VA.isRegLoc()) {
3156       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3157         assert(VA.getLocVT() == MVT::i64 &&
3158                "unexpected calling convention register assignment");
3159         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3160                "unexpected use of 'returned'");
3161         IsThisReturn = true;
3162       }
3163       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3164     } else {
3165       assert(VA.isMemLoc());
3166
3167       SDValue DstAddr;
3168       MachinePointerInfo DstInfo;
3169
3170       // FIXME: This works on big-endian for composite byvals, which are the
3171       // common case. It should also work for fundamental types too.
3172       uint32_t BEAlign = 0;
3173       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3174                                         : VA.getValVT().getSizeInBits();
3175       OpSize = (OpSize + 7) / 8;
3176       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3177           !Flags.isInConsecutiveRegs()) {
3178         if (OpSize < 8)
3179           BEAlign = 8 - OpSize;
3180       }
3181       unsigned LocMemOffset = VA.getLocMemOffset();
3182       int32_t Offset = LocMemOffset + BEAlign;
3183       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3184       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3185
3186       if (IsTailCall) {
3187         Offset = Offset + FPDiff;
3188         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3189
3190         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3191         DstInfo =
3192             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3193
3194         // Make sure any stack arguments overlapping with where we're storing
3195         // are loaded before this eventual operation. Otherwise they'll be
3196         // clobbered.
3197         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3198       } else {
3199         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3200
3201         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3202         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3203                                                LocMemOffset);
3204       }
3205
3206       if (Outs[i].Flags.isByVal()) {
3207         SDValue SizeNode =
3208             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3209         SDValue Cpy = DAG.getMemcpy(
3210             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3211             /*isVol = */ false, /*AlwaysInline = */ false,
3212             /*isTailCall = */ false,
3213             DstInfo, MachinePointerInfo());
3214
3215         MemOpChains.push_back(Cpy);
3216       } else {
3217         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3218         // promoted to a legal register type i32, we should truncate Arg back to
3219         // i1/i8/i16.
3220         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3221             VA.getValVT() == MVT::i16)
3222           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3223
3224         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3225         MemOpChains.push_back(Store);
3226       }
3227     }
3228   }
3229
3230   if (!MemOpChains.empty())
3231     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3232
3233   // Build a sequence of copy-to-reg nodes chained together with token chain
3234   // and flag operands which copy the outgoing args into the appropriate regs.
3235   SDValue InFlag;
3236   for (auto &RegToPass : RegsToPass) {
3237     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3238                              RegToPass.second, InFlag);
3239     InFlag = Chain.getValue(1);
3240   }
3241
3242   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3243   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3244   // node so that legalize doesn't hack it.
3245   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3246       Subtarget->isTargetMachO()) {
3247     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3248       const GlobalValue *GV = G->getGlobal();
3249       bool InternalLinkage = GV->hasInternalLinkage();
3250       if (InternalLinkage)
3251         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3252       else {
3253         Callee =
3254             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3255         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3256       }
3257     } else if (ExternalSymbolSDNode *S =
3258                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3259       const char *Sym = S->getSymbol();
3260       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3261       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3262     }
3263   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3264     const GlobalValue *GV = G->getGlobal();
3265     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3266   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3267     const char *Sym = S->getSymbol();
3268     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3269   }
3270
3271   // We don't usually want to end the call-sequence here because we would tidy
3272   // the frame up *after* the call, however in the ABI-changing tail-call case
3273   // we've carefully laid out the parameters so that when sp is reset they'll be
3274   // in the correct location.
3275   if (IsTailCall && !IsSibCall) {
3276     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3277                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3278     InFlag = Chain.getValue(1);
3279   }
3280
3281   std::vector<SDValue> Ops;
3282   Ops.push_back(Chain);
3283   Ops.push_back(Callee);
3284
3285   if (IsTailCall) {
3286     // Each tail call may have to adjust the stack by a different amount, so
3287     // this information must travel along with the operation for eventual
3288     // consumption by emitEpilogue.
3289     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3290   }
3291
3292   // Add argument registers to the end of the list so that they are known live
3293   // into the call.
3294   for (auto &RegToPass : RegsToPass)
3295     Ops.push_back(DAG.getRegister(RegToPass.first,
3296                                   RegToPass.second.getValueType()));
3297
3298   // Add a register mask operand representing the call-preserved registers.
3299   const uint32_t *Mask;
3300   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3301   if (IsThisReturn) {
3302     // For 'this' returns, use the X0-preserving mask if applicable
3303     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3304     if (!Mask) {
3305       IsThisReturn = false;
3306       Mask = TRI->getCallPreservedMask(MF, CallConv);
3307     }
3308   } else
3309     Mask = TRI->getCallPreservedMask(MF, CallConv);
3310
3311   assert(Mask && "Missing call preserved mask for calling convention");
3312   Ops.push_back(DAG.getRegisterMask(Mask));
3313
3314   if (InFlag.getNode())
3315     Ops.push_back(InFlag);
3316
3317   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3318
3319   // If we're doing a tall call, use a TC_RETURN here rather than an
3320   // actual call instruction.
3321   if (IsTailCall) {
3322     MF.getFrameInfo().setHasTailCall();
3323     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3324   }
3325
3326   // Returns a chain and a flag for retval copy to use.
3327   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3328   InFlag = Chain.getValue(1);
3329
3330   uint64_t CalleePopBytes =
3331       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3332
3333   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3334                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3335                              InFlag, DL);
3336   if (!Ins.empty())
3337     InFlag = Chain.getValue(1);
3338
3339   // Handle result values, copying them out of physregs into vregs that we
3340   // return.
3341   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3342                          InVals, IsThisReturn,
3343                          IsThisReturn ? OutVals[0] : SDValue());
3344 }
3345
3346 bool AArch64TargetLowering::CanLowerReturn(
3347     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3348     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3349   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3350                           ? RetCC_AArch64_WebKit_JS
3351                           : RetCC_AArch64_AAPCS;
3352   SmallVector<CCValAssign, 16> RVLocs;
3353   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3354   return CCInfo.CheckReturn(Outs, RetCC);
3355 }
3356
3357 SDValue
3358 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3359                                    bool isVarArg,
3360                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3361                                    const SmallVectorImpl<SDValue> &OutVals,
3362                                    const SDLoc &DL, SelectionDAG &DAG) const {
3363   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3364                           ? RetCC_AArch64_WebKit_JS
3365                           : RetCC_AArch64_AAPCS;
3366   SmallVector<CCValAssign, 16> RVLocs;
3367   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3368                  *DAG.getContext());
3369   CCInfo.AnalyzeReturn(Outs, RetCC);
3370
3371   // Copy the result values into the output registers.
3372   SDValue Flag;
3373   SmallVector<SDValue, 4> RetOps(1, Chain);
3374   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3375        ++i, ++realRVLocIdx) {
3376     CCValAssign &VA = RVLocs[i];
3377     assert(VA.isRegLoc() && "Can only return in registers!");
3378     SDValue Arg = OutVals[realRVLocIdx];
3379
3380     switch (VA.getLocInfo()) {
3381     default:
3382       llvm_unreachable("Unknown loc info!");
3383     case CCValAssign::Full:
3384       if (Outs[i].ArgVT == MVT::i1) {
3385         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3386         // value. This is strictly redundant on Darwin (which uses "zeroext
3387         // i1"), but will be optimised out before ISel.
3388         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3389         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3390       }
3391       break;
3392     case CCValAssign::BCvt:
3393       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3394       break;
3395     }
3396
3397     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3398     Flag = Chain.getValue(1);
3399     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3400   }
3401   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3402   const MCPhysReg *I =
3403       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3404   if (I) {
3405     for (; *I; ++I) {
3406       if (AArch64::GPR64RegClass.contains(*I))
3407         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3408       else if (AArch64::FPR64RegClass.contains(*I))
3409         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3410       else
3411         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3412     }
3413   }
3414
3415   RetOps[0] = Chain; // Update chain.
3416
3417   // Add the flag if we have it.
3418   if (Flag.getNode())
3419     RetOps.push_back(Flag);
3420
3421   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3422 }
3423
3424 //===----------------------------------------------------------------------===//
3425 //  Other Lowering Code
3426 //===----------------------------------------------------------------------===//
3427
3428 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3429                                                   SelectionDAG &DAG) const {
3430   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3431   SDLoc DL(Op);
3432   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3433   const GlobalValue *GV = GN->getGlobal();
3434   unsigned char OpFlags =
3435       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3436
3437   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3438          "unexpected offset in global node");
3439
3440   // This also catched the large code model case for Darwin.
3441   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3442     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3443     // FIXME: Once remat is capable of dealing with instructions with register
3444     // operands, expand this into two nodes instead of using a wrapper node.
3445     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3446   }
3447
3448   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3449     const unsigned char MO_NC = AArch64II::MO_NC;
3450     return DAG.getNode(
3451         AArch64ISD::WrapperLarge, DL, PtrVT,
3452         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3453         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3454         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3455         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3456   } else {
3457     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3458     // the only correct model on Darwin.
3459     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3460                                             OpFlags | AArch64II::MO_PAGE);
3461     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3462     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3463
3464     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3465     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3466   }
3467 }
3468
3469 /// \brief Convert a TLS address reference into the correct sequence of loads
3470 /// and calls to compute the variable's address (for Darwin, currently) and
3471 /// return an SDValue containing the final node.
3472
3473 /// Darwin only has one TLS scheme which must be capable of dealing with the
3474 /// fully general situation, in the worst case. This means:
3475 ///     + "extern __thread" declaration.
3476 ///     + Defined in a possibly unknown dynamic library.
3477 ///
3478 /// The general system is that each __thread variable has a [3 x i64] descriptor
3479 /// which contains information used by the runtime to calculate the address. The
3480 /// only part of this the compiler needs to know about is the first xword, which
3481 /// contains a function pointer that must be called with the address of the
3482 /// entire descriptor in "x0".
3483 ///
3484 /// Since this descriptor may be in a different unit, in general even the
3485 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3486 /// is:
3487 ///     adrp x0, _var@TLVPPAGE
3488 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3489 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3490 ///                                      ; the function pointer
3491 ///     blr x1                           ; Uses descriptor address in x0
3492 ///     ; Address of _var is now in x0.
3493 ///
3494 /// If the address of _var's descriptor *is* known to the linker, then it can
3495 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3496 /// a slight efficiency gain.
3497 SDValue
3498 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3499                                                    SelectionDAG &DAG) const {
3500   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3501
3502   SDLoc DL(Op);
3503   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3504   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3505
3506   SDValue TLVPAddr =
3507       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3508   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3509
3510   // The first entry in the descriptor is a function pointer that we must call
3511   // to obtain the address of the variable.
3512   SDValue Chain = DAG.getEntryNode();
3513   SDValue FuncTLVGet = DAG.getLoad(
3514       MVT::i64, DL, Chain, DescAddr,
3515       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3516       /* Alignment = */ 8,
3517       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3518           MachineMemOperand::MODereferenceable);
3519   Chain = FuncTLVGet.getValue(1);
3520
3521   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3522   MFI.setAdjustsStack(true);
3523
3524   // TLS calls preserve all registers except those that absolutely must be
3525   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3526   // silly).
3527   const uint32_t *Mask =
3528       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3529
3530   // Finally, we can make the call. This is just a degenerate version of a
3531   // normal AArch64 call node: x0 takes the address of the descriptor, and
3532   // returns the address of the variable in this thread.
3533   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3534   Chain =
3535       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3536                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3537                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3538   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3539 }
3540
3541 /// When accessing thread-local variables under either the general-dynamic or
3542 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3543 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3544 /// is a function pointer to carry out the resolution.
3545 ///
3546 /// The sequence is:
3547 ///    adrp  x0, :tlsdesc:var
3548 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3549 ///    add   x0, x0, #:tlsdesc_lo12:var
3550 ///    .tlsdesccall var
3551 ///    blr   x1
3552 ///    (TPIDR_EL0 offset now in x0)
3553 ///
3554 ///  The above sequence must be produced unscheduled, to enable the linker to
3555 ///  optimize/relax this sequence.
3556 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3557 ///  above sequence, and expanded really late in the compilation flow, to ensure
3558 ///  the sequence is produced as per above.
3559 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3560                                                       const SDLoc &DL,
3561                                                       SelectionDAG &DAG) const {
3562   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3563
3564   SDValue Chain = DAG.getEntryNode();
3565   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3566
3567   Chain =
3568       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3569   SDValue Glue = Chain.getValue(1);
3570
3571   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3572 }
3573
3574 SDValue
3575 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3576                                                 SelectionDAG &DAG) const {
3577   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3578   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3579          "ELF TLS only supported in small memory model");
3580   // Different choices can be made for the maximum size of the TLS area for a
3581   // module. For the small address model, the default TLS size is 16MiB and the
3582   // maximum TLS size is 4GiB.
3583   // FIXME: add -mtls-size command line option and make it control the 16MiB
3584   // vs. 4GiB code sequence generation.
3585   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3586
3587   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3588
3589   if (DAG.getTarget().Options.EmulatedTLS)
3590     return LowerToTLSEmulatedModel(GA, DAG);
3591
3592   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3593     if (Model == TLSModel::LocalDynamic)
3594       Model = TLSModel::GeneralDynamic;
3595   }
3596
3597   SDValue TPOff;
3598   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3599   SDLoc DL(Op);
3600   const GlobalValue *GV = GA->getGlobal();
3601
3602   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3603
3604   if (Model == TLSModel::LocalExec) {
3605     SDValue HiVar = DAG.getTargetGlobalAddress(
3606         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3607     SDValue LoVar = DAG.getTargetGlobalAddress(
3608         GV, DL, PtrVT, 0,
3609         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3610
3611     SDValue TPWithOff_lo =
3612         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3613                                    HiVar,
3614                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3615                 0);
3616     SDValue TPWithOff =
3617         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3618                                    LoVar,
3619                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3620                 0);
3621     return TPWithOff;
3622   } else if (Model == TLSModel::InitialExec) {
3623     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3624     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3625   } else if (Model == TLSModel::LocalDynamic) {
3626     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3627     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3628     // the beginning of the module's TLS region, followed by a DTPREL offset
3629     // calculation.
3630
3631     // These accesses will need deduplicating if there's more than one.
3632     AArch64FunctionInfo *MFI =
3633         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3634     MFI->incNumLocalDynamicTLSAccesses();
3635
3636     // The call needs a relocation too for linker relaxation. It doesn't make
3637     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3638     // the address.
3639     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3640                                                   AArch64II::MO_TLS);
3641
3642     // Now we can calculate the offset from TPIDR_EL0 to this module's
3643     // thread-local area.
3644     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3645
3646     // Now use :dtprel_whatever: operations to calculate this variable's offset
3647     // in its thread-storage area.
3648     SDValue HiVar = DAG.getTargetGlobalAddress(
3649         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3650     SDValue LoVar = DAG.getTargetGlobalAddress(
3651         GV, DL, MVT::i64, 0,
3652         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3653
3654     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3655                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3656                     0);
3657     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3658                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3659                     0);
3660   } else if (Model == TLSModel::GeneralDynamic) {
3661     // The call needs a relocation too for linker relaxation. It doesn't make
3662     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3663     // the address.
3664     SDValue SymAddr =
3665         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3666
3667     // Finally we can make a call to calculate the offset from tpidr_el0.
3668     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3669   } else
3670     llvm_unreachable("Unsupported ELF TLS access model");
3671
3672   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3673 }
3674
3675 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3676                                                      SelectionDAG &DAG) const {
3677   if (Subtarget->isTargetDarwin())
3678     return LowerDarwinGlobalTLSAddress(Op, DAG);
3679   else if (Subtarget->isTargetELF())
3680     return LowerELFGlobalTLSAddress(Op, DAG);
3681
3682   llvm_unreachable("Unexpected platform trying to use TLS");
3683 }
3684
3685 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3686   SDValue Chain = Op.getOperand(0);
3687   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3688   SDValue LHS = Op.getOperand(2);
3689   SDValue RHS = Op.getOperand(3);
3690   SDValue Dest = Op.getOperand(4);
3691   SDLoc dl(Op);
3692
3693   // Handle f128 first, since lowering it will result in comparing the return
3694   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3695   // is expecting to deal with.
3696   if (LHS.getValueType() == MVT::f128) {
3697     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3698
3699     // If softenSetCCOperands returned a scalar, we need to compare the result
3700     // against zero to select between true and false values.
3701     if (!RHS.getNode()) {
3702       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3703       CC = ISD::SETNE;
3704     }
3705   }
3706
3707   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3708   // instruction.
3709   unsigned Opc = LHS.getOpcode();
3710   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3711       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3712        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3713     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3714            "Unexpected condition code.");
3715     // Only lower legal XALUO ops.
3716     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3717       return SDValue();
3718
3719     // The actual operation with overflow check.
3720     AArch64CC::CondCode OFCC;
3721     SDValue Value, Overflow;
3722     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3723
3724     if (CC == ISD::SETNE)
3725       OFCC = getInvertedCondCode(OFCC);
3726     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3727
3728     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3729                        Overflow);
3730   }
3731
3732   if (LHS.getValueType().isInteger()) {
3733     assert((LHS.getValueType() == RHS.getValueType()) &&
3734            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3735
3736     // If the RHS of the comparison is zero, we can potentially fold this
3737     // to a specialized branch.
3738     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3739     if (RHSC && RHSC->getZExtValue() == 0) {
3740       if (CC == ISD::SETEQ) {
3741         // See if we can use a TBZ to fold in an AND as well.
3742         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3743         // out of bounds, a late MI-layer pass rewrites branches.
3744         // 403.gcc is an example that hits this case.
3745         if (LHS.getOpcode() == ISD::AND &&
3746             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3747             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3748           SDValue Test = LHS.getOperand(0);
3749           uint64_t Mask = LHS.getConstantOperandVal(1);
3750           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3751                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3752                              Dest);
3753         }
3754
3755         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3756       } else if (CC == ISD::SETNE) {
3757         // See if we can use a TBZ to fold in an AND as well.
3758         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3759         // out of bounds, a late MI-layer pass rewrites branches.
3760         // 403.gcc is an example that hits this case.
3761         if (LHS.getOpcode() == ISD::AND &&
3762             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3763             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3764           SDValue Test = LHS.getOperand(0);
3765           uint64_t Mask = LHS.getConstantOperandVal(1);
3766           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3767                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3768                              Dest);
3769         }
3770
3771         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3772       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3773         // Don't combine AND since emitComparison converts the AND to an ANDS
3774         // (a.k.a. TST) and the test in the test bit and branch instruction
3775         // becomes redundant.  This would also increase register pressure.
3776         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3777         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3778                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3779       }
3780     }
3781     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3782         LHS.getOpcode() != ISD::AND) {
3783       // Don't combine AND since emitComparison converts the AND to an ANDS
3784       // (a.k.a. TST) and the test in the test bit and branch instruction
3785       // becomes redundant.  This would also increase register pressure.
3786       uint64_t Mask = LHS.getValueSizeInBits() - 1;
3787       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3788                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3789     }
3790
3791     SDValue CCVal;
3792     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3793     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3794                        Cmp);
3795   }
3796
3797   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3798
3799   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3800   // clean.  Some of them require two branches to implement.
3801   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3802   AArch64CC::CondCode CC1, CC2;
3803   changeFPCCToAArch64CC(CC, CC1, CC2);
3804   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3805   SDValue BR1 =
3806       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3807   if (CC2 != AArch64CC::AL) {
3808     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3809     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3810                        Cmp);
3811   }
3812
3813   return BR1;
3814 }
3815
3816 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3817                                               SelectionDAG &DAG) const {
3818   EVT VT = Op.getValueType();
3819   SDLoc DL(Op);
3820
3821   SDValue In1 = Op.getOperand(0);
3822   SDValue In2 = Op.getOperand(1);
3823   EVT SrcVT = In2.getValueType();
3824
3825   if (SrcVT.bitsLT(VT))
3826     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3827   else if (SrcVT.bitsGT(VT))
3828     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3829
3830   EVT VecVT;
3831   EVT EltVT;
3832   uint64_t EltMask;
3833   SDValue VecVal1, VecVal2;
3834   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3835     EltVT = MVT::i32;
3836     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3837     EltMask = 0x80000000ULL;
3838
3839     if (!VT.isVector()) {
3840       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3841                                           DAG.getUNDEF(VecVT), In1);
3842       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3843                                           DAG.getUNDEF(VecVT), In2);
3844     } else {
3845       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3846       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3847     }
3848   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3849     EltVT = MVT::i64;
3850     VecVT = MVT::v2i64;
3851
3852     // We want to materialize a mask with the high bit set, but the AdvSIMD
3853     // immediate moves cannot materialize that in a single instruction for
3854     // 64-bit elements. Instead, materialize zero and then negate it.
3855     EltMask = 0;
3856
3857     if (!VT.isVector()) {
3858       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3859                                           DAG.getUNDEF(VecVT), In1);
3860       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3861                                           DAG.getUNDEF(VecVT), In2);
3862     } else {
3863       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3864       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3865     }
3866   } else {
3867     llvm_unreachable("Invalid type for copysign!");
3868   }
3869
3870   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3871
3872   // If we couldn't materialize the mask above, then the mask vector will be
3873   // the zero vector, and we need to negate it here.
3874   if (VT == MVT::f64 || VT == MVT::v2f64) {
3875     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3876     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3877     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3878   }
3879
3880   SDValue Sel =
3881       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3882
3883   if (VT == MVT::f32)
3884     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3885   else if (VT == MVT::f64)
3886     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3887   else
3888     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3889 }
3890
3891 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3892   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3893           Attribute::NoImplicitFloat))
3894     return SDValue();
3895
3896   if (!Subtarget->hasNEON())
3897     return SDValue();
3898
3899   // While there is no integer popcount instruction, it can
3900   // be more efficiently lowered to the following sequence that uses
3901   // AdvSIMD registers/instructions as long as the copies to/from
3902   // the AdvSIMD registers are cheap.
3903   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3904   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3905   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3906   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3907   SDValue Val = Op.getOperand(0);
3908   SDLoc DL(Op);
3909   EVT VT = Op.getValueType();
3910
3911   if (VT == MVT::i32)
3912     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3913   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3914
3915   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3916   SDValue UaddLV = DAG.getNode(
3917       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3918       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3919
3920   if (VT == MVT::i64)
3921     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3922   return UaddLV;
3923 }
3924
3925 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3926
3927   if (Op.getValueType().isVector())
3928     return LowerVSETCC(Op, DAG);
3929
3930   SDValue LHS = Op.getOperand(0);
3931   SDValue RHS = Op.getOperand(1);
3932   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3933   SDLoc dl(Op);
3934
3935   // We chose ZeroOrOneBooleanContents, so use zero and one.
3936   EVT VT = Op.getValueType();
3937   SDValue TVal = DAG.getConstant(1, dl, VT);
3938   SDValue FVal = DAG.getConstant(0, dl, VT);
3939
3940   // Handle f128 first, since one possible outcome is a normal integer
3941   // comparison which gets picked up by the next if statement.
3942   if (LHS.getValueType() == MVT::f128) {
3943     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3944
3945     // If softenSetCCOperands returned a scalar, use it.
3946     if (!RHS.getNode()) {
3947       assert(LHS.getValueType() == Op.getValueType() &&
3948              "Unexpected setcc expansion!");
3949       return LHS;
3950     }
3951   }
3952
3953   if (LHS.getValueType().isInteger()) {
3954     SDValue CCVal;
3955     SDValue Cmp =
3956         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3957
3958     // Note that we inverted the condition above, so we reverse the order of
3959     // the true and false operands here.  This will allow the setcc to be
3960     // matched to a single CSINC instruction.
3961     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3962   }
3963
3964   // Now we know we're dealing with FP values.
3965   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3966
3967   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3968   // and do the comparison.
3969   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3970
3971   AArch64CC::CondCode CC1, CC2;
3972   changeFPCCToAArch64CC(CC, CC1, CC2);
3973   if (CC2 == AArch64CC::AL) {
3974     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3975     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3976
3977     // Note that we inverted the condition above, so we reverse the order of
3978     // the true and false operands here.  This will allow the setcc to be
3979     // matched to a single CSINC instruction.
3980     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3981   } else {
3982     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3983     // totally clean.  Some of them require two CSELs to implement.  As is in
3984     // this case, we emit the first CSEL and then emit a second using the output
3985     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3986
3987     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3988     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3989     SDValue CS1 =
3990         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3991
3992     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3993     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3994   }
3995 }
3996
3997 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3998                                               SDValue RHS, SDValue TVal,
3999                                               SDValue FVal, const SDLoc &dl,
4000                                               SelectionDAG &DAG) const {
4001   // Handle f128 first, because it will result in a comparison of some RTLIB
4002   // call result against zero.
4003   if (LHS.getValueType() == MVT::f128) {
4004     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4005
4006     // If softenSetCCOperands returned a scalar, we need to compare the result
4007     // against zero to select between true and false values.
4008     if (!RHS.getNode()) {
4009       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4010       CC = ISD::SETNE;
4011     }
4012   }
4013
4014   // Also handle f16, for which we need to do a f32 comparison.
4015   if (LHS.getValueType() == MVT::f16) {
4016     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4017     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4018   }
4019
4020   // Next, handle integers.
4021   if (LHS.getValueType().isInteger()) {
4022     assert((LHS.getValueType() == RHS.getValueType()) &&
4023            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4024
4025     unsigned Opcode = AArch64ISD::CSEL;
4026
4027     // If both the TVal and the FVal are constants, see if we can swap them in
4028     // order to for a CSINV or CSINC out of them.
4029     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4030     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4031
4032     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4033       std::swap(TVal, FVal);
4034       std::swap(CTVal, CFVal);
4035       CC = ISD::getSetCCInverse(CC, true);
4036     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4037       std::swap(TVal, FVal);
4038       std::swap(CTVal, CFVal);
4039       CC = ISD::getSetCCInverse(CC, true);
4040     } else if (TVal.getOpcode() == ISD::XOR) {
4041       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4042       // with a CSINV rather than a CSEL.
4043       if (isAllOnesConstant(TVal.getOperand(1))) {
4044         std::swap(TVal, FVal);
4045         std::swap(CTVal, CFVal);
4046         CC = ISD::getSetCCInverse(CC, true);
4047       }
4048     } else if (TVal.getOpcode() == ISD::SUB) {
4049       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4050       // that we can match with a CSNEG rather than a CSEL.
4051       if (isNullConstant(TVal.getOperand(0))) {
4052         std::swap(TVal, FVal);
4053         std::swap(CTVal, CFVal);
4054         CC = ISD::getSetCCInverse(CC, true);
4055       }
4056     } else if (CTVal && CFVal) {
4057       const int64_t TrueVal = CTVal->getSExtValue();
4058       const int64_t FalseVal = CFVal->getSExtValue();
4059       bool Swap = false;
4060
4061       // If both TVal and FVal are constants, see if FVal is the
4062       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4063       // instead of a CSEL in that case.
4064       if (TrueVal == ~FalseVal) {
4065         Opcode = AArch64ISD::CSINV;
4066       } else if (TrueVal == -FalseVal) {
4067         Opcode = AArch64ISD::CSNEG;
4068       } else if (TVal.getValueType() == MVT::i32) {
4069         // If our operands are only 32-bit wide, make sure we use 32-bit
4070         // arithmetic for the check whether we can use CSINC. This ensures that
4071         // the addition in the check will wrap around properly in case there is
4072         // an overflow (which would not be the case if we do the check with
4073         // 64-bit arithmetic).
4074         const uint32_t TrueVal32 = CTVal->getZExtValue();
4075         const uint32_t FalseVal32 = CFVal->getZExtValue();
4076
4077         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4078           Opcode = AArch64ISD::CSINC;
4079
4080           if (TrueVal32 > FalseVal32) {
4081             Swap = true;
4082           }
4083         }
4084         // 64-bit check whether we can use CSINC.
4085       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4086         Opcode = AArch64ISD::CSINC;
4087
4088         if (TrueVal > FalseVal) {
4089           Swap = true;
4090         }
4091       }
4092
4093       // Swap TVal and FVal if necessary.
4094       if (Swap) {
4095         std::swap(TVal, FVal);
4096         std::swap(CTVal, CFVal);
4097         CC = ISD::getSetCCInverse(CC, true);
4098       }
4099
4100       if (Opcode != AArch64ISD::CSEL) {
4101         // Drop FVal since we can get its value by simply inverting/negating
4102         // TVal.
4103         FVal = TVal;
4104       }
4105     }
4106
4107     // Avoid materializing a constant when possible by reusing a known value in
4108     // a register.  However, don't perform this optimization if the known value
4109     // is one, zero or negative one in the case of a CSEL.  We can always
4110     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4111     // FVal, respectively.
4112     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4113     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4114         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4115       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4116       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4117       // "a != C ? x : a" to avoid materializing C.
4118       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4119         TVal = LHS;
4120       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4121         FVal = LHS;
4122     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4123       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4124       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4125       // avoid materializing C.
4126       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4127       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4128         Opcode = AArch64ISD::CSINV;
4129         TVal = LHS;
4130         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4131       }
4132     }
4133
4134     SDValue CCVal;
4135     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4136
4137     EVT VT = TVal.getValueType();
4138     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4139   }
4140
4141   // Now we know we're dealing with FP values.
4142   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4143   assert(LHS.getValueType() == RHS.getValueType());
4144   EVT VT = TVal.getValueType();
4145   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4146
4147   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4148   // clean.  Some of them require two CSELs to implement.
4149   AArch64CC::CondCode CC1, CC2;
4150   changeFPCCToAArch64CC(CC, CC1, CC2);
4151
4152   if (DAG.getTarget().Options.UnsafeFPMath) {
4153     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4154     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4155     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4156     if (RHSVal && RHSVal->isZero()) {
4157       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4158       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4159
4160       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4161           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4162         TVal = LHS;
4163       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4164                CFVal && CFVal->isZero() &&
4165                FVal.getValueType() == LHS.getValueType())
4166         FVal = LHS;
4167     }
4168   }
4169
4170   // Emit first, and possibly only, CSEL.
4171   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4172   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4173
4174   // If we need a second CSEL, emit it, using the output of the first as the
4175   // RHS.  We're effectively OR'ing the two CC's together.
4176   if (CC2 != AArch64CC::AL) {
4177     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4178     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4179   }
4180
4181   // Otherwise, return the output of the first CSEL.
4182   return CS1;
4183 }
4184
4185 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4186                                               SelectionDAG &DAG) const {
4187   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4188   SDValue LHS = Op.getOperand(0);
4189   SDValue RHS = Op.getOperand(1);
4190   SDValue TVal = Op.getOperand(2);
4191   SDValue FVal = Op.getOperand(3);
4192   SDLoc DL(Op);
4193   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4194 }
4195
4196 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4197                                            SelectionDAG &DAG) const {
4198   SDValue CCVal = Op->getOperand(0);
4199   SDValue TVal = Op->getOperand(1);
4200   SDValue FVal = Op->getOperand(2);
4201   SDLoc DL(Op);
4202
4203   unsigned Opc = CCVal.getOpcode();
4204   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4205   // instruction.
4206   if (CCVal.getResNo() == 1 &&
4207       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4208        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4209     // Only lower legal XALUO ops.
4210     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4211       return SDValue();
4212
4213     AArch64CC::CondCode OFCC;
4214     SDValue Value, Overflow;
4215     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4216     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4217
4218     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4219                        CCVal, Overflow);
4220   }
4221
4222   // Lower it the same way as we would lower a SELECT_CC node.
4223   ISD::CondCode CC;
4224   SDValue LHS, RHS;
4225   if (CCVal.getOpcode() == ISD::SETCC) {
4226     LHS = CCVal.getOperand(0);
4227     RHS = CCVal.getOperand(1);
4228     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4229   } else {
4230     LHS = CCVal;
4231     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4232     CC = ISD::SETNE;
4233   }
4234   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4235 }
4236
4237 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4238                                               SelectionDAG &DAG) const {
4239   // Jump table entries as PC relative offsets. No additional tweaking
4240   // is necessary here. Just get the address of the jump table.
4241   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4242   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4243   SDLoc DL(Op);
4244
4245   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4246       !Subtarget->isTargetMachO()) {
4247     const unsigned char MO_NC = AArch64II::MO_NC;
4248     return DAG.getNode(
4249         AArch64ISD::WrapperLarge, DL, PtrVT,
4250         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4251         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4252         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4253         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4254                                AArch64II::MO_G0 | MO_NC));
4255   }
4256
4257   SDValue Hi =
4258       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4259   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4260                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4261   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4262   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4263 }
4264
4265 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4266                                                  SelectionDAG &DAG) const {
4267   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4268   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4269   SDLoc DL(Op);
4270
4271   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4272     // Use the GOT for the large code model on iOS.
4273     if (Subtarget->isTargetMachO()) {
4274       SDValue GotAddr = DAG.getTargetConstantPool(
4275           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4276           AArch64II::MO_GOT);
4277       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4278     }
4279
4280     const unsigned char MO_NC = AArch64II::MO_NC;
4281     return DAG.getNode(
4282         AArch64ISD::WrapperLarge, DL, PtrVT,
4283         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4284                                   CP->getOffset(), AArch64II::MO_G3),
4285         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4286                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4287         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4288                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4289         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4290                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4291   } else {
4292     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4293     // ELF, the only valid one on Darwin.
4294     SDValue Hi =
4295         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4296                                   CP->getOffset(), AArch64II::MO_PAGE);
4297     SDValue Lo = DAG.getTargetConstantPool(
4298         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4299         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4300
4301     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4302     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4303   }
4304 }
4305
4306 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4307                                                SelectionDAG &DAG) const {
4308   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4309   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4310   SDLoc DL(Op);
4311   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4312       !Subtarget->isTargetMachO()) {
4313     const unsigned char MO_NC = AArch64II::MO_NC;
4314     return DAG.getNode(
4315         AArch64ISD::WrapperLarge, DL, PtrVT,
4316         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4317         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4318         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4319         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4320   } else {
4321     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4322     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4323                                                              AArch64II::MO_NC);
4324     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4325     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4326   }
4327 }
4328
4329 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4330                                                  SelectionDAG &DAG) const {
4331   AArch64FunctionInfo *FuncInfo =
4332       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4333
4334   SDLoc DL(Op);
4335   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4336                                  getPointerTy(DAG.getDataLayout()));
4337   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4338   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4339                       MachinePointerInfo(SV));
4340 }
4341
4342 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4343                                                 SelectionDAG &DAG) const {
4344   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4345   // Standard, section B.3.
4346   MachineFunction &MF = DAG.getMachineFunction();
4347   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4348   auto PtrVT = getPointerTy(DAG.getDataLayout());
4349   SDLoc DL(Op);
4350
4351   SDValue Chain = Op.getOperand(0);
4352   SDValue VAList = Op.getOperand(1);
4353   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4354   SmallVector<SDValue, 4> MemOps;
4355
4356   // void *__stack at offset 0
4357   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4358   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4359                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4360
4361   // void *__gr_top at offset 8
4362   int GPRSize = FuncInfo->getVarArgsGPRSize();
4363   if (GPRSize > 0) {
4364     SDValue GRTop, GRTopAddr;
4365
4366     GRTopAddr =
4367         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4368
4369     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4370     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4371                         DAG.getConstant(GPRSize, DL, PtrVT));
4372
4373     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4374                                   MachinePointerInfo(SV, 8),
4375                                   /* Alignment = */ 8));
4376   }
4377
4378   // void *__vr_top at offset 16
4379   int FPRSize = FuncInfo->getVarArgsFPRSize();
4380   if (FPRSize > 0) {
4381     SDValue VRTop, VRTopAddr;
4382     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4383                             DAG.getConstant(16, DL, PtrVT));
4384
4385     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4386     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4387                         DAG.getConstant(FPRSize, DL, PtrVT));
4388
4389     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4390                                   MachinePointerInfo(SV, 16),
4391                                   /* Alignment = */ 8));
4392   }
4393
4394   // int __gr_offs at offset 24
4395   SDValue GROffsAddr =
4396       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4397   MemOps.push_back(DAG.getStore(
4398       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4399       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4400
4401   // int __vr_offs at offset 28
4402   SDValue VROffsAddr =
4403       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4404   MemOps.push_back(DAG.getStore(
4405       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4406       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4407
4408   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4409 }
4410
4411 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4412                                             SelectionDAG &DAG) const {
4413   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4414                                      : LowerAAPCS_VASTART(Op, DAG);
4415 }
4416
4417 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4418                                            SelectionDAG &DAG) const {
4419   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4420   // pointer.
4421   SDLoc DL(Op);
4422   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4423   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4424   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4425
4426   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4427                        Op.getOperand(2),
4428                        DAG.getConstant(VaListSize, DL, MVT::i32),
4429                        8, false, false, false, MachinePointerInfo(DestSV),
4430                        MachinePointerInfo(SrcSV));
4431 }
4432
4433 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4434   assert(Subtarget->isTargetDarwin() &&
4435          "automatic va_arg instruction only works on Darwin");
4436
4437   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4438   EVT VT = Op.getValueType();
4439   SDLoc DL(Op);
4440   SDValue Chain = Op.getOperand(0);
4441   SDValue Addr = Op.getOperand(1);
4442   unsigned Align = Op.getConstantOperandVal(3);
4443   auto PtrVT = getPointerTy(DAG.getDataLayout());
4444
4445   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4446   Chain = VAList.getValue(1);
4447
4448   if (Align > 8) {
4449     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4450     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4451                          DAG.getConstant(Align - 1, DL, PtrVT));
4452     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4453                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4454   }
4455
4456   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4457   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4458
4459   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4460   // up to 64 bits.  At the very least, we have to increase the striding of the
4461   // vaargs list to match this, and for FP values we need to introduce
4462   // FP_ROUND nodes as well.
4463   if (VT.isInteger() && !VT.isVector())
4464     ArgSize = 8;
4465   bool NeedFPTrunc = false;
4466   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4467     ArgSize = 8;
4468     NeedFPTrunc = true;
4469   }
4470
4471   // Increment the pointer, VAList, to the next vaarg
4472   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4473                                DAG.getConstant(ArgSize, DL, PtrVT));
4474   // Store the incremented VAList to the legalized pointer
4475   SDValue APStore =
4476       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4477
4478   // Load the actual argument out of the pointer VAList
4479   if (NeedFPTrunc) {
4480     // Load the value as an f64.
4481     SDValue WideFP =
4482         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4483     // Round the value down to an f32.
4484     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4485                                    DAG.getIntPtrConstant(1, DL));
4486     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4487     // Merge the rounded value with the chain output of the load.
4488     return DAG.getMergeValues(Ops, DL);
4489   }
4490
4491   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4492 }
4493
4494 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4495                                               SelectionDAG &DAG) const {
4496   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4497   MFI.setFrameAddressIsTaken(true);
4498
4499   EVT VT = Op.getValueType();
4500   SDLoc DL(Op);
4501   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4502   SDValue FrameAddr =
4503       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4504   while (Depth--)
4505     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4506                             MachinePointerInfo());
4507   return FrameAddr;
4508 }
4509
4510 // FIXME? Maybe this could be a TableGen attribute on some registers and
4511 // this table could be generated automatically from RegInfo.
4512 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4513                                                   SelectionDAG &DAG) const {
4514   unsigned Reg = StringSwitch<unsigned>(RegName)
4515                        .Case("sp", AArch64::SP)
4516                        .Default(0);
4517   if (Reg)
4518     return Reg;
4519   report_fatal_error(Twine("Invalid register name \""
4520                               + StringRef(RegName)  + "\"."));
4521 }
4522
4523 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4524                                                SelectionDAG &DAG) const {
4525   MachineFunction &MF = DAG.getMachineFunction();
4526   MachineFrameInfo &MFI = MF.getFrameInfo();
4527   MFI.setReturnAddressIsTaken(true);
4528
4529   EVT VT = Op.getValueType();
4530   SDLoc DL(Op);
4531   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4532   if (Depth) {
4533     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4534     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4535     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4536                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4537                        MachinePointerInfo());
4538   }
4539
4540   // Return LR, which contains the return address. Mark it an implicit live-in.
4541   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4542   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4543 }
4544
4545 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4546 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4547 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4548                                                     SelectionDAG &DAG) const {
4549   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4550   EVT VT = Op.getValueType();
4551   unsigned VTBits = VT.getSizeInBits();
4552   SDLoc dl(Op);
4553   SDValue ShOpLo = Op.getOperand(0);
4554   SDValue ShOpHi = Op.getOperand(1);
4555   SDValue ShAmt = Op.getOperand(2);
4556   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4557
4558   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4559
4560   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4561                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4562   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4563
4564   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4565   // is "undef". We wanted 0, so CSEL it directly.
4566   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4567                                ISD::SETEQ, dl, DAG);
4568   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4569   HiBitsForLo =
4570       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4571                   HiBitsForLo, CCVal, Cmp);
4572
4573   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4574                                    DAG.getConstant(VTBits, dl, MVT::i64));
4575
4576   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4577   SDValue LoForNormalShift =
4578       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4579
4580   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4581                        dl, DAG);
4582   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4583   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4584   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4585                            LoForNormalShift, CCVal, Cmp);
4586
4587   // AArch64 shifts larger than the register width are wrapped rather than
4588   // clamped, so we can't just emit "hi >> x".
4589   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4590   SDValue HiForBigShift =
4591       Opc == ISD::SRA
4592           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4593                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4594           : DAG.getConstant(0, dl, VT);
4595   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4596                            HiForNormalShift, CCVal, Cmp);
4597
4598   SDValue Ops[2] = { Lo, Hi };
4599   return DAG.getMergeValues(Ops, dl);
4600 }
4601
4602 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4603 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4604 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4605                                                    SelectionDAG &DAG) const {
4606   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4607   EVT VT = Op.getValueType();
4608   unsigned VTBits = VT.getSizeInBits();
4609   SDLoc dl(Op);
4610   SDValue ShOpLo = Op.getOperand(0);
4611   SDValue ShOpHi = Op.getOperand(1);
4612   SDValue ShAmt = Op.getOperand(2);
4613
4614   assert(Op.getOpcode() == ISD::SHL_PARTS);
4615   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4616                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4617   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4618
4619   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4620   // is "undef". We wanted 0, so CSEL it directly.
4621   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4622                                ISD::SETEQ, dl, DAG);
4623   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4624   LoBitsForHi =
4625       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4626                   LoBitsForHi, CCVal, Cmp);
4627
4628   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4629                                    DAG.getConstant(VTBits, dl, MVT::i64));
4630   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4631   SDValue HiForNormalShift =
4632       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4633
4634   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4635
4636   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4637                        dl, DAG);
4638   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4639   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4640                            HiForNormalShift, CCVal, Cmp);
4641
4642   // AArch64 shifts of larger than register sizes are wrapped rather than
4643   // clamped, so we can't just emit "lo << a" if a is too big.
4644   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4645   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4646   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4647                            LoForNormalShift, CCVal, Cmp);
4648
4649   SDValue Ops[2] = { Lo, Hi };
4650   return DAG.getMergeValues(Ops, dl);
4651 }
4652
4653 bool AArch64TargetLowering::isOffsetFoldingLegal(
4654     const GlobalAddressSDNode *GA) const {
4655   // The AArch64 target doesn't support folding offsets into global addresses.
4656   return false;
4657 }
4658
4659 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4660   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4661   // FIXME: We should be able to handle f128 as well with a clever lowering.
4662   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4663     return true;
4664
4665   if (VT == MVT::f64)
4666     return AArch64_AM::getFP64Imm(Imm) != -1;
4667   else if (VT == MVT::f32)
4668     return AArch64_AM::getFP32Imm(Imm) != -1;
4669   return false;
4670 }
4671
4672 //===----------------------------------------------------------------------===//
4673 //                          AArch64 Optimization Hooks
4674 //===----------------------------------------------------------------------===//
4675
4676 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4677                            SDValue Operand, SelectionDAG &DAG,
4678                            int &ExtraSteps) {
4679   EVT VT = Operand.getValueType();
4680   if (ST->hasNEON() &&
4681       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4682        VT == MVT::f32 || VT == MVT::v1f32 ||
4683        VT == MVT::v2f32 || VT == MVT::v4f32)) {
4684     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4685       // For the reciprocal estimates, convergence is quadratic, so the number
4686       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
4687       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
4688       // the result for float (23 mantissa bits) is 2 and for double (52
4689       // mantissa bits) is 3.
4690       ExtraSteps = VT == MVT::f64 ? 3 : 2;
4691
4692     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4693   }
4694
4695   return SDValue();
4696 }
4697
4698 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4699                                                SelectionDAG &DAG, int Enabled,
4700                                                int &ExtraSteps,
4701                                                bool &UseOneConst,
4702                                                bool Reciprocal) const {
4703   if (Enabled == ReciprocalEstimate::Enabled ||
4704       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4705     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4706                                        DAG, ExtraSteps)) {
4707       SDLoc DL(Operand);
4708       EVT VT = Operand.getValueType();
4709
4710       SDNodeFlags Flags;
4711       Flags.setUnsafeAlgebra(true);
4712
4713       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4714       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4715       for (int i = ExtraSteps; i > 0; --i) {
4716         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4717                                    &Flags);
4718         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4719         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4720       }
4721
4722       if (!Reciprocal) {
4723         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4724                                       VT);
4725         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4726         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4727
4728         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4729         // Correct the result if the operand is 0.0.
4730         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4731                                VT, Eq, Operand, Estimate);
4732       }
4733
4734       ExtraSteps = 0;
4735       return Estimate;
4736     }
4737
4738   return SDValue();
4739 }
4740
4741 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4742                                                 SelectionDAG &DAG, int Enabled,
4743                                                 int &ExtraSteps) const {
4744   if (Enabled == ReciprocalEstimate::Enabled)
4745     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4746                                        DAG, ExtraSteps)) {
4747       SDLoc DL(Operand);
4748       EVT VT = Operand.getValueType();
4749
4750       SDNodeFlags Flags;
4751       Flags.setUnsafeAlgebra(true);
4752
4753       // Newton reciprocal iteration: E * (2 - X * E)
4754       // AArch64 reciprocal iteration instruction: (2 - M * N)
4755       for (int i = ExtraSteps; i > 0; --i) {
4756         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4757                                    Estimate, &Flags);
4758         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4759       }
4760
4761       ExtraSteps = 0;
4762       return Estimate;
4763     }
4764
4765   return SDValue();
4766 }
4767
4768 //===----------------------------------------------------------------------===//
4769 //                          AArch64 Inline Assembly Support
4770 //===----------------------------------------------------------------------===//
4771
4772 // Table of Constraints
4773 // TODO: This is the current set of constraints supported by ARM for the
4774 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4775 //
4776 // r - A general register
4777 // w - An FP/SIMD register of some size in the range v0-v31
4778 // x - An FP/SIMD register of some size in the range v0-v15
4779 // I - Constant that can be used with an ADD instruction
4780 // J - Constant that can be used with a SUB instruction
4781 // K - Constant that can be used with a 32-bit logical instruction
4782 // L - Constant that can be used with a 64-bit logical instruction
4783 // M - Constant that can be used as a 32-bit MOV immediate
4784 // N - Constant that can be used as a 64-bit MOV immediate
4785 // Q - A memory reference with base register and no offset
4786 // S - A symbolic address
4787 // Y - Floating point constant zero
4788 // Z - Integer constant zero
4789 //
4790 //   Note that general register operands will be output using their 64-bit x
4791 // register name, whatever the size of the variable, unless the asm operand
4792 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4793 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4794 // %q modifier.
4795 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4796   // At this point, we have to lower this constraint to something else, so we
4797   // lower it to an "r" or "w". However, by doing this we will force the result
4798   // to be in register, while the X constraint is much more permissive.
4799   //
4800   // Although we are correct (we are free to emit anything, without
4801   // constraints), we might break use cases that would expect us to be more
4802   // efficient and emit something else.
4803   if (!Subtarget->hasFPARMv8())
4804     return "r";
4805
4806   if (ConstraintVT.isFloatingPoint())
4807     return "w";
4808
4809   if (ConstraintVT.isVector() &&
4810      (ConstraintVT.getSizeInBits() == 64 ||
4811       ConstraintVT.getSizeInBits() == 128))
4812     return "w";
4813
4814   return "r";
4815 }
4816
4817 /// getConstraintType - Given a constraint letter, return the type of
4818 /// constraint it is for this target.
4819 AArch64TargetLowering::ConstraintType
4820 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4821   if (Constraint.size() == 1) {
4822     switch (Constraint[0]) {
4823     default:
4824       break;
4825     case 'z':
4826       return C_Other;
4827     case 'x':
4828     case 'w':
4829       return C_RegisterClass;
4830     // An address with a single base register. Due to the way we
4831     // currently handle addresses it is the same as 'r'.
4832     case 'Q':
4833       return C_Memory;
4834     }
4835   }
4836   return TargetLowering::getConstraintType(Constraint);
4837 }
4838
4839 /// Examine constraint type and operand type and determine a weight value.
4840 /// This object must already have been set up with the operand type
4841 /// and the current alternative constraint selected.
4842 TargetLowering::ConstraintWeight
4843 AArch64TargetLowering::getSingleConstraintMatchWeight(
4844     AsmOperandInfo &info, const char *constraint) const {
4845   ConstraintWeight weight = CW_Invalid;
4846   Value *CallOperandVal = info.CallOperandVal;
4847   // If we don't have a value, we can't do a match,
4848   // but allow it at the lowest weight.
4849   if (!CallOperandVal)
4850     return CW_Default;
4851   Type *type = CallOperandVal->getType();
4852   // Look at the constraint type.
4853   switch (*constraint) {
4854   default:
4855     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4856     break;
4857   case 'x':
4858   case 'w':
4859     if (type->isFloatingPointTy() || type->isVectorTy())
4860       weight = CW_Register;
4861     break;
4862   case 'z':
4863     weight = CW_Constant;
4864     break;
4865   }
4866   return weight;
4867 }
4868
4869 std::pair<unsigned, const TargetRegisterClass *>
4870 AArch64TargetLowering::getRegForInlineAsmConstraint(
4871     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4872   if (Constraint.size() == 1) {
4873     switch (Constraint[0]) {
4874     case 'r':
4875       if (VT.getSizeInBits() == 64)
4876         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4877       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4878     case 'w':
4879       if (VT.getSizeInBits() == 16)
4880         return std::make_pair(0U, &AArch64::FPR16RegClass);
4881       if (VT.getSizeInBits() == 32)
4882         return std::make_pair(0U, &AArch64::FPR32RegClass);
4883       if (VT.getSizeInBits() == 64)
4884         return std::make_pair(0U, &AArch64::FPR64RegClass);
4885       if (VT.getSizeInBits() == 128)
4886         return std::make_pair(0U, &AArch64::FPR128RegClass);
4887       break;
4888     // The instructions that this constraint is designed for can
4889     // only take 128-bit registers so just use that regclass.
4890     case 'x':
4891       if (VT.getSizeInBits() == 128)
4892         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4893       break;
4894     }
4895   }
4896   if (StringRef("{cc}").equals_lower(Constraint))
4897     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4898
4899   // Use the default implementation in TargetLowering to convert the register
4900   // constraint into a member of a register class.
4901   std::pair<unsigned, const TargetRegisterClass *> Res;
4902   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4903
4904   // Not found as a standard register?
4905   if (!Res.second) {
4906     unsigned Size = Constraint.size();
4907     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4908         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4909       int RegNo;
4910       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4911       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4912         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4913         // By default we'll emit v0-v31 for this unless there's a modifier where
4914         // we'll emit the correct register as well.
4915         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4916           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4917           Res.second = &AArch64::FPR64RegClass;
4918         } else {
4919           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4920           Res.second = &AArch64::FPR128RegClass;
4921         }
4922       }
4923     }
4924   }
4925
4926   return Res;
4927 }
4928
4929 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4930 /// vector.  If it is invalid, don't add anything to Ops.
4931 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4932     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4933     SelectionDAG &DAG) const {
4934   SDValue Result;
4935
4936   // Currently only support length 1 constraints.
4937   if (Constraint.length() != 1)
4938     return;
4939
4940   char ConstraintLetter = Constraint[0];
4941   switch (ConstraintLetter) {
4942   default:
4943     break;
4944
4945   // This set of constraints deal with valid constants for various instructions.
4946   // Validate and return a target constant for them if we can.
4947   case 'z': {
4948     // 'z' maps to xzr or wzr so it needs an input of 0.
4949     if (!isNullConstant(Op))
4950       return;
4951
4952     if (Op.getValueType() == MVT::i64)
4953       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4954     else
4955       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4956     break;
4957   }
4958
4959   case 'I':
4960   case 'J':
4961   case 'K':
4962   case 'L':
4963   case 'M':
4964   case 'N':
4965     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4966     if (!C)
4967       return;
4968
4969     // Grab the value and do some validation.
4970     uint64_t CVal = C->getZExtValue();
4971     switch (ConstraintLetter) {
4972     // The I constraint applies only to simple ADD or SUB immediate operands:
4973     // i.e. 0 to 4095 with optional shift by 12
4974     // The J constraint applies only to ADD or SUB immediates that would be
4975     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4976     // instruction [or vice versa], in other words -1 to -4095 with optional
4977     // left shift by 12.
4978     case 'I':
4979       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4980         break;
4981       return;
4982     case 'J': {
4983       uint64_t NVal = -C->getSExtValue();
4984       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4985         CVal = C->getSExtValue();
4986         break;
4987       }
4988       return;
4989     }
4990     // The K and L constraints apply *only* to logical immediates, including
4991     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4992     // been removed and MOV should be used). So these constraints have to
4993     // distinguish between bit patterns that are valid 32-bit or 64-bit
4994     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4995     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4996     // versa.
4997     case 'K':
4998       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4999         break;
5000       return;
5001     case 'L':
5002       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5003         break;
5004       return;
5005     // The M and N constraints are a superset of K and L respectively, for use
5006     // with the MOV (immediate) alias. As well as the logical immediates they
5007     // also match 32 or 64-bit immediates that can be loaded either using a
5008     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5009     // (M) or 64-bit 0x1234000000000000 (N) etc.
5010     // As a note some of this code is liberally stolen from the asm parser.
5011     case 'M': {
5012       if (!isUInt<32>(CVal))
5013         return;
5014       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5015         break;
5016       if ((CVal & 0xFFFF) == CVal)
5017         break;
5018       if ((CVal & 0xFFFF0000ULL) == CVal)
5019         break;
5020       uint64_t NCVal = ~(uint32_t)CVal;
5021       if ((NCVal & 0xFFFFULL) == NCVal)
5022         break;
5023       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5024         break;
5025       return;
5026     }
5027     case 'N': {
5028       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5029         break;
5030       if ((CVal & 0xFFFFULL) == CVal)
5031         break;
5032       if ((CVal & 0xFFFF0000ULL) == CVal)
5033         break;
5034       if ((CVal & 0xFFFF00000000ULL) == CVal)
5035         break;
5036       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5037         break;
5038       uint64_t NCVal = ~CVal;
5039       if ((NCVal & 0xFFFFULL) == NCVal)
5040         break;
5041       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5042         break;
5043       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5044         break;
5045       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5046         break;
5047       return;
5048     }
5049     default:
5050       return;
5051     }
5052
5053     // All assembler immediates are 64-bit integers.
5054     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5055     break;
5056   }
5057
5058   if (Result.getNode()) {
5059     Ops.push_back(Result);
5060     return;
5061   }
5062
5063   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5064 }
5065
5066 //===----------------------------------------------------------------------===//
5067 //                     AArch64 Advanced SIMD Support
5068 //===----------------------------------------------------------------------===//
5069
5070 /// WidenVector - Given a value in the V64 register class, produce the
5071 /// equivalent value in the V128 register class.
5072 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5073   EVT VT = V64Reg.getValueType();
5074   unsigned NarrowSize = VT.getVectorNumElements();
5075   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5076   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5077   SDLoc DL(V64Reg);
5078
5079   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5080                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5081 }
5082
5083 /// getExtFactor - Determine the adjustment factor for the position when
5084 /// generating an "extract from vector registers" instruction.
5085 static unsigned getExtFactor(SDValue &V) {
5086   EVT EltType = V.getValueType().getVectorElementType();
5087   return EltType.getSizeInBits() / 8;
5088 }
5089
5090 /// NarrowVector - Given a value in the V128 register class, produce the
5091 /// equivalent value in the V64 register class.
5092 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5093   EVT VT = V128Reg.getValueType();
5094   unsigned WideSize = VT.getVectorNumElements();
5095   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5096   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5097   SDLoc DL(V128Reg);
5098
5099   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5100 }
5101
5102 // Gather data to see if the operation can be modelled as a
5103 // shuffle in combination with VEXTs.
5104 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5105                                                   SelectionDAG &DAG) const {
5106   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5107   SDLoc dl(Op);
5108   EVT VT = Op.getValueType();
5109   unsigned NumElts = VT.getVectorNumElements();
5110
5111   struct ShuffleSourceInfo {
5112     SDValue Vec;
5113     unsigned MinElt;
5114     unsigned MaxElt;
5115
5116     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5117     // be compatible with the shuffle we intend to construct. As a result
5118     // ShuffleVec will be some sliding window into the original Vec.
5119     SDValue ShuffleVec;
5120
5121     // Code should guarantee that element i in Vec starts at element "WindowBase
5122     // + i * WindowScale in ShuffleVec".
5123     int WindowBase;
5124     int WindowScale;
5125
5126     ShuffleSourceInfo(SDValue Vec)
5127       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5128           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5129
5130     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5131   };
5132
5133   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5134   // node.
5135   SmallVector<ShuffleSourceInfo, 2> Sources;
5136   for (unsigned i = 0; i < NumElts; ++i) {
5137     SDValue V = Op.getOperand(i);
5138     if (V.isUndef())
5139       continue;
5140     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5141              !isa<ConstantSDNode>(V.getOperand(1))) {
5142       // A shuffle can only come from building a vector from various
5143       // elements of other vectors, provided their indices are constant.
5144       return SDValue();
5145     }
5146
5147     // Add this element source to the list if it's not already there.
5148     SDValue SourceVec = V.getOperand(0);
5149     auto Source = find(Sources, SourceVec);
5150     if (Source == Sources.end())
5151       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5152
5153     // Update the minimum and maximum lane number seen.
5154     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5155     Source->MinElt = std::min(Source->MinElt, EltNo);
5156     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5157   }
5158
5159   // Currently only do something sane when at most two source vectors
5160   // are involved.
5161   if (Sources.size() > 2)
5162     return SDValue();
5163
5164   // Find out the smallest element size among result and two sources, and use
5165   // it as element size to build the shuffle_vector.
5166   EVT SmallestEltTy = VT.getVectorElementType();
5167   for (auto &Source : Sources) {
5168     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5169     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5170       SmallestEltTy = SrcEltTy;
5171     }
5172   }
5173   unsigned ResMultiplier =
5174       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5175   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5176   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5177
5178   // If the source vector is too wide or too narrow, we may nevertheless be able
5179   // to construct a compatible shuffle either by concatenating it with UNDEF or
5180   // extracting a suitable range of elements.
5181   for (auto &Src : Sources) {
5182     EVT SrcVT = Src.ShuffleVec.getValueType();
5183
5184     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5185       continue;
5186
5187     // This stage of the search produces a source with the same element type as
5188     // the original, but with a total width matching the BUILD_VECTOR output.
5189     EVT EltVT = SrcVT.getVectorElementType();
5190     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5191     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5192
5193     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5194       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5195       // We can pad out the smaller vector for free, so if it's part of a
5196       // shuffle...
5197       Src.ShuffleVec =
5198           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5199                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5200       continue;
5201     }
5202
5203     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5204
5205     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5206       // Span too large for a VEXT to cope
5207       return SDValue();
5208     }
5209
5210     if (Src.MinElt >= NumSrcElts) {
5211       // The extraction can just take the second half
5212       Src.ShuffleVec =
5213           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5214                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5215       Src.WindowBase = -NumSrcElts;
5216     } else if (Src.MaxElt < NumSrcElts) {
5217       // The extraction can just take the first half
5218       Src.ShuffleVec =
5219           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5220                       DAG.getConstant(0, dl, MVT::i64));
5221     } else {
5222       // An actual VEXT is needed
5223       SDValue VEXTSrc1 =
5224           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5225                       DAG.getConstant(0, dl, MVT::i64));
5226       SDValue VEXTSrc2 =
5227           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5228                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5229       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5230
5231       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5232                                    VEXTSrc2,
5233                                    DAG.getConstant(Imm, dl, MVT::i32));
5234       Src.WindowBase = -Src.MinElt;
5235     }
5236   }
5237
5238   // Another possible incompatibility occurs from the vector element types. We
5239   // can fix this by bitcasting the source vectors to the same type we intend
5240   // for the shuffle.
5241   for (auto &Src : Sources) {
5242     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5243     if (SrcEltTy == SmallestEltTy)
5244       continue;
5245     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5246     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5247     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5248     Src.WindowBase *= Src.WindowScale;
5249   }
5250
5251   // Final sanity check before we try to actually produce a shuffle.
5252   DEBUG(
5253     for (auto Src : Sources)
5254       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5255   );
5256
5257   // The stars all align, our next step is to produce the mask for the shuffle.
5258   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5259   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5260   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5261     SDValue Entry = Op.getOperand(i);
5262     if (Entry.isUndef())
5263       continue;
5264
5265     auto Src = find(Sources, Entry.getOperand(0));
5266     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5267
5268     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5269     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5270     // segment.
5271     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5272     int BitsDefined =
5273         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5274     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5275
5276     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5277     // starting at the appropriate offset.
5278     int *LaneMask = &Mask[i * ResMultiplier];
5279
5280     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5281     ExtractBase += NumElts * (Src - Sources.begin());
5282     for (int j = 0; j < LanesDefined; ++j)
5283       LaneMask[j] = ExtractBase + j;
5284   }
5285
5286   // Final check before we try to produce nonsense...
5287   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5288     return SDValue();
5289
5290   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5291   for (unsigned i = 0; i < Sources.size(); ++i)
5292     ShuffleOps[i] = Sources[i].ShuffleVec;
5293
5294   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5295                                          ShuffleOps[1], Mask);
5296   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5297 }
5298
5299 // check if an EXT instruction can handle the shuffle mask when the
5300 // vector sources of the shuffle are the same.
5301 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5302   unsigned NumElts = VT.getVectorNumElements();
5303
5304   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5305   if (M[0] < 0)
5306     return false;
5307
5308   Imm = M[0];
5309
5310   // If this is a VEXT shuffle, the immediate value is the index of the first
5311   // element.  The other shuffle indices must be the successive elements after
5312   // the first one.
5313   unsigned ExpectedElt = Imm;
5314   for (unsigned i = 1; i < NumElts; ++i) {
5315     // Increment the expected index.  If it wraps around, just follow it
5316     // back to index zero and keep going.
5317     ++ExpectedElt;
5318     if (ExpectedElt == NumElts)
5319       ExpectedElt = 0;
5320
5321     if (M[i] < 0)
5322       continue; // ignore UNDEF indices
5323     if (ExpectedElt != static_cast<unsigned>(M[i]))
5324       return false;
5325   }
5326
5327   return true;
5328 }
5329
5330 // check if an EXT instruction can handle the shuffle mask when the
5331 // vector sources of the shuffle are different.
5332 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5333                       unsigned &Imm) {
5334   // Look for the first non-undef element.
5335   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5336
5337   // Benefit form APInt to handle overflow when calculating expected element.
5338   unsigned NumElts = VT.getVectorNumElements();
5339   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5340   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5341   // The following shuffle indices must be the successive elements after the
5342   // first real element.
5343   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5344       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5345   if (FirstWrongElt != M.end())
5346     return false;
5347
5348   // The index of an EXT is the first element if it is not UNDEF.
5349   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5350   // value of the first element.  E.g.
5351   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5352   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5353   // ExpectedElt is the last mask index plus 1.
5354   Imm = ExpectedElt.getZExtValue();
5355
5356   // There are two difference cases requiring to reverse input vectors.
5357   // For example, for vector <4 x i32> we have the following cases,
5358   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5359   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5360   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5361   // to reverse two input vectors.
5362   if (Imm < NumElts)
5363     ReverseEXT = true;
5364   else
5365     Imm -= NumElts;
5366
5367   return true;
5368 }
5369
5370 /// isREVMask - Check if a vector shuffle corresponds to a REV
5371 /// instruction with the specified blocksize.  (The order of the elements
5372 /// within each block of the vector is reversed.)
5373 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5374   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5375          "Only possible block sizes for REV are: 16, 32, 64");
5376
5377   unsigned EltSz = VT.getScalarSizeInBits();
5378   if (EltSz == 64)
5379     return false;
5380
5381   unsigned NumElts = VT.getVectorNumElements();
5382   unsigned BlockElts = M[0] + 1;
5383   // If the first shuffle index is UNDEF, be optimistic.
5384   if (M[0] < 0)
5385     BlockElts = BlockSize / EltSz;
5386
5387   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5388     return false;
5389
5390   for (unsigned i = 0; i < NumElts; ++i) {
5391     if (M[i] < 0)
5392       continue; // ignore UNDEF indices
5393     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5394       return false;
5395   }
5396
5397   return true;
5398 }
5399
5400 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5401   unsigned NumElts = VT.getVectorNumElements();
5402   WhichResult = (M[0] == 0 ? 0 : 1);
5403   unsigned Idx = WhichResult * NumElts / 2;
5404   for (unsigned i = 0; i != NumElts; i += 2) {
5405     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5406         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5407       return false;
5408     Idx += 1;
5409   }
5410
5411   return true;
5412 }
5413
5414 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5415   unsigned NumElts = VT.getVectorNumElements();
5416   WhichResult = (M[0] == 0 ? 0 : 1);
5417   for (unsigned i = 0; i != NumElts; ++i) {
5418     if (M[i] < 0)
5419       continue; // ignore UNDEF indices
5420     if ((unsigned)M[i] != 2 * i + WhichResult)
5421       return false;
5422   }
5423
5424   return true;
5425 }
5426
5427 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5428   unsigned NumElts = VT.getVectorNumElements();
5429   WhichResult = (M[0] == 0 ? 0 : 1);
5430   for (unsigned i = 0; i < NumElts; i += 2) {
5431     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5432         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5433       return false;
5434   }
5435   return true;
5436 }
5437
5438 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5439 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5440 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5441 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5442   unsigned NumElts = VT.getVectorNumElements();
5443   WhichResult = (M[0] == 0 ? 0 : 1);
5444   unsigned Idx = WhichResult * NumElts / 2;
5445   for (unsigned i = 0; i != NumElts; i += 2) {
5446     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5447         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5448       return false;
5449     Idx += 1;
5450   }
5451
5452   return true;
5453 }
5454
5455 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5456 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5457 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5458 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5459   unsigned Half = VT.getVectorNumElements() / 2;
5460   WhichResult = (M[0] == 0 ? 0 : 1);
5461   for (unsigned j = 0; j != 2; ++j) {
5462     unsigned Idx = WhichResult;
5463     for (unsigned i = 0; i != Half; ++i) {
5464       int MIdx = M[i + j * Half];
5465       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5466         return false;
5467       Idx += 2;
5468     }
5469   }
5470
5471   return true;
5472 }
5473
5474 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5475 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5476 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5477 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5478   unsigned NumElts = VT.getVectorNumElements();
5479   WhichResult = (M[0] == 0 ? 0 : 1);
5480   for (unsigned i = 0; i < NumElts; i += 2) {
5481     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5482         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5483       return false;
5484   }
5485   return true;
5486 }
5487
5488 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5489                       bool &DstIsLeft, int &Anomaly) {
5490   if (M.size() != static_cast<size_t>(NumInputElements))
5491     return false;
5492
5493   int NumLHSMatch = 0, NumRHSMatch = 0;
5494   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5495
5496   for (int i = 0; i < NumInputElements; ++i) {
5497     if (M[i] == -1) {
5498       ++NumLHSMatch;
5499       ++NumRHSMatch;
5500       continue;
5501     }
5502
5503     if (M[i] == i)
5504       ++NumLHSMatch;
5505     else
5506       LastLHSMismatch = i;
5507
5508     if (M[i] == i + NumInputElements)
5509       ++NumRHSMatch;
5510     else
5511       LastRHSMismatch = i;
5512   }
5513
5514   if (NumLHSMatch == NumInputElements - 1) {
5515     DstIsLeft = true;
5516     Anomaly = LastLHSMismatch;
5517     return true;
5518   } else if (NumRHSMatch == NumInputElements - 1) {
5519     DstIsLeft = false;
5520     Anomaly = LastRHSMismatch;
5521     return true;
5522   }
5523
5524   return false;
5525 }
5526
5527 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5528   if (VT.getSizeInBits() != 128)
5529     return false;
5530
5531   unsigned NumElts = VT.getVectorNumElements();
5532
5533   for (int I = 0, E = NumElts / 2; I != E; I++) {
5534     if (Mask[I] != I)
5535       return false;
5536   }
5537
5538   int Offset = NumElts / 2;
5539   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5540     if (Mask[I] != I + SplitLHS * Offset)
5541       return false;
5542   }
5543
5544   return true;
5545 }
5546
5547 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5548   SDLoc DL(Op);
5549   EVT VT = Op.getValueType();
5550   SDValue V0 = Op.getOperand(0);
5551   SDValue V1 = Op.getOperand(1);
5552   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5553
5554   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5555       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5556     return SDValue();
5557
5558   bool SplitV0 = V0.getValueSizeInBits() == 128;
5559
5560   if (!isConcatMask(Mask, VT, SplitV0))
5561     return SDValue();
5562
5563   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5564                                 VT.getVectorNumElements() / 2);
5565   if (SplitV0) {
5566     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5567                      DAG.getConstant(0, DL, MVT::i64));
5568   }
5569   if (V1.getValueSizeInBits() == 128) {
5570     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5571                      DAG.getConstant(0, DL, MVT::i64));
5572   }
5573   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5574 }
5575
5576 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5577 /// the specified operations to build the shuffle.
5578 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5579                                       SDValue RHS, SelectionDAG &DAG,
5580                                       const SDLoc &dl) {
5581   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5582   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5583   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5584
5585   enum {
5586     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5587     OP_VREV,
5588     OP_VDUP0,
5589     OP_VDUP1,
5590     OP_VDUP2,
5591     OP_VDUP3,
5592     OP_VEXT1,
5593     OP_VEXT2,
5594     OP_VEXT3,
5595     OP_VUZPL, // VUZP, left result
5596     OP_VUZPR, // VUZP, right result
5597     OP_VZIPL, // VZIP, left result
5598     OP_VZIPR, // VZIP, right result
5599     OP_VTRNL, // VTRN, left result
5600     OP_VTRNR  // VTRN, right result
5601   };
5602
5603   if (OpNum == OP_COPY) {
5604     if (LHSID == (1 * 9 + 2) * 9 + 3)
5605       return LHS;
5606     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5607     return RHS;
5608   }
5609
5610   SDValue OpLHS, OpRHS;
5611   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5612   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5613   EVT VT = OpLHS.getValueType();
5614
5615   switch (OpNum) {
5616   default:
5617     llvm_unreachable("Unknown shuffle opcode!");
5618   case OP_VREV:
5619     // VREV divides the vector in half and swaps within the half.
5620     if (VT.getVectorElementType() == MVT::i32 ||
5621         VT.getVectorElementType() == MVT::f32)
5622       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5623     // vrev <4 x i16> -> REV32
5624     if (VT.getVectorElementType() == MVT::i16 ||
5625         VT.getVectorElementType() == MVT::f16)
5626       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5627     // vrev <4 x i8> -> REV16
5628     assert(VT.getVectorElementType() == MVT::i8);
5629     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5630   case OP_VDUP0:
5631   case OP_VDUP1:
5632   case OP_VDUP2:
5633   case OP_VDUP3: {
5634     EVT EltTy = VT.getVectorElementType();
5635     unsigned Opcode;
5636     if (EltTy == MVT::i8)
5637       Opcode = AArch64ISD::DUPLANE8;
5638     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5639       Opcode = AArch64ISD::DUPLANE16;
5640     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5641       Opcode = AArch64ISD::DUPLANE32;
5642     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5643       Opcode = AArch64ISD::DUPLANE64;
5644     else
5645       llvm_unreachable("Invalid vector element type?");
5646
5647     if (VT.getSizeInBits() == 64)
5648       OpLHS = WidenVector(OpLHS, DAG);
5649     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5650     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5651   }
5652   case OP_VEXT1:
5653   case OP_VEXT2:
5654   case OP_VEXT3: {
5655     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5656     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5657                        DAG.getConstant(Imm, dl, MVT::i32));
5658   }
5659   case OP_VUZPL:
5660     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5661                        OpRHS);
5662   case OP_VUZPR:
5663     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5664                        OpRHS);
5665   case OP_VZIPL:
5666     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5667                        OpRHS);
5668   case OP_VZIPR:
5669     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5670                        OpRHS);
5671   case OP_VTRNL:
5672     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5673                        OpRHS);
5674   case OP_VTRNR:
5675     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5676                        OpRHS);
5677   }
5678 }
5679
5680 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5681                            SelectionDAG &DAG) {
5682   // Check to see if we can use the TBL instruction.
5683   SDValue V1 = Op.getOperand(0);
5684   SDValue V2 = Op.getOperand(1);
5685   SDLoc DL(Op);
5686
5687   EVT EltVT = Op.getValueType().getVectorElementType();
5688   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5689
5690   SmallVector<SDValue, 8> TBLMask;
5691   for (int Val : ShuffleMask) {
5692     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5693       unsigned Offset = Byte + Val * BytesPerElt;
5694       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5695     }
5696   }
5697
5698   MVT IndexVT = MVT::v8i8;
5699   unsigned IndexLen = 8;
5700   if (Op.getValueSizeInBits() == 128) {
5701     IndexVT = MVT::v16i8;
5702     IndexLen = 16;
5703   }
5704
5705   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5706   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5707
5708   SDValue Shuffle;
5709   if (V2.getNode()->isUndef()) {
5710     if (IndexLen == 8)
5711       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5712     Shuffle = DAG.getNode(
5713         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5714         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5715         DAG.getBuildVector(IndexVT, DL,
5716                            makeArrayRef(TBLMask.data(), IndexLen)));
5717   } else {
5718     if (IndexLen == 8) {
5719       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5720       Shuffle = DAG.getNode(
5721           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5722           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5723           DAG.getBuildVector(IndexVT, DL,
5724                              makeArrayRef(TBLMask.data(), IndexLen)));
5725     } else {
5726       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5727       // cannot currently represent the register constraints on the input
5728       // table registers.
5729       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5730       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5731       //                   IndexLen));
5732       Shuffle = DAG.getNode(
5733           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5734           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5735           V2Cst, DAG.getBuildVector(IndexVT, DL,
5736                                     makeArrayRef(TBLMask.data(), IndexLen)));
5737     }
5738   }
5739   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5740 }
5741
5742 static unsigned getDUPLANEOp(EVT EltType) {
5743   if (EltType == MVT::i8)
5744     return AArch64ISD::DUPLANE8;
5745   if (EltType == MVT::i16 || EltType == MVT::f16)
5746     return AArch64ISD::DUPLANE16;
5747   if (EltType == MVT::i32 || EltType == MVT::f32)
5748     return AArch64ISD::DUPLANE32;
5749   if (EltType == MVT::i64 || EltType == MVT::f64)
5750     return AArch64ISD::DUPLANE64;
5751
5752   llvm_unreachable("Invalid vector element type?");
5753 }
5754
5755 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5756                                                    SelectionDAG &DAG) const {
5757   SDLoc dl(Op);
5758   EVT VT = Op.getValueType();
5759
5760   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5761
5762   // Convert shuffles that are directly supported on NEON to target-specific
5763   // DAG nodes, instead of keeping them as shuffles and matching them again
5764   // during code selection.  This is more efficient and avoids the possibility
5765   // of inconsistencies between legalization and selection.
5766   ArrayRef<int> ShuffleMask = SVN->getMask();
5767
5768   SDValue V1 = Op.getOperand(0);
5769   SDValue V2 = Op.getOperand(1);
5770
5771   if (SVN->isSplat()) {
5772     int Lane = SVN->getSplatIndex();
5773     // If this is undef splat, generate it via "just" vdup, if possible.
5774     if (Lane == -1)
5775       Lane = 0;
5776
5777     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5778       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5779                          V1.getOperand(0));
5780     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5781     // constant. If so, we can just reference the lane's definition directly.
5782     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5783         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5784       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5785
5786     // Otherwise, duplicate from the lane of the input vector.
5787     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5788
5789     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5790     // to make a vector of the same size as this SHUFFLE. We can ignore the
5791     // extract entirely, and canonicalise the concat using WidenVector.
5792     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5793       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5794       V1 = V1.getOperand(0);
5795     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5796       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5797       Lane -= Idx * VT.getVectorNumElements() / 2;
5798       V1 = WidenVector(V1.getOperand(Idx), DAG);
5799     } else if (VT.getSizeInBits() == 64)
5800       V1 = WidenVector(V1, DAG);
5801
5802     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5803   }
5804
5805   if (isREVMask(ShuffleMask, VT, 64))
5806     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5807   if (isREVMask(ShuffleMask, VT, 32))
5808     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5809   if (isREVMask(ShuffleMask, VT, 16))
5810     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5811
5812   bool ReverseEXT = false;
5813   unsigned Imm;
5814   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5815     if (ReverseEXT)
5816       std::swap(V1, V2);
5817     Imm *= getExtFactor(V1);
5818     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5819                        DAG.getConstant(Imm, dl, MVT::i32));
5820   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5821     Imm *= getExtFactor(V1);
5822     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5823                        DAG.getConstant(Imm, dl, MVT::i32));
5824   }
5825
5826   unsigned WhichResult;
5827   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5828     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5829     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5830   }
5831   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5832     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5833     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5834   }
5835   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5836     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5837     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5838   }
5839
5840   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5841     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5842     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5843   }
5844   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5845     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5846     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5847   }
5848   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5849     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5850     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5851   }
5852
5853   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5854     return Concat;
5855
5856   bool DstIsLeft;
5857   int Anomaly;
5858   int NumInputElements = V1.getValueType().getVectorNumElements();
5859   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5860     SDValue DstVec = DstIsLeft ? V1 : V2;
5861     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5862
5863     SDValue SrcVec = V1;
5864     int SrcLane = ShuffleMask[Anomaly];
5865     if (SrcLane >= NumInputElements) {
5866       SrcVec = V2;
5867       SrcLane -= VT.getVectorNumElements();
5868     }
5869     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5870
5871     EVT ScalarVT = VT.getVectorElementType();
5872
5873     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5874       ScalarVT = MVT::i32;
5875
5876     return DAG.getNode(
5877         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5878         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5879         DstLaneV);
5880   }
5881
5882   // If the shuffle is not directly supported and it has 4 elements, use
5883   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5884   unsigned NumElts = VT.getVectorNumElements();
5885   if (NumElts == 4) {
5886     unsigned PFIndexes[4];
5887     for (unsigned i = 0; i != 4; ++i) {
5888       if (ShuffleMask[i] < 0)
5889         PFIndexes[i] = 8;
5890       else
5891         PFIndexes[i] = ShuffleMask[i];
5892     }
5893
5894     // Compute the index in the perfect shuffle table.
5895     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5896                             PFIndexes[2] * 9 + PFIndexes[3];
5897     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5898     unsigned Cost = (PFEntry >> 30);
5899
5900     if (Cost <= 4)
5901       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5902   }
5903
5904   return GenerateTBL(Op, ShuffleMask, DAG);
5905 }
5906
5907 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5908                                APInt &UndefBits) {
5909   EVT VT = BVN->getValueType(0);
5910   APInt SplatBits, SplatUndef;
5911   unsigned SplatBitSize;
5912   bool HasAnyUndefs;
5913   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5914     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5915
5916     for (unsigned i = 0; i < NumSplats; ++i) {
5917       CnstBits <<= SplatBitSize;
5918       UndefBits <<= SplatBitSize;
5919       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5920       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5921     }
5922
5923     return true;
5924   }
5925
5926   return false;
5927 }
5928
5929 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5930                                               SelectionDAG &DAG) const {
5931   BuildVectorSDNode *BVN =
5932       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5933   SDValue LHS = Op.getOperand(0);
5934   SDLoc dl(Op);
5935   EVT VT = Op.getValueType();
5936
5937   if (!BVN)
5938     return Op;
5939
5940   APInt CnstBits(VT.getSizeInBits(), 0);
5941   APInt UndefBits(VT.getSizeInBits(), 0);
5942   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5943     // We only have BIC vector immediate instruction, which is and-not.
5944     CnstBits = ~CnstBits;
5945
5946     // We make use of a little bit of goto ickiness in order to avoid having to
5947     // duplicate the immediate matching logic for the undef toggled case.
5948     bool SecondTry = false;
5949   AttemptModImm:
5950
5951     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5952       CnstBits = CnstBits.zextOrTrunc(64);
5953       uint64_t CnstVal = CnstBits.getZExtValue();
5954
5955       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5956         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5957         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5958         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5959                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5960                                   DAG.getConstant(0, dl, MVT::i32));
5961         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5962       }
5963
5964       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5965         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5966         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5967         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5968                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5969                                   DAG.getConstant(8, dl, MVT::i32));
5970         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5971       }
5972
5973       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5974         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5975         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5976         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5977                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5978                                   DAG.getConstant(16, dl, MVT::i32));
5979         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5980       }
5981
5982       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5983         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5984         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5985         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5986                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5987                                   DAG.getConstant(24, dl, MVT::i32));
5988         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5989       }
5990
5991       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5992         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5993         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5994         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5995                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5996                                   DAG.getConstant(0, dl, MVT::i32));
5997         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5998       }
5999
6000       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6001         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6002         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6003         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6004                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6005                                   DAG.getConstant(8, dl, MVT::i32));
6006         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6007       }
6008     }
6009
6010     if (SecondTry)
6011       goto FailedModImm;
6012     SecondTry = true;
6013     CnstBits = ~UndefBits;
6014     goto AttemptModImm;
6015   }
6016
6017 // We can always fall back to a non-immediate AND.
6018 FailedModImm:
6019   return Op;
6020 }
6021
6022 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6023 // consists of only the same constant int value, returned in reference arg
6024 // ConstVal
6025 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6026                                      uint64_t &ConstVal) {
6027   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6028   if (!Bvec)
6029     return false;
6030   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6031   if (!FirstElt)
6032     return false;
6033   EVT VT = Bvec->getValueType(0);
6034   unsigned NumElts = VT.getVectorNumElements();
6035   for (unsigned i = 1; i < NumElts; ++i)
6036     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6037       return false;
6038   ConstVal = FirstElt->getZExtValue();
6039   return true;
6040 }
6041
6042 static unsigned getIntrinsicID(const SDNode *N) {
6043   unsigned Opcode = N->getOpcode();
6044   switch (Opcode) {
6045   default:
6046     return Intrinsic::not_intrinsic;
6047   case ISD::INTRINSIC_WO_CHAIN: {
6048     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6049     if (IID < Intrinsic::num_intrinsics)
6050       return IID;
6051     return Intrinsic::not_intrinsic;
6052   }
6053   }
6054 }
6055
6056 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6057 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6058 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6059 // Also, logical shift right -> sri, with the same structure.
6060 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6061   EVT VT = N->getValueType(0);
6062
6063   if (!VT.isVector())
6064     return SDValue();
6065
6066   SDLoc DL(N);
6067
6068   // Is the first op an AND?
6069   const SDValue And = N->getOperand(0);
6070   if (And.getOpcode() != ISD::AND)
6071     return SDValue();
6072
6073   // Is the second op an shl or lshr?
6074   SDValue Shift = N->getOperand(1);
6075   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6076   // or AArch64ISD::VLSHR vector, #shift
6077   unsigned ShiftOpc = Shift.getOpcode();
6078   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6079     return SDValue();
6080   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6081
6082   // Is the shift amount constant?
6083   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6084   if (!C2node)
6085     return SDValue();
6086
6087   // Is the and mask vector all constant?
6088   uint64_t C1;
6089   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6090     return SDValue();
6091
6092   // Is C1 == ~C2, taking into account how much one can shift elements of a
6093   // particular size?
6094   uint64_t C2 = C2node->getZExtValue();
6095   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6096   if (C2 > ElemSizeInBits)
6097     return SDValue();
6098   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6099   if ((C1 & ElemMask) != (~C2 & ElemMask))
6100     return SDValue();
6101
6102   SDValue X = And.getOperand(0);
6103   SDValue Y = Shift.getOperand(0);
6104
6105   unsigned Intrin =
6106       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6107   SDValue ResultSLI =
6108       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6109                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6110                   Shift.getOperand(1));
6111
6112   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6113   DEBUG(N->dump(&DAG));
6114   DEBUG(dbgs() << "into: \n");
6115   DEBUG(ResultSLI->dump(&DAG));
6116
6117   ++NumShiftInserts;
6118   return ResultSLI;
6119 }
6120
6121 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6122                                              SelectionDAG &DAG) const {
6123   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6124   if (EnableAArch64SlrGeneration) {
6125     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6126       return Res;
6127   }
6128
6129   BuildVectorSDNode *BVN =
6130       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6131   SDValue LHS = Op.getOperand(1);
6132   SDLoc dl(Op);
6133   EVT VT = Op.getValueType();
6134
6135   // OR commutes, so try swapping the operands.
6136   if (!BVN) {
6137     LHS = Op.getOperand(0);
6138     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6139   }
6140   if (!BVN)
6141     return Op;
6142
6143   APInt CnstBits(VT.getSizeInBits(), 0);
6144   APInt UndefBits(VT.getSizeInBits(), 0);
6145   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6146     // We make use of a little bit of goto ickiness in order to avoid having to
6147     // duplicate the immediate matching logic for the undef toggled case.
6148     bool SecondTry = false;
6149   AttemptModImm:
6150
6151     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6152       CnstBits = CnstBits.zextOrTrunc(64);
6153       uint64_t CnstVal = CnstBits.getZExtValue();
6154
6155       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6156         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6157         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6158         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6159                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6160                                   DAG.getConstant(0, dl, MVT::i32));
6161         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6162       }
6163
6164       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6165         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6166         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6167         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6168                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6169                                   DAG.getConstant(8, dl, MVT::i32));
6170         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6171       }
6172
6173       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6174         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6175         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6176         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6177                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6178                                   DAG.getConstant(16, dl, MVT::i32));
6179         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6180       }
6181
6182       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6183         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6184         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6185         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6186                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6187                                   DAG.getConstant(24, dl, MVT::i32));
6188         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6189       }
6190
6191       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6192         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6193         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6194         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6195                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6196                                   DAG.getConstant(0, dl, MVT::i32));
6197         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6198       }
6199
6200       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6201         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6202         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6203         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6204                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6205                                   DAG.getConstant(8, dl, MVT::i32));
6206         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6207       }
6208     }
6209
6210     if (SecondTry)
6211       goto FailedModImm;
6212     SecondTry = true;
6213     CnstBits = UndefBits;
6214     goto AttemptModImm;
6215   }
6216
6217 // We can always fall back to a non-immediate OR.
6218 FailedModImm:
6219   return Op;
6220 }
6221
6222 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6223 // be truncated to fit element width.
6224 static SDValue NormalizeBuildVector(SDValue Op,
6225                                     SelectionDAG &DAG) {
6226   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6227   SDLoc dl(Op);
6228   EVT VT = Op.getValueType();
6229   EVT EltTy= VT.getVectorElementType();
6230
6231   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6232     return Op;
6233
6234   SmallVector<SDValue, 16> Ops;
6235   for (SDValue Lane : Op->ops()) {
6236     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6237       APInt LowBits(EltTy.getSizeInBits(),
6238                     CstLane->getZExtValue());
6239       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6240     }
6241     Ops.push_back(Lane);
6242   }
6243   return DAG.getBuildVector(VT, dl, Ops);
6244 }
6245
6246 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6247                                                  SelectionDAG &DAG) const {
6248   SDLoc dl(Op);
6249   EVT VT = Op.getValueType();
6250   Op = NormalizeBuildVector(Op, DAG);
6251   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6252
6253   APInt CnstBits(VT.getSizeInBits(), 0);
6254   APInt UndefBits(VT.getSizeInBits(), 0);
6255   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6256     // We make use of a little bit of goto ickiness in order to avoid having to
6257     // duplicate the immediate matching logic for the undef toggled case.
6258     bool SecondTry = false;
6259   AttemptModImm:
6260
6261     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6262       CnstBits = CnstBits.zextOrTrunc(64);
6263       uint64_t CnstVal = CnstBits.getZExtValue();
6264
6265       // Certain magic vector constants (used to express things like NOT
6266       // and NEG) are passed through unmodified.  This allows codegen patterns
6267       // for these operations to match.  Special-purpose patterns will lower
6268       // these immediates to MOVIs if it proves necessary.
6269       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6270         return Op;
6271
6272       // The many faces of MOVI...
6273       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6274         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6275         if (VT.getSizeInBits() == 128) {
6276           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6277                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6278           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6279         }
6280
6281         // Support the V64 version via subregister insertion.
6282         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6283                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6284         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6285       }
6286
6287       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6288         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6289         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6290         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6291                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6292                                   DAG.getConstant(0, dl, MVT::i32));
6293         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6294       }
6295
6296       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6297         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6298         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6299         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6300                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6301                                   DAG.getConstant(8, dl, MVT::i32));
6302         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6303       }
6304
6305       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6306         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6307         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6308         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6309                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6310                                   DAG.getConstant(16, dl, MVT::i32));
6311         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6312       }
6313
6314       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6315         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6316         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6317         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6318                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6319                                   DAG.getConstant(24, dl, MVT::i32));
6320         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6321       }
6322
6323       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6324         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6325         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6326         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6327                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6328                                   DAG.getConstant(0, dl, MVT::i32));
6329         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6330       }
6331
6332       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6333         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6334         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6335         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6336                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6337                                   DAG.getConstant(8, dl, MVT::i32));
6338         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6339       }
6340
6341       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6342         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6343         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6344         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6345                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6346                                   DAG.getConstant(264, dl, MVT::i32));
6347         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6348       }
6349
6350       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6351         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6352         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6353         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6354                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6355                                   DAG.getConstant(272, dl, MVT::i32));
6356         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6357       }
6358
6359       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6360         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6361         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6362         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6363                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6364         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6365       }
6366
6367       // The few faces of FMOV...
6368       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6369         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6370         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6371         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6372                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6373         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6374       }
6375
6376       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6377           VT.getSizeInBits() == 128) {
6378         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6379         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6380                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6381         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6382       }
6383
6384       // The many faces of MVNI...
6385       CnstVal = ~CnstVal;
6386       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6387         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6388         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6389         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6390                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6391                                   DAG.getConstant(0, dl, MVT::i32));
6392         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6393       }
6394
6395       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6396         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6397         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6398         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6399                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6400                                   DAG.getConstant(8, dl, MVT::i32));
6401         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6402       }
6403
6404       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6405         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6406         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6407         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6408                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6409                                   DAG.getConstant(16, dl, MVT::i32));
6410         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6411       }
6412
6413       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6414         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6415         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6416         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6417                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6418                                   DAG.getConstant(24, dl, MVT::i32));
6419         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6420       }
6421
6422       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6423         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6424         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6425         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6426                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6427                                   DAG.getConstant(0, dl, MVT::i32));
6428         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6429       }
6430
6431       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6432         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6433         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6434         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6435                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6436                                   DAG.getConstant(8, dl, MVT::i32));
6437         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6438       }
6439
6440       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6441         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6442         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6443         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6444                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6445                                   DAG.getConstant(264, dl, MVT::i32));
6446         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6447       }
6448
6449       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6450         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6451         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6452         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6453                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6454                                   DAG.getConstant(272, dl, MVT::i32));
6455         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6456       }
6457     }
6458
6459     if (SecondTry)
6460       goto FailedModImm;
6461     SecondTry = true;
6462     CnstBits = UndefBits;
6463     goto AttemptModImm;
6464   }
6465 FailedModImm:
6466
6467   // Scan through the operands to find some interesting properties we can
6468   // exploit:
6469   //   1) If only one value is used, we can use a DUP, or
6470   //   2) if only the low element is not undef, we can just insert that, or
6471   //   3) if only one constant value is used (w/ some non-constant lanes),
6472   //      we can splat the constant value into the whole vector then fill
6473   //      in the non-constant lanes.
6474   //   4) FIXME: If different constant values are used, but we can intelligently
6475   //             select the values we'll be overwriting for the non-constant
6476   //             lanes such that we can directly materialize the vector
6477   //             some other way (MOVI, e.g.), we can be sneaky.
6478   unsigned NumElts = VT.getVectorNumElements();
6479   bool isOnlyLowElement = true;
6480   bool usesOnlyOneValue = true;
6481   bool usesOnlyOneConstantValue = true;
6482   bool isConstant = true;
6483   unsigned NumConstantLanes = 0;
6484   SDValue Value;
6485   SDValue ConstantValue;
6486   for (unsigned i = 0; i < NumElts; ++i) {
6487     SDValue V = Op.getOperand(i);
6488     if (V.isUndef())
6489       continue;
6490     if (i > 0)
6491       isOnlyLowElement = false;
6492     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6493       isConstant = false;
6494
6495     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6496       ++NumConstantLanes;
6497       if (!ConstantValue.getNode())
6498         ConstantValue = V;
6499       else if (ConstantValue != V)
6500         usesOnlyOneConstantValue = false;
6501     }
6502
6503     if (!Value.getNode())
6504       Value = V;
6505     else if (V != Value)
6506       usesOnlyOneValue = false;
6507   }
6508
6509   if (!Value.getNode())
6510     return DAG.getUNDEF(VT);
6511
6512   if (isOnlyLowElement)
6513     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6514
6515   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6516   // i32 and try again.
6517   if (usesOnlyOneValue) {
6518     if (!isConstant) {
6519       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6520           Value.getValueType() != VT)
6521         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6522
6523       // This is actually a DUPLANExx operation, which keeps everything vectory.
6524
6525       // DUPLANE works on 128-bit vectors, widen it if necessary.
6526       SDValue Lane = Value.getOperand(1);
6527       Value = Value.getOperand(0);
6528       if (Value.getValueSizeInBits() == 64)
6529         Value = WidenVector(Value, DAG);
6530
6531       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6532       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6533     }
6534
6535     if (VT.getVectorElementType().isFloatingPoint()) {
6536       SmallVector<SDValue, 8> Ops;
6537       EVT EltTy = VT.getVectorElementType();
6538       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6539               "Unsupported floating-point vector type");
6540       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6541       for (unsigned i = 0; i < NumElts; ++i)
6542         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6543       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6544       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6545       Val = LowerBUILD_VECTOR(Val, DAG);
6546       if (Val.getNode())
6547         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6548     }
6549   }
6550
6551   // If there was only one constant value used and for more than one lane,
6552   // start by splatting that value, then replace the non-constant lanes. This
6553   // is better than the default, which will perform a separate initialization
6554   // for each lane.
6555   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6556     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6557     // Now insert the non-constant lanes.
6558     for (unsigned i = 0; i < NumElts; ++i) {
6559       SDValue V = Op.getOperand(i);
6560       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6561       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6562         // Note that type legalization likely mucked about with the VT of the
6563         // source operand, so we may have to convert it here before inserting.
6564         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6565       }
6566     }
6567     return Val;
6568   }
6569
6570   // If all elements are constants and the case above didn't get hit, fall back
6571   // to the default expansion, which will generate a load from the constant
6572   // pool.
6573   if (isConstant)
6574     return SDValue();
6575
6576   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6577   if (NumElts >= 4) {
6578     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6579       return shuffle;
6580   }
6581
6582   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6583   // know the default expansion would otherwise fall back on something even
6584   // worse. For a vector with one or two non-undef values, that's
6585   // scalar_to_vector for the elements followed by a shuffle (provided the
6586   // shuffle is valid for the target) and materialization element by element
6587   // on the stack followed by a load for everything else.
6588   if (!isConstant && !usesOnlyOneValue) {
6589     SDValue Vec = DAG.getUNDEF(VT);
6590     SDValue Op0 = Op.getOperand(0);
6591     unsigned ElemSize = VT.getScalarSizeInBits();
6592     unsigned i = 0;
6593     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6594     // a) Avoid a RMW dependency on the full vector register, and
6595     // b) Allow the register coalescer to fold away the copy if the
6596     //    value is already in an S or D register.
6597     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6598     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6599     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6600         (ElemSize == 32 || ElemSize == 64)) {
6601       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6602       MachineSDNode *N =
6603           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6604                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6605       Vec = SDValue(N, 0);
6606       ++i;
6607     }
6608     for (; i < NumElts; ++i) {
6609       SDValue V = Op.getOperand(i);
6610       if (V.isUndef())
6611         continue;
6612       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6613       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6614     }
6615     return Vec;
6616   }
6617
6618   // Just use the default expansion. We failed to find a better alternative.
6619   return SDValue();
6620 }
6621
6622 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6623                                                       SelectionDAG &DAG) const {
6624   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6625
6626   // Check for non-constant or out of range lane.
6627   EVT VT = Op.getOperand(0).getValueType();
6628   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6629   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6630     return SDValue();
6631
6632
6633   // Insertion/extraction are legal for V128 types.
6634   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6635       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6636       VT == MVT::v8f16)
6637     return Op;
6638
6639   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6640       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6641     return SDValue();
6642
6643   // For V64 types, we perform insertion by expanding the value
6644   // to a V128 type and perform the insertion on that.
6645   SDLoc DL(Op);
6646   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6647   EVT WideTy = WideVec.getValueType();
6648
6649   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6650                              Op.getOperand(1), Op.getOperand(2));
6651   // Re-narrow the resultant vector.
6652   return NarrowVector(Node, DAG);
6653 }
6654
6655 SDValue
6656 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6657                                                SelectionDAG &DAG) const {
6658   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6659
6660   // Check for non-constant or out of range lane.
6661   EVT VT = Op.getOperand(0).getValueType();
6662   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6663   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6664     return SDValue();
6665
6666
6667   // Insertion/extraction are legal for V128 types.
6668   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6669       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6670       VT == MVT::v8f16)
6671     return Op;
6672
6673   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6674       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6675     return SDValue();
6676
6677   // For V64 types, we perform extraction by expanding the value
6678   // to a V128 type and perform the extraction on that.
6679   SDLoc DL(Op);
6680   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6681   EVT WideTy = WideVec.getValueType();
6682
6683   EVT ExtrTy = WideTy.getVectorElementType();
6684   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6685     ExtrTy = MVT::i32;
6686
6687   // For extractions, we just return the result directly.
6688   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6689                      Op.getOperand(1));
6690 }
6691
6692 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6693                                                       SelectionDAG &DAG) const {
6694   EVT VT = Op.getOperand(0).getValueType();
6695   SDLoc dl(Op);
6696   // Just in case...
6697   if (!VT.isVector())
6698     return SDValue();
6699
6700   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6701   if (!Cst)
6702     return SDValue();
6703   unsigned Val = Cst->getZExtValue();
6704
6705   unsigned Size = Op.getValueSizeInBits();
6706
6707   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6708   if (Val == 0)
6709     return Op;
6710
6711   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6712   // that directly.
6713   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6714     return Op;
6715
6716   return SDValue();
6717 }
6718
6719 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6720                                                EVT VT) const {
6721   if (VT.getVectorNumElements() == 4 &&
6722       (VT.is128BitVector() || VT.is64BitVector())) {
6723     unsigned PFIndexes[4];
6724     for (unsigned i = 0; i != 4; ++i) {
6725       if (M[i] < 0)
6726         PFIndexes[i] = 8;
6727       else
6728         PFIndexes[i] = M[i];
6729     }
6730
6731     // Compute the index in the perfect shuffle table.
6732     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6733                             PFIndexes[2] * 9 + PFIndexes[3];
6734     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6735     unsigned Cost = (PFEntry >> 30);
6736
6737     if (Cost <= 4)
6738       return true;
6739   }
6740
6741   bool DummyBool;
6742   int DummyInt;
6743   unsigned DummyUnsigned;
6744
6745   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6746           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6747           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6748           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6749           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6750           isZIPMask(M, VT, DummyUnsigned) ||
6751           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6752           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6753           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6754           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6755           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6756 }
6757
6758 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6759 /// operand of a vector shift operation, where all the elements of the
6760 /// build_vector must have the same constant integer value.
6761 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6762   // Ignore bit_converts.
6763   while (Op.getOpcode() == ISD::BITCAST)
6764     Op = Op.getOperand(0);
6765   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6766   APInt SplatBits, SplatUndef;
6767   unsigned SplatBitSize;
6768   bool HasAnyUndefs;
6769   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6770                                     HasAnyUndefs, ElementBits) ||
6771       SplatBitSize > ElementBits)
6772     return false;
6773   Cnt = SplatBits.getSExtValue();
6774   return true;
6775 }
6776
6777 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6778 /// operand of a vector shift left operation.  That value must be in the range:
6779 ///   0 <= Value < ElementBits for a left shift; or
6780 ///   0 <= Value <= ElementBits for a long left shift.
6781 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6782   assert(VT.isVector() && "vector shift count is not a vector type");
6783   int64_t ElementBits = VT.getScalarSizeInBits();
6784   if (!getVShiftImm(Op, ElementBits, Cnt))
6785     return false;
6786   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6787 }
6788
6789 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6790 /// operand of a vector shift right operation. The value must be in the range:
6791 ///   1 <= Value <= ElementBits for a right shift; or
6792 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6793   assert(VT.isVector() && "vector shift count is not a vector type");
6794   int64_t ElementBits = VT.getScalarSizeInBits();
6795   if (!getVShiftImm(Op, ElementBits, Cnt))
6796     return false;
6797   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6798 }
6799
6800 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6801                                                       SelectionDAG &DAG) const {
6802   EVT VT = Op.getValueType();
6803   SDLoc DL(Op);
6804   int64_t Cnt;
6805
6806   if (!Op.getOperand(1).getValueType().isVector())
6807     return Op;
6808   unsigned EltSize = VT.getScalarSizeInBits();
6809
6810   switch (Op.getOpcode()) {
6811   default:
6812     llvm_unreachable("unexpected shift opcode");
6813
6814   case ISD::SHL:
6815     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6816       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6817                          DAG.getConstant(Cnt, DL, MVT::i32));
6818     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6819                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6820                                        MVT::i32),
6821                        Op.getOperand(0), Op.getOperand(1));
6822   case ISD::SRA:
6823   case ISD::SRL:
6824     // Right shift immediate
6825     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6826       unsigned Opc =
6827           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6828       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6829                          DAG.getConstant(Cnt, DL, MVT::i32));
6830     }
6831
6832     // Right shift register.  Note, there is not a shift right register
6833     // instruction, but the shift left register instruction takes a signed
6834     // value, where negative numbers specify a right shift.
6835     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6836                                                 : Intrinsic::aarch64_neon_ushl;
6837     // negate the shift amount
6838     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6839     SDValue NegShiftLeft =
6840         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6841                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6842                     NegShift);
6843     return NegShiftLeft;
6844   }
6845
6846   return SDValue();
6847 }
6848
6849 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6850                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6851                                     const SDLoc &dl, SelectionDAG &DAG) {
6852   EVT SrcVT = LHS.getValueType();
6853   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6854          "function only supposed to emit natural comparisons");
6855
6856   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6857   APInt CnstBits(VT.getSizeInBits(), 0);
6858   APInt UndefBits(VT.getSizeInBits(), 0);
6859   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6860   bool IsZero = IsCnst && (CnstBits == 0);
6861
6862   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6863     switch (CC) {
6864     default:
6865       return SDValue();
6866     case AArch64CC::NE: {
6867       SDValue Fcmeq;
6868       if (IsZero)
6869         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6870       else
6871         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6872       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6873     }
6874     case AArch64CC::EQ:
6875       if (IsZero)
6876         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6877       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6878     case AArch64CC::GE:
6879       if (IsZero)
6880         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6881       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6882     case AArch64CC::GT:
6883       if (IsZero)
6884         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6885       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6886     case AArch64CC::LS:
6887       if (IsZero)
6888         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6889       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6890     case AArch64CC::LT:
6891       if (!NoNans)
6892         return SDValue();
6893       // If we ignore NaNs then we can use to the MI implementation.
6894       LLVM_FALLTHROUGH;
6895     case AArch64CC::MI:
6896       if (IsZero)
6897         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6898       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6899     }
6900   }
6901
6902   switch (CC) {
6903   default:
6904     return SDValue();
6905   case AArch64CC::NE: {
6906     SDValue Cmeq;
6907     if (IsZero)
6908       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6909     else
6910       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6911     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6912   }
6913   case AArch64CC::EQ:
6914     if (IsZero)
6915       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6916     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6917   case AArch64CC::GE:
6918     if (IsZero)
6919       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6920     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6921   case AArch64CC::GT:
6922     if (IsZero)
6923       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6924     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6925   case AArch64CC::LE:
6926     if (IsZero)
6927       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6928     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6929   case AArch64CC::LS:
6930     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6931   case AArch64CC::LO:
6932     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6933   case AArch64CC::LT:
6934     if (IsZero)
6935       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6936     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6937   case AArch64CC::HI:
6938     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6939   case AArch64CC::HS:
6940     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6941   }
6942 }
6943
6944 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6945                                            SelectionDAG &DAG) const {
6946   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6947   SDValue LHS = Op.getOperand(0);
6948   SDValue RHS = Op.getOperand(1);
6949   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6950   SDLoc dl(Op);
6951
6952   if (LHS.getValueType().getVectorElementType().isInteger()) {
6953     assert(LHS.getValueType() == RHS.getValueType());
6954     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6955     SDValue Cmp =
6956         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6957     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6958   }
6959
6960   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6961     return SDValue();
6962
6963   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6964          LHS.getValueType().getVectorElementType() == MVT::f64);
6965
6966   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6967   // clean.  Some of them require two branches to implement.
6968   AArch64CC::CondCode CC1, CC2;
6969   bool ShouldInvert;
6970   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6971
6972   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6973   SDValue Cmp =
6974       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6975   if (!Cmp.getNode())
6976     return SDValue();
6977
6978   if (CC2 != AArch64CC::AL) {
6979     SDValue Cmp2 =
6980         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6981     if (!Cmp2.getNode())
6982       return SDValue();
6983
6984     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6985   }
6986
6987   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6988
6989   if (ShouldInvert)
6990     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6991
6992   return Cmp;
6993 }
6994
6995 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6996 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6997 /// specified in the intrinsic calls.
6998 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6999                                                const CallInst &I,
7000                                                unsigned Intrinsic) const {
7001   auto &DL = I.getModule()->getDataLayout();
7002   switch (Intrinsic) {
7003   case Intrinsic::aarch64_neon_ld2:
7004   case Intrinsic::aarch64_neon_ld3:
7005   case Intrinsic::aarch64_neon_ld4:
7006   case Intrinsic::aarch64_neon_ld1x2:
7007   case Intrinsic::aarch64_neon_ld1x3:
7008   case Intrinsic::aarch64_neon_ld1x4:
7009   case Intrinsic::aarch64_neon_ld2lane:
7010   case Intrinsic::aarch64_neon_ld3lane:
7011   case Intrinsic::aarch64_neon_ld4lane:
7012   case Intrinsic::aarch64_neon_ld2r:
7013   case Intrinsic::aarch64_neon_ld3r:
7014   case Intrinsic::aarch64_neon_ld4r: {
7015     Info.opc = ISD::INTRINSIC_W_CHAIN;
7016     // Conservatively set memVT to the entire set of vectors loaded.
7017     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7018     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7019     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7020     Info.offset = 0;
7021     Info.align = 0;
7022     Info.vol = false; // volatile loads with NEON intrinsics not supported
7023     Info.readMem = true;
7024     Info.writeMem = false;
7025     return true;
7026   }
7027   case Intrinsic::aarch64_neon_st2:
7028   case Intrinsic::aarch64_neon_st3:
7029   case Intrinsic::aarch64_neon_st4:
7030   case Intrinsic::aarch64_neon_st1x2:
7031   case Intrinsic::aarch64_neon_st1x3:
7032   case Intrinsic::aarch64_neon_st1x4:
7033   case Intrinsic::aarch64_neon_st2lane:
7034   case Intrinsic::aarch64_neon_st3lane:
7035   case Intrinsic::aarch64_neon_st4lane: {
7036     Info.opc = ISD::INTRINSIC_VOID;
7037     // Conservatively set memVT to the entire set of vectors stored.
7038     unsigned NumElts = 0;
7039     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7040       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7041       if (!ArgTy->isVectorTy())
7042         break;
7043       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7044     }
7045     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7046     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7047     Info.offset = 0;
7048     Info.align = 0;
7049     Info.vol = false; // volatile stores with NEON intrinsics not supported
7050     Info.readMem = false;
7051     Info.writeMem = true;
7052     return true;
7053   }
7054   case Intrinsic::aarch64_ldaxr:
7055   case Intrinsic::aarch64_ldxr: {
7056     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7057     Info.opc = ISD::INTRINSIC_W_CHAIN;
7058     Info.memVT = MVT::getVT(PtrTy->getElementType());
7059     Info.ptrVal = I.getArgOperand(0);
7060     Info.offset = 0;
7061     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7062     Info.vol = true;
7063     Info.readMem = true;
7064     Info.writeMem = false;
7065     return true;
7066   }
7067   case Intrinsic::aarch64_stlxr:
7068   case Intrinsic::aarch64_stxr: {
7069     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7070     Info.opc = ISD::INTRINSIC_W_CHAIN;
7071     Info.memVT = MVT::getVT(PtrTy->getElementType());
7072     Info.ptrVal = I.getArgOperand(1);
7073     Info.offset = 0;
7074     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7075     Info.vol = true;
7076     Info.readMem = false;
7077     Info.writeMem = true;
7078     return true;
7079   }
7080   case Intrinsic::aarch64_ldaxp:
7081   case Intrinsic::aarch64_ldxp:
7082     Info.opc = ISD::INTRINSIC_W_CHAIN;
7083     Info.memVT = MVT::i128;
7084     Info.ptrVal = I.getArgOperand(0);
7085     Info.offset = 0;
7086     Info.align = 16;
7087     Info.vol = true;
7088     Info.readMem = true;
7089     Info.writeMem = false;
7090     return true;
7091   case Intrinsic::aarch64_stlxp:
7092   case Intrinsic::aarch64_stxp:
7093     Info.opc = ISD::INTRINSIC_W_CHAIN;
7094     Info.memVT = MVT::i128;
7095     Info.ptrVal = I.getArgOperand(2);
7096     Info.offset = 0;
7097     Info.align = 16;
7098     Info.vol = true;
7099     Info.readMem = false;
7100     Info.writeMem = true;
7101     return true;
7102   default:
7103     break;
7104   }
7105
7106   return false;
7107 }
7108
7109 // Truncations from 64-bit GPR to 32-bit GPR is free.
7110 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7111   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7112     return false;
7113   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7114   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7115   return NumBits1 > NumBits2;
7116 }
7117 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7118   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7119     return false;
7120   unsigned NumBits1 = VT1.getSizeInBits();
7121   unsigned NumBits2 = VT2.getSizeInBits();
7122   return NumBits1 > NumBits2;
7123 }
7124
7125 /// Check if it is profitable to hoist instruction in then/else to if.
7126 /// Not profitable if I and it's user can form a FMA instruction
7127 /// because we prefer FMSUB/FMADD.
7128 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7129   if (I->getOpcode() != Instruction::FMul)
7130     return true;
7131
7132   if (I->getNumUses() != 1)
7133     return true;
7134
7135   Instruction *User = I->user_back();
7136
7137   if (User &&
7138       !(User->getOpcode() == Instruction::FSub ||
7139         User->getOpcode() == Instruction::FAdd))
7140     return true;
7141
7142   const TargetOptions &Options = getTargetMachine().Options;
7143   const DataLayout &DL = I->getModule()->getDataLayout();
7144   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7145
7146   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7147            isOperationLegalOrCustom(ISD::FMA, VT) &&
7148            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7149             Options.UnsafeFPMath));
7150 }
7151
7152 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7153 // 64-bit GPR.
7154 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7155   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7156     return false;
7157   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7158   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7159   return NumBits1 == 32 && NumBits2 == 64;
7160 }
7161 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7162   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7163     return false;
7164   unsigned NumBits1 = VT1.getSizeInBits();
7165   unsigned NumBits2 = VT2.getSizeInBits();
7166   return NumBits1 == 32 && NumBits2 == 64;
7167 }
7168
7169 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7170   EVT VT1 = Val.getValueType();
7171   if (isZExtFree(VT1, VT2)) {
7172     return true;
7173   }
7174
7175   if (Val.getOpcode() != ISD::LOAD)
7176     return false;
7177
7178   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7179   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7180           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7181           VT1.getSizeInBits() <= 32);
7182 }
7183
7184 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7185   if (isa<FPExtInst>(Ext))
7186     return false;
7187
7188   // Vector types are next free.
7189   if (Ext->getType()->isVectorTy())
7190     return false;
7191
7192   for (const Use &U : Ext->uses()) {
7193     // The extension is free if we can fold it with a left shift in an
7194     // addressing mode or an arithmetic operation: add, sub, and cmp.
7195
7196     // Is there a shift?
7197     const Instruction *Instr = cast<Instruction>(U.getUser());
7198
7199     // Is this a constant shift?
7200     switch (Instr->getOpcode()) {
7201     case Instruction::Shl:
7202       if (!isa<ConstantInt>(Instr->getOperand(1)))
7203         return false;
7204       break;
7205     case Instruction::GetElementPtr: {
7206       gep_type_iterator GTI = gep_type_begin(Instr);
7207       auto &DL = Ext->getModule()->getDataLayout();
7208       std::advance(GTI, U.getOperandNo()-1);
7209       Type *IdxTy = GTI.getIndexedType();
7210       // This extension will end up with a shift because of the scaling factor.
7211       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7212       // Get the shift amount based on the scaling factor:
7213       // log2(sizeof(IdxTy)) - log2(8).
7214       uint64_t ShiftAmt =
7215           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7216       // Is the constant foldable in the shift of the addressing mode?
7217       // I.e., shift amount is between 1 and 4 inclusive.
7218       if (ShiftAmt == 0 || ShiftAmt > 4)
7219         return false;
7220       break;
7221     }
7222     case Instruction::Trunc:
7223       // Check if this is a noop.
7224       // trunc(sext ty1 to ty2) to ty1.
7225       if (Instr->getType() == Ext->getOperand(0)->getType())
7226         continue;
7227       LLVM_FALLTHROUGH;
7228     default:
7229       return false;
7230     }
7231
7232     // At this point we can use the bfm family, so this extension is free
7233     // for that use.
7234   }
7235   return true;
7236 }
7237
7238 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7239                                           unsigned &RequiredAligment) const {
7240   if (!LoadedType.isSimple() ||
7241       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7242     return false;
7243   // Cyclone supports unaligned accesses.
7244   RequiredAligment = 0;
7245   unsigned NumBits = LoadedType.getSizeInBits();
7246   return NumBits == 32 || NumBits == 64;
7247 }
7248
7249 /// \brief Lower an interleaved load into a ldN intrinsic.
7250 ///
7251 /// E.g. Lower an interleaved load (Factor = 2):
7252 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7253 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7254 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7255 ///
7256 ///      Into:
7257 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7258 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7259 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7260 bool AArch64TargetLowering::lowerInterleavedLoad(
7261     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7262     ArrayRef<unsigned> Indices, unsigned Factor) const {
7263   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7264          "Invalid interleave factor");
7265   assert(!Shuffles.empty() && "Empty shufflevector input");
7266   assert(Shuffles.size() == Indices.size() &&
7267          "Unmatched number of shufflevectors and indices");
7268
7269   const DataLayout &DL = LI->getModule()->getDataLayout();
7270
7271   VectorType *VecTy = Shuffles[0]->getType();
7272   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7273
7274   // Skip if we do not have NEON and skip illegal vector types.
7275   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7276     return false;
7277
7278   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7279   // load integer vectors first and then convert to pointer vectors.
7280   Type *EltTy = VecTy->getVectorElementType();
7281   if (EltTy->isPointerTy())
7282     VecTy =
7283         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7284
7285   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7286   Type *Tys[2] = {VecTy, PtrTy};
7287   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7288                                             Intrinsic::aarch64_neon_ld3,
7289                                             Intrinsic::aarch64_neon_ld4};
7290   Function *LdNFunc =
7291       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7292
7293   IRBuilder<> Builder(LI);
7294   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7295
7296   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7297
7298   // Replace uses of each shufflevector with the corresponding vector loaded
7299   // by ldN.
7300   for (unsigned i = 0; i < Shuffles.size(); i++) {
7301     ShuffleVectorInst *SVI = Shuffles[i];
7302     unsigned Index = Indices[i];
7303
7304     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7305
7306     // Convert the integer vector to pointer vector if the element is pointer.
7307     if (EltTy->isPointerTy())
7308       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7309
7310     SVI->replaceAllUsesWith(SubVec);
7311   }
7312
7313   return true;
7314 }
7315
7316 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7317 ///
7318 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7319 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7320                                    unsigned NumElts) {
7321   SmallVector<Constant *, 16> Mask;
7322   for (unsigned i = 0; i < NumElts; i++)
7323     Mask.push_back(Builder.getInt32(Start + i));
7324
7325   return ConstantVector::get(Mask);
7326 }
7327
7328 /// \brief Lower an interleaved store into a stN intrinsic.
7329 ///
7330 /// E.g. Lower an interleaved store (Factor = 3):
7331 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7332 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7333 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7334 ///
7335 ///      Into:
7336 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7337 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7338 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7339 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7340 ///
7341 /// Note that the new shufflevectors will be removed and we'll only generate one
7342 /// st3 instruction in CodeGen.
7343 ///
7344 /// Example for a more general valid mask (Factor 3). Lower:
7345 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7346 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7347 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7348 ///
7349 ///      Into:
7350 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7351 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7352 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7353 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7354 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7355                                                   ShuffleVectorInst *SVI,
7356                                                   unsigned Factor) const {
7357   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7358          "Invalid interleave factor");
7359
7360   VectorType *VecTy = SVI->getType();
7361   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7362          "Invalid interleaved store");
7363
7364   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7365   Type *EltTy = VecTy->getVectorElementType();
7366   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7367
7368   const DataLayout &DL = SI->getModule()->getDataLayout();
7369   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7370
7371   // Skip if we do not have NEON and skip illegal vector types.
7372   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7373     return false;
7374
7375   Value *Op0 = SVI->getOperand(0);
7376   Value *Op1 = SVI->getOperand(1);
7377   IRBuilder<> Builder(SI);
7378
7379   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7380   // vectors to integer vectors.
7381   if (EltTy->isPointerTy()) {
7382     Type *IntTy = DL.getIntPtrType(EltTy);
7383     unsigned NumOpElts =
7384         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7385
7386     // Convert to the corresponding integer vector.
7387     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7388     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7389     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7390
7391     SubVecTy = VectorType::get(IntTy, LaneLen);
7392   }
7393
7394   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7395   Type *Tys[2] = {SubVecTy, PtrTy};
7396   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7397                                              Intrinsic::aarch64_neon_st3,
7398                                              Intrinsic::aarch64_neon_st4};
7399   Function *StNFunc =
7400       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7401
7402   SmallVector<Value *, 5> Ops;
7403
7404   // Split the shufflevector operands into sub vectors for the new stN call.
7405   auto Mask = SVI->getShuffleMask();
7406   for (unsigned i = 0; i < Factor; i++) {
7407     if (Mask[i] >= 0) {
7408       Ops.push_back(Builder.CreateShuffleVector(
7409         Op0, Op1, getSequentialMask(Builder, Mask[i], LaneLen)));
7410     } else {
7411       unsigned StartMask = 0;
7412       for (unsigned j = 1; j < LaneLen; j++) {
7413         if (Mask[j*Factor + i] >= 0) {
7414           StartMask = Mask[j*Factor + i] - j;
7415           break;
7416         }
7417       }
7418       // Note: If all elements in a chunk are undefs, StartMask=0!
7419       // Note: Filling undef gaps with random elements is ok, since
7420       // those elements were being written anyway (with undefs).
7421       // In the case of all undefs we're defaulting to using elems from 0
7422       // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7423       Ops.push_back(Builder.CreateShuffleVector(
7424         Op0, Op1, getSequentialMask(Builder, StartMask, LaneLen)));
7425     }
7426   }
7427
7428   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7429   Builder.CreateCall(StNFunc, Ops);
7430   return true;
7431 }
7432
7433 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7434                        unsigned AlignCheck) {
7435   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7436           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7437 }
7438
7439 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7440                                                unsigned SrcAlign, bool IsMemset,
7441                                                bool ZeroMemset,
7442                                                bool MemcpyStrSrc,
7443                                                MachineFunction &MF) const {
7444   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7445   // instruction to materialize the v2i64 zero and one store (with restrictive
7446   // addressing mode). Just do two i64 store of zero-registers.
7447   bool Fast;
7448   const Function *F = MF.getFunction();
7449   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7450       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7451       (memOpAlign(SrcAlign, DstAlign, 16) ||
7452        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7453     return MVT::f128;
7454
7455   if (Size >= 8 &&
7456       (memOpAlign(SrcAlign, DstAlign, 8) ||
7457        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7458     return MVT::i64;
7459
7460   if (Size >= 4 &&
7461       (memOpAlign(SrcAlign, DstAlign, 4) ||
7462        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7463     return MVT::i32;
7464
7465   return MVT::Other;
7466 }
7467
7468 // 12-bit optionally shifted immediates are legal for adds.
7469 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7470   // Avoid UB for INT64_MIN.
7471   if (Immed == std::numeric_limits<int64_t>::min())
7472     return false;
7473   // Same encoding for add/sub, just flip the sign.
7474   Immed = std::abs(Immed);
7475   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7476 }
7477
7478 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7479 // immediates is the same as for an add or a sub.
7480 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7481   return isLegalAddImmediate(Immed);
7482 }
7483
7484 /// isLegalAddressingMode - Return true if the addressing mode represented
7485 /// by AM is legal for this target, for a load/store of the specified type.
7486 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7487                                                   const AddrMode &AM, Type *Ty,
7488                                                   unsigned AS) const {
7489   // AArch64 has five basic addressing modes:
7490   //  reg
7491   //  reg + 9-bit signed offset
7492   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7493   //  reg1 + reg2
7494   //  reg + SIZE_IN_BYTES * reg
7495
7496   // No global is ever allowed as a base.
7497   if (AM.BaseGV)
7498     return false;
7499
7500   // No reg+reg+imm addressing.
7501   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7502     return false;
7503
7504   // check reg + imm case:
7505   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7506   uint64_t NumBytes = 0;
7507   if (Ty->isSized()) {
7508     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7509     NumBytes = NumBits / 8;
7510     if (!isPowerOf2_64(NumBits))
7511       NumBytes = 0;
7512   }
7513
7514   if (!AM.Scale) {
7515     int64_t Offset = AM.BaseOffs;
7516
7517     // 9-bit signed offset
7518     if (isInt<9>(Offset))
7519       return true;
7520
7521     // 12-bit unsigned offset
7522     unsigned shift = Log2_64(NumBytes);
7523     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7524         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7525         (Offset >> shift) << shift == Offset)
7526       return true;
7527     return false;
7528   }
7529
7530   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7531
7532   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7533 }
7534
7535 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7536                                                 const AddrMode &AM, Type *Ty,
7537                                                 unsigned AS) const {
7538   // Scaling factors are not free at all.
7539   // Operands                     | Rt Latency
7540   // -------------------------------------------
7541   // Rt, [Xn, Xm]                 | 4
7542   // -------------------------------------------
7543   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7544   // Rt, [Xn, Wm, <extend> #imm]  |
7545   if (isLegalAddressingMode(DL, AM, Ty, AS))
7546     // Scale represents reg2 * scale, thus account for 1 if
7547     // it is not equal to 0 or 1.
7548     return AM.Scale != 0 && AM.Scale != 1;
7549   return -1;
7550 }
7551
7552 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7553   VT = VT.getScalarType();
7554
7555   if (!VT.isSimple())
7556     return false;
7557
7558   switch (VT.getSimpleVT().SimpleTy) {
7559   case MVT::f32:
7560   case MVT::f64:
7561     return true;
7562   default:
7563     break;
7564   }
7565
7566   return false;
7567 }
7568
7569 const MCPhysReg *
7570 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7571   // LR is a callee-save register, but we must treat it as clobbered by any call
7572   // site. Hence we include LR in the scratch registers, which are in turn added
7573   // as implicit-defs for stackmaps and patchpoints.
7574   static const MCPhysReg ScratchRegs[] = {
7575     AArch64::X16, AArch64::X17, AArch64::LR, 0
7576   };
7577   return ScratchRegs;
7578 }
7579
7580 bool
7581 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7582   EVT VT = N->getValueType(0);
7583     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7584     // it with shift to let it be lowered to UBFX.
7585   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7586       isa<ConstantSDNode>(N->getOperand(1))) {
7587     uint64_t TruncMask = N->getConstantOperandVal(1);
7588     if (isMask_64(TruncMask) &&
7589       N->getOperand(0).getOpcode() == ISD::SRL &&
7590       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7591       return false;
7592   }
7593   return true;
7594 }
7595
7596 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7597                                                               Type *Ty) const {
7598   assert(Ty->isIntegerTy());
7599
7600   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7601   if (BitSize == 0)
7602     return false;
7603
7604   int64_t Val = Imm.getSExtValue();
7605   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7606     return true;
7607
7608   if ((int64_t)Val < 0)
7609     Val = ~Val;
7610   if (BitSize == 32)
7611     Val &= (1LL << 32) - 1;
7612
7613   unsigned LZ = countLeadingZeros((uint64_t)Val);
7614   unsigned Shift = (63 - LZ) / 16;
7615   // MOVZ is free so return true for one or fewer MOVK.
7616   return Shift < 3;
7617 }
7618
7619 /// Turn vector tests of the signbit in the form of:
7620 ///   xor (sra X, elt_size(X)-1), -1
7621 /// into:
7622 ///   cmge X, X, #0
7623 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7624                                          const AArch64Subtarget *Subtarget) {
7625   EVT VT = N->getValueType(0);
7626   if (!Subtarget->hasNEON() || !VT.isVector())
7627     return SDValue();
7628
7629   // There must be a shift right algebraic before the xor, and the xor must be a
7630   // 'not' operation.
7631   SDValue Shift = N->getOperand(0);
7632   SDValue Ones = N->getOperand(1);
7633   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7634       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7635     return SDValue();
7636
7637   // The shift should be smearing the sign bit across each vector element.
7638   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7639   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7640   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7641     return SDValue();
7642
7643   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7644 }
7645
7646 // Generate SUBS and CSEL for integer abs.
7647 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7648   EVT VT = N->getValueType(0);
7649
7650   SDValue N0 = N->getOperand(0);
7651   SDValue N1 = N->getOperand(1);
7652   SDLoc DL(N);
7653
7654   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7655   // and change it to SUB and CSEL.
7656   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7657       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7658       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7659     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7660       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7661         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7662                                   N0.getOperand(0));
7663         // Generate SUBS & CSEL.
7664         SDValue Cmp =
7665             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7666                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7667         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7668                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7669                            SDValue(Cmp.getNode(), 1));
7670       }
7671   return SDValue();
7672 }
7673
7674 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7675                                  TargetLowering::DAGCombinerInfo &DCI,
7676                                  const AArch64Subtarget *Subtarget) {
7677   if (DCI.isBeforeLegalizeOps())
7678     return SDValue();
7679
7680   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7681     return Cmp;
7682
7683   return performIntegerAbsCombine(N, DAG);
7684 }
7685
7686 SDValue
7687 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7688                                      SelectionDAG &DAG,
7689                                      std::vector<SDNode *> *Created) const {
7690   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7691   if (isIntDivCheap(N->getValueType(0), Attr))
7692     return SDValue(N,0); // Lower SDIV as SDIV
7693
7694   // fold (sdiv X, pow2)
7695   EVT VT = N->getValueType(0);
7696   if ((VT != MVT::i32 && VT != MVT::i64) ||
7697       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7698     return SDValue();
7699
7700   SDLoc DL(N);
7701   SDValue N0 = N->getOperand(0);
7702   unsigned Lg2 = Divisor.countTrailingZeros();
7703   SDValue Zero = DAG.getConstant(0, DL, VT);
7704   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7705
7706   // Add (N0 < 0) ? Pow2 - 1 : 0;
7707   SDValue CCVal;
7708   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7709   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7710   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7711
7712   if (Created) {
7713     Created->push_back(Cmp.getNode());
7714     Created->push_back(Add.getNode());
7715     Created->push_back(CSel.getNode());
7716   }
7717
7718   // Divide by pow2.
7719   SDValue SRA =
7720       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7721
7722   // If we're dividing by a positive value, we're done.  Otherwise, we must
7723   // negate the result.
7724   if (Divisor.isNonNegative())
7725     return SRA;
7726
7727   if (Created)
7728     Created->push_back(SRA.getNode());
7729   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7730 }
7731
7732 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7733                                  TargetLowering::DAGCombinerInfo &DCI,
7734                                  const AArch64Subtarget *Subtarget) {
7735   if (DCI.isBeforeLegalizeOps())
7736     return SDValue();
7737
7738   // The below optimizations require a constant RHS.
7739   if (!isa<ConstantSDNode>(N->getOperand(1)))
7740     return SDValue();
7741
7742   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7743   const APInt &ConstValue = C->getAPIntValue();
7744
7745   // Multiplication of a power of two plus/minus one can be done more
7746   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7747   // future CPUs have a cheaper MADD instruction, this may need to be
7748   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7749   // 64-bit is 5 cycles, so this is always a win.
7750   // More aggressively, some multiplications N0 * C can be lowered to
7751   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7752   // e.g. 6=3*2=(2+1)*2.
7753   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7754   // which equals to (1+2)*16-(1+2).
7755   SDValue N0 = N->getOperand(0);
7756   // TrailingZeroes is used to test if the mul can be lowered to
7757   // shift+add+shift.
7758   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7759   if (TrailingZeroes) {
7760     // Conservatively do not lower to shift+add+shift if the mul might be
7761     // folded into smul or umul.
7762     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7763                             isZeroExtended(N0.getNode(), DAG)))
7764       return SDValue();
7765     // Conservatively do not lower to shift+add+shift if the mul might be
7766     // folded into madd or msub.
7767     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7768                            N->use_begin()->getOpcode() == ISD::SUB))
7769       return SDValue();
7770   }
7771   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7772   // and shift+add+shift.
7773   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7774
7775   unsigned ShiftAmt, AddSubOpc;
7776   // Is the shifted value the LHS operand of the add/sub?
7777   bool ShiftValUseIsN0 = true;
7778   // Do we need to negate the result?
7779   bool NegateResult = false;
7780
7781   if (ConstValue.isNonNegative()) {
7782     // (mul x, 2^N + 1) => (add (shl x, N), x)
7783     // (mul x, 2^N - 1) => (sub (shl x, N), x)
7784     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7785     APInt SCVMinus1 = ShiftedConstValue - 1;
7786     APInt CVPlus1 = ConstValue + 1;
7787     if (SCVMinus1.isPowerOf2()) {
7788       ShiftAmt = SCVMinus1.logBase2();
7789       AddSubOpc = ISD::ADD;
7790     } else if (CVPlus1.isPowerOf2()) {
7791       ShiftAmt = CVPlus1.logBase2();
7792       AddSubOpc = ISD::SUB;
7793     } else
7794       return SDValue();
7795   } else {
7796     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7797     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7798     APInt CVNegPlus1 = -ConstValue + 1;
7799     APInt CVNegMinus1 = -ConstValue - 1;
7800     if (CVNegPlus1.isPowerOf2()) {
7801       ShiftAmt = CVNegPlus1.logBase2();
7802       AddSubOpc = ISD::SUB;
7803       ShiftValUseIsN0 = false;
7804     } else if (CVNegMinus1.isPowerOf2()) {
7805       ShiftAmt = CVNegMinus1.logBase2();
7806       AddSubOpc = ISD::ADD;
7807       NegateResult = true;
7808     } else
7809       return SDValue();
7810   }
7811
7812   SDLoc DL(N);
7813   EVT VT = N->getValueType(0);
7814   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
7815                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
7816
7817   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7818   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7819   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
7820   assert(!(NegateResult && TrailingZeroes) &&
7821          "NegateResult and TrailingZeroes cannot both be true for now.");
7822   // Negate the result.
7823   if (NegateResult)
7824     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7825   // Shift the result.
7826   if (TrailingZeroes)
7827     return DAG.getNode(ISD::SHL, DL, VT, Res,
7828                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7829   return Res;
7830 }
7831
7832 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7833                                                          SelectionDAG &DAG) {
7834   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7835   // optimize away operation when it's from a constant.
7836   //
7837   // The general transformation is:
7838   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7839   //       AND(VECTOR_CMP(x,y), constant2)
7840   //    constant2 = UNARYOP(constant)
7841
7842   // Early exit if this isn't a vector operation, the operand of the
7843   // unary operation isn't a bitwise AND, or if the sizes of the operations
7844   // aren't the same.
7845   EVT VT = N->getValueType(0);
7846   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7847       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7848       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7849     return SDValue();
7850
7851   // Now check that the other operand of the AND is a constant. We could
7852   // make the transformation for non-constant splats as well, but it's unclear
7853   // that would be a benefit as it would not eliminate any operations, just
7854   // perform one more step in scalar code before moving to the vector unit.
7855   if (BuildVectorSDNode *BV =
7856           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7857     // Bail out if the vector isn't a constant.
7858     if (!BV->isConstant())
7859       return SDValue();
7860
7861     // Everything checks out. Build up the new and improved node.
7862     SDLoc DL(N);
7863     EVT IntVT = BV->getValueType(0);
7864     // Create a new constant of the appropriate type for the transformed
7865     // DAG.
7866     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7867     // The AND node needs bitcasts to/from an integer vector type around it.
7868     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7869     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7870                                  N->getOperand(0)->getOperand(0), MaskConst);
7871     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7872     return Res;
7873   }
7874
7875   return SDValue();
7876 }
7877
7878 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7879                                      const AArch64Subtarget *Subtarget) {
7880   // First try to optimize away the conversion when it's conditionally from
7881   // a constant. Vectors only.
7882   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7883     return Res;
7884
7885   EVT VT = N->getValueType(0);
7886   if (VT != MVT::f32 && VT != MVT::f64)
7887     return SDValue();
7888
7889   // Only optimize when the source and destination types have the same width.
7890   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7891     return SDValue();
7892
7893   // If the result of an integer load is only used by an integer-to-float
7894   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7895   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7896   SDValue N0 = N->getOperand(0);
7897   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7898       // Do not change the width of a volatile load.
7899       !cast<LoadSDNode>(N0)->isVolatile()) {
7900     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7901     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7902                                LN0->getPointerInfo(), LN0->getAlignment(),
7903                                LN0->getMemOperand()->getFlags());
7904
7905     // Make sure successors of the original load stay after it by updating them
7906     // to use the new Chain.
7907     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7908
7909     unsigned Opcode =
7910         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7911     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7912   }
7913
7914   return SDValue();
7915 }
7916
7917 /// Fold a floating-point multiply by power of two into floating-point to
7918 /// fixed-point conversion.
7919 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7920                                      TargetLowering::DAGCombinerInfo &DCI,
7921                                      const AArch64Subtarget *Subtarget) {
7922   if (!Subtarget->hasNEON())
7923     return SDValue();
7924
7925   SDValue Op = N->getOperand(0);
7926   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7927       Op.getOpcode() != ISD::FMUL)
7928     return SDValue();
7929
7930   SDValue ConstVec = Op->getOperand(1);
7931   if (!isa<BuildVectorSDNode>(ConstVec))
7932     return SDValue();
7933
7934   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7935   uint32_t FloatBits = FloatTy.getSizeInBits();
7936   if (FloatBits != 32 && FloatBits != 64)
7937     return SDValue();
7938
7939   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7940   uint32_t IntBits = IntTy.getSizeInBits();
7941   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7942     return SDValue();
7943
7944   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7945   if (IntBits > FloatBits)
7946     return SDValue();
7947
7948   BitVector UndefElements;
7949   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7950   int32_t Bits = IntBits == 64 ? 64 : 32;
7951   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7952   if (C == -1 || C == 0 || C > Bits)
7953     return SDValue();
7954
7955   MVT ResTy;
7956   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7957   switch (NumLanes) {
7958   default:
7959     return SDValue();
7960   case 2:
7961     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7962     break;
7963   case 4:
7964     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7965     break;
7966   }
7967
7968   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7969     return SDValue();
7970
7971   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7972          "Illegal vector type after legalization");
7973
7974   SDLoc DL(N);
7975   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7976   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7977                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7978   SDValue FixConv =
7979       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7980                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7981                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7982   // We can handle smaller integers by generating an extra trunc.
7983   if (IntBits < FloatBits)
7984     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7985
7986   return FixConv;
7987 }
7988
7989 /// Fold a floating-point divide by power of two into fixed-point to
7990 /// floating-point conversion.
7991 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7992                                   TargetLowering::DAGCombinerInfo &DCI,
7993                                   const AArch64Subtarget *Subtarget) {
7994   if (!Subtarget->hasNEON())
7995     return SDValue();
7996
7997   SDValue Op = N->getOperand(0);
7998   unsigned Opc = Op->getOpcode();
7999   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8000       !Op.getOperand(0).getValueType().isSimple() ||
8001       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8002     return SDValue();
8003
8004   SDValue ConstVec = N->getOperand(1);
8005   if (!isa<BuildVectorSDNode>(ConstVec))
8006     return SDValue();
8007
8008   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8009   int32_t IntBits = IntTy.getSizeInBits();
8010   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8011     return SDValue();
8012
8013   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8014   int32_t FloatBits = FloatTy.getSizeInBits();
8015   if (FloatBits != 32 && FloatBits != 64)
8016     return SDValue();
8017
8018   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8019   if (IntBits > FloatBits)
8020     return SDValue();
8021
8022   BitVector UndefElements;
8023   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8024   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8025   if (C == -1 || C == 0 || C > FloatBits)
8026     return SDValue();
8027
8028   MVT ResTy;
8029   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8030   switch (NumLanes) {
8031   default:
8032     return SDValue();
8033   case 2:
8034     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8035     break;
8036   case 4:
8037     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8038     break;
8039   }
8040
8041   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8042     return SDValue();
8043
8044   SDLoc DL(N);
8045   SDValue ConvInput = Op.getOperand(0);
8046   bool IsSigned = Opc == ISD::SINT_TO_FP;
8047   if (IntBits < FloatBits)
8048     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8049                             ResTy, ConvInput);
8050
8051   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8052                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
8053   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8054                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8055                      DAG.getConstant(C, DL, MVT::i32));
8056 }
8057
8058 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8059 /// searches for and classifies those shifts.
8060 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8061                          bool &FromHi) {
8062   if (N.getOpcode() == ISD::SHL)
8063     FromHi = false;
8064   else if (N.getOpcode() == ISD::SRL)
8065     FromHi = true;
8066   else
8067     return false;
8068
8069   if (!isa<ConstantSDNode>(N.getOperand(1)))
8070     return false;
8071
8072   ShiftAmount = N->getConstantOperandVal(1);
8073   Src = N->getOperand(0);
8074   return true;
8075 }
8076
8077 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8078 /// registers viewed as a high/low pair. This function looks for the pattern:
8079 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8080 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8081 /// independent.
8082 static SDValue tryCombineToEXTR(SDNode *N,
8083                                 TargetLowering::DAGCombinerInfo &DCI) {
8084   SelectionDAG &DAG = DCI.DAG;
8085   SDLoc DL(N);
8086   EVT VT = N->getValueType(0);
8087
8088   assert(N->getOpcode() == ISD::OR && "Unexpected root");
8089
8090   if (VT != MVT::i32 && VT != MVT::i64)
8091     return SDValue();
8092
8093   SDValue LHS;
8094   uint32_t ShiftLHS = 0;
8095   bool LHSFromHi = false;
8096   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8097     return SDValue();
8098
8099   SDValue RHS;
8100   uint32_t ShiftRHS = 0;
8101   bool RHSFromHi = false;
8102   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8103     return SDValue();
8104
8105   // If they're both trying to come from the high part of the register, they're
8106   // not really an EXTR.
8107   if (LHSFromHi == RHSFromHi)
8108     return SDValue();
8109
8110   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8111     return SDValue();
8112
8113   if (LHSFromHi) {
8114     std::swap(LHS, RHS);
8115     std::swap(ShiftLHS, ShiftRHS);
8116   }
8117
8118   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8119                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
8120 }
8121
8122 static SDValue tryCombineToBSL(SDNode *N,
8123                                 TargetLowering::DAGCombinerInfo &DCI) {
8124   EVT VT = N->getValueType(0);
8125   SelectionDAG &DAG = DCI.DAG;
8126   SDLoc DL(N);
8127
8128   if (!VT.isVector())
8129     return SDValue();
8130
8131   SDValue N0 = N->getOperand(0);
8132   if (N0.getOpcode() != ISD::AND)
8133     return SDValue();
8134
8135   SDValue N1 = N->getOperand(1);
8136   if (N1.getOpcode() != ISD::AND)
8137     return SDValue();
8138
8139   // We only have to look for constant vectors here since the general, variable
8140   // case can be handled in TableGen.
8141   unsigned Bits = VT.getScalarSizeInBits();
8142   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8143   for (int i = 1; i >= 0; --i)
8144     for (int j = 1; j >= 0; --j) {
8145       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8146       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8147       if (!BVN0 || !BVN1)
8148         continue;
8149
8150       bool FoundMatch = true;
8151       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8152         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8153         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8154         if (!CN0 || !CN1 ||
8155             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8156           FoundMatch = false;
8157           break;
8158         }
8159       }
8160
8161       if (FoundMatch)
8162         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8163                            N0->getOperand(1 - i), N1->getOperand(1 - j));
8164     }
8165
8166   return SDValue();
8167 }
8168
8169 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8170                                 const AArch64Subtarget *Subtarget) {
8171   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8172   SelectionDAG &DAG = DCI.DAG;
8173   EVT VT = N->getValueType(0);
8174
8175   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8176     return SDValue();
8177
8178   if (SDValue Res = tryCombineToEXTR(N, DCI))
8179     return Res;
8180
8181   if (SDValue Res = tryCombineToBSL(N, DCI))
8182     return Res;
8183
8184   return SDValue();
8185 }
8186
8187 static SDValue performSRLCombine(SDNode *N,
8188                                  TargetLowering::DAGCombinerInfo &DCI) {
8189   SelectionDAG &DAG = DCI.DAG;
8190   EVT VT = N->getValueType(0);
8191   if (VT != MVT::i32 && VT != MVT::i64)
8192     return SDValue();
8193
8194   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8195   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8196   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8197   SDValue N0 = N->getOperand(0);
8198   if (N0.getOpcode() == ISD::BSWAP) {
8199     SDLoc DL(N);
8200     SDValue N1 = N->getOperand(1);
8201     SDValue N00 = N0.getOperand(0);
8202     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8203       uint64_t ShiftAmt = C->getZExtValue();
8204       if (VT == MVT::i32 && ShiftAmt == 16 &&
8205           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8206         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8207       if (VT == MVT::i64 && ShiftAmt == 32 &&
8208           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8209         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8210     }
8211   }
8212   return SDValue();
8213 }
8214
8215 static SDValue performBitcastCombine(SDNode *N,
8216                                      TargetLowering::DAGCombinerInfo &DCI,
8217                                      SelectionDAG &DAG) {
8218   // Wait 'til after everything is legalized to try this. That way we have
8219   // legal vector types and such.
8220   if (DCI.isBeforeLegalizeOps())
8221     return SDValue();
8222
8223   // Remove extraneous bitcasts around an extract_subvector.
8224   // For example,
8225   //    (v4i16 (bitconvert
8226   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8227   //  becomes
8228   //    (extract_subvector ((v8i16 ...), (i64 4)))
8229
8230   // Only interested in 64-bit vectors as the ultimate result.
8231   EVT VT = N->getValueType(0);
8232   if (!VT.isVector())
8233     return SDValue();
8234   if (VT.getSimpleVT().getSizeInBits() != 64)
8235     return SDValue();
8236   // Is the operand an extract_subvector starting at the beginning or halfway
8237   // point of the vector? A low half may also come through as an
8238   // EXTRACT_SUBREG, so look for that, too.
8239   SDValue Op0 = N->getOperand(0);
8240   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8241       !(Op0->isMachineOpcode() &&
8242         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8243     return SDValue();
8244   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8245   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8246     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8247       return SDValue();
8248   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8249     if (idx != AArch64::dsub)
8250       return SDValue();
8251     // The dsub reference is equivalent to a lane zero subvector reference.
8252     idx = 0;
8253   }
8254   // Look through the bitcast of the input to the extract.
8255   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8256     return SDValue();
8257   SDValue Source = Op0->getOperand(0)->getOperand(0);
8258   // If the source type has twice the number of elements as our destination
8259   // type, we know this is an extract of the high or low half of the vector.
8260   EVT SVT = Source->getValueType(0);
8261   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8262     return SDValue();
8263
8264   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8265
8266   // Create the simplified form to just extract the low or high half of the
8267   // vector directly rather than bothering with the bitcasts.
8268   SDLoc dl(N);
8269   unsigned NumElements = VT.getVectorNumElements();
8270   if (idx) {
8271     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8272     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8273   } else {
8274     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8275     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8276                                       Source, SubReg),
8277                    0);
8278   }
8279 }
8280
8281 static SDValue performConcatVectorsCombine(SDNode *N,
8282                                            TargetLowering::DAGCombinerInfo &DCI,
8283                                            SelectionDAG &DAG) {
8284   SDLoc dl(N);
8285   EVT VT = N->getValueType(0);
8286   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8287
8288   // Optimize concat_vectors of truncated vectors, where the intermediate
8289   // type is illegal, to avoid said illegality,  e.g.,
8290   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8291   //                          (v2i16 (truncate (v2i64)))))
8292   // ->
8293   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8294   //                                    (v4i32 (bitcast (v2i64))),
8295   //                                    <0, 2, 4, 6>)))
8296   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8297   // on both input and result type, so we might generate worse code.
8298   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8299   if (N->getNumOperands() == 2 &&
8300       N0->getOpcode() == ISD::TRUNCATE &&
8301       N1->getOpcode() == ISD::TRUNCATE) {
8302     SDValue N00 = N0->getOperand(0);
8303     SDValue N10 = N1->getOperand(0);
8304     EVT N00VT = N00.getValueType();
8305
8306     if (N00VT == N10.getValueType() &&
8307         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8308         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8309       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8310       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8311       for (size_t i = 0; i < Mask.size(); ++i)
8312         Mask[i] = i * 2;
8313       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8314                          DAG.getVectorShuffle(
8315                              MidVT, dl,
8316                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8317                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8318     }
8319   }
8320
8321   // Wait 'til after everything is legalized to try this. That way we have
8322   // legal vector types and such.
8323   if (DCI.isBeforeLegalizeOps())
8324     return SDValue();
8325
8326   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8327   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8328   // canonicalise to that.
8329   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8330     assert(VT.getScalarSizeInBits() == 64);
8331     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8332                        DAG.getConstant(0, dl, MVT::i64));
8333   }
8334
8335   // Canonicalise concat_vectors so that the right-hand vector has as few
8336   // bit-casts as possible before its real operation. The primary matching
8337   // destination for these operations will be the narrowing "2" instructions,
8338   // which depend on the operation being performed on this right-hand vector.
8339   // For example,
8340   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8341   // becomes
8342   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8343
8344   if (N1->getOpcode() != ISD::BITCAST)
8345     return SDValue();
8346   SDValue RHS = N1->getOperand(0);
8347   MVT RHSTy = RHS.getValueType().getSimpleVT();
8348   // If the RHS is not a vector, this is not the pattern we're looking for.
8349   if (!RHSTy.isVector())
8350     return SDValue();
8351
8352   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8353
8354   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8355                                   RHSTy.getVectorNumElements() * 2);
8356   return DAG.getNode(ISD::BITCAST, dl, VT,
8357                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8358                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8359                                  RHS));
8360 }
8361
8362 static SDValue tryCombineFixedPointConvert(SDNode *N,
8363                                            TargetLowering::DAGCombinerInfo &DCI,
8364                                            SelectionDAG &DAG) {
8365   // Wait 'til after everything is legalized to try this. That way we have
8366   // legal vector types and such.
8367   if (DCI.isBeforeLegalizeOps())
8368     return SDValue();
8369   // Transform a scalar conversion of a value from a lane extract into a
8370   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8371   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8372   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8373   //
8374   // The second form interacts better with instruction selection and the
8375   // register allocator to avoid cross-class register copies that aren't
8376   // coalescable due to a lane reference.
8377
8378   // Check the operand and see if it originates from a lane extract.
8379   SDValue Op1 = N->getOperand(1);
8380   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8381     // Yep, no additional predication needed. Perform the transform.
8382     SDValue IID = N->getOperand(0);
8383     SDValue Shift = N->getOperand(2);
8384     SDValue Vec = Op1.getOperand(0);
8385     SDValue Lane = Op1.getOperand(1);
8386     EVT ResTy = N->getValueType(0);
8387     EVT VecResTy;
8388     SDLoc DL(N);
8389
8390     // The vector width should be 128 bits by the time we get here, even
8391     // if it started as 64 bits (the extract_vector handling will have
8392     // done so).
8393     assert(Vec.getValueSizeInBits() == 128 &&
8394            "unexpected vector size on extract_vector_elt!");
8395     if (Vec.getValueType() == MVT::v4i32)
8396       VecResTy = MVT::v4f32;
8397     else if (Vec.getValueType() == MVT::v2i64)
8398       VecResTy = MVT::v2f64;
8399     else
8400       llvm_unreachable("unexpected vector type!");
8401
8402     SDValue Convert =
8403         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8404     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8405   }
8406   return SDValue();
8407 }
8408
8409 // AArch64 high-vector "long" operations are formed by performing the non-high
8410 // version on an extract_subvector of each operand which gets the high half:
8411 //
8412 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8413 //
8414 // However, there are cases which don't have an extract_high explicitly, but
8415 // have another operation that can be made compatible with one for free. For
8416 // example:
8417 //
8418 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8419 //
8420 // This routine does the actual conversion of such DUPs, once outer routines
8421 // have determined that everything else is in order.
8422 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8423 // similarly here.
8424 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8425   switch (N.getOpcode()) {
8426   case AArch64ISD::DUP:
8427   case AArch64ISD::DUPLANE8:
8428   case AArch64ISD::DUPLANE16:
8429   case AArch64ISD::DUPLANE32:
8430   case AArch64ISD::DUPLANE64:
8431   case AArch64ISD::MOVI:
8432   case AArch64ISD::MOVIshift:
8433   case AArch64ISD::MOVIedit:
8434   case AArch64ISD::MOVImsl:
8435   case AArch64ISD::MVNIshift:
8436   case AArch64ISD::MVNImsl:
8437     break;
8438   default:
8439     // FMOV could be supported, but isn't very useful, as it would only occur
8440     // if you passed a bitcast' floating point immediate to an eligible long
8441     // integer op (addl, smull, ...).
8442     return SDValue();
8443   }
8444
8445   MVT NarrowTy = N.getSimpleValueType();
8446   if (!NarrowTy.is64BitVector())
8447     return SDValue();
8448
8449   MVT ElementTy = NarrowTy.getVectorElementType();
8450   unsigned NumElems = NarrowTy.getVectorNumElements();
8451   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8452
8453   SDLoc dl(N);
8454   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8455                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8456                      DAG.getConstant(NumElems, dl, MVT::i64));
8457 }
8458
8459 static bool isEssentiallyExtractSubvector(SDValue N) {
8460   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8461     return true;
8462
8463   return N.getOpcode() == ISD::BITCAST &&
8464          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8465 }
8466
8467 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8468 struct GenericSetCCInfo {
8469   const SDValue *Opnd0;
8470   const SDValue *Opnd1;
8471   ISD::CondCode CC;
8472 };
8473
8474 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8475 struct AArch64SetCCInfo {
8476   const SDValue *Cmp;
8477   AArch64CC::CondCode CC;
8478 };
8479
8480 /// \brief Helper structure to keep track of SetCC information.
8481 union SetCCInfo {
8482   GenericSetCCInfo Generic;
8483   AArch64SetCCInfo AArch64;
8484 };
8485
8486 /// \brief Helper structure to be able to read SetCC information.  If set to
8487 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8488 /// GenericSetCCInfo.
8489 struct SetCCInfoAndKind {
8490   SetCCInfo Info;
8491   bool IsAArch64;
8492 };
8493
8494 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8495 /// an
8496 /// AArch64 lowered one.
8497 /// \p SetCCInfo is filled accordingly.
8498 /// \post SetCCInfo is meanginfull only when this function returns true.
8499 /// \return True when Op is a kind of SET_CC operation.
8500 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8501   // If this is a setcc, this is straight forward.
8502   if (Op.getOpcode() == ISD::SETCC) {
8503     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8504     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8505     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8506     SetCCInfo.IsAArch64 = false;
8507     return true;
8508   }
8509   // Otherwise, check if this is a matching csel instruction.
8510   // In other words:
8511   // - csel 1, 0, cc
8512   // - csel 0, 1, !cc
8513   if (Op.getOpcode() != AArch64ISD::CSEL)
8514     return false;
8515   // Set the information about the operands.
8516   // TODO: we want the operands of the Cmp not the csel
8517   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8518   SetCCInfo.IsAArch64 = true;
8519   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8520       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8521
8522   // Check that the operands matches the constraints:
8523   // (1) Both operands must be constants.
8524   // (2) One must be 1 and the other must be 0.
8525   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8526   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8527
8528   // Check (1).
8529   if (!TValue || !FValue)
8530     return false;
8531
8532   // Check (2).
8533   if (!TValue->isOne()) {
8534     // Update the comparison when we are interested in !cc.
8535     std::swap(TValue, FValue);
8536     SetCCInfo.Info.AArch64.CC =
8537         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8538   }
8539   return TValue->isOne() && FValue->isNullValue();
8540 }
8541
8542 // Returns true if Op is setcc or zext of setcc.
8543 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8544   if (isSetCC(Op, Info))
8545     return true;
8546   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8547     isSetCC(Op->getOperand(0), Info));
8548 }
8549
8550 // The folding we want to perform is:
8551 // (add x, [zext] (setcc cc ...) )
8552 //   -->
8553 // (csel x, (add x, 1), !cc ...)
8554 //
8555 // The latter will get matched to a CSINC instruction.
8556 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8557   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8558   SDValue LHS = Op->getOperand(0);
8559   SDValue RHS = Op->getOperand(1);
8560   SetCCInfoAndKind InfoAndKind;
8561
8562   // If neither operand is a SET_CC, give up.
8563   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8564     std::swap(LHS, RHS);
8565     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8566       return SDValue();
8567   }
8568
8569   // FIXME: This could be generatized to work for FP comparisons.
8570   EVT CmpVT = InfoAndKind.IsAArch64
8571                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8572                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8573   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8574     return SDValue();
8575
8576   SDValue CCVal;
8577   SDValue Cmp;
8578   SDLoc dl(Op);
8579   if (InfoAndKind.IsAArch64) {
8580     CCVal = DAG.getConstant(
8581         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8582         MVT::i32);
8583     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8584   } else
8585     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8586                       *InfoAndKind.Info.Generic.Opnd1,
8587                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8588                       CCVal, DAG, dl);
8589
8590   EVT VT = Op->getValueType(0);
8591   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8592   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8593 }
8594
8595 // The basic add/sub long vector instructions have variants with "2" on the end
8596 // which act on the high-half of their inputs. They are normally matched by
8597 // patterns like:
8598 //
8599 // (add (zeroext (extract_high LHS)),
8600 //      (zeroext (extract_high RHS)))
8601 // -> uaddl2 vD, vN, vM
8602 //
8603 // However, if one of the extracts is something like a duplicate, this
8604 // instruction can still be used profitably. This function puts the DAG into a
8605 // more appropriate form for those patterns to trigger.
8606 static SDValue performAddSubLongCombine(SDNode *N,
8607                                         TargetLowering::DAGCombinerInfo &DCI,
8608                                         SelectionDAG &DAG) {
8609   if (DCI.isBeforeLegalizeOps())
8610     return SDValue();
8611
8612   MVT VT = N->getSimpleValueType(0);
8613   if (!VT.is128BitVector()) {
8614     if (N->getOpcode() == ISD::ADD)
8615       return performSetccAddFolding(N, DAG);
8616     return SDValue();
8617   }
8618
8619   // Make sure both branches are extended in the same way.
8620   SDValue LHS = N->getOperand(0);
8621   SDValue RHS = N->getOperand(1);
8622   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8623        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8624       LHS.getOpcode() != RHS.getOpcode())
8625     return SDValue();
8626
8627   unsigned ExtType = LHS.getOpcode();
8628
8629   // It's not worth doing if at least one of the inputs isn't already an
8630   // extract, but we don't know which it'll be so we have to try both.
8631   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8632     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8633     if (!RHS.getNode())
8634       return SDValue();
8635
8636     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8637   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8638     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8639     if (!LHS.getNode())
8640       return SDValue();
8641
8642     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8643   }
8644
8645   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8646 }
8647
8648 // Massage DAGs which we can use the high-half "long" operations on into
8649 // something isel will recognize better. E.g.
8650 //
8651 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8652 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8653 //                     (extract_high (v2i64 (dup128 scalar)))))
8654 //
8655 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8656                                        TargetLowering::DAGCombinerInfo &DCI,
8657                                        SelectionDAG &DAG) {
8658   if (DCI.isBeforeLegalizeOps())
8659     return SDValue();
8660
8661   SDValue LHS = N->getOperand(1);
8662   SDValue RHS = N->getOperand(2);
8663   assert(LHS.getValueType().is64BitVector() &&
8664          RHS.getValueType().is64BitVector() &&
8665          "unexpected shape for long operation");
8666
8667   // Either node could be a DUP, but it's not worth doing both of them (you'd
8668   // just as well use the non-high version) so look for a corresponding extract
8669   // operation on the other "wing".
8670   if (isEssentiallyExtractSubvector(LHS)) {
8671     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8672     if (!RHS.getNode())
8673       return SDValue();
8674   } else if (isEssentiallyExtractSubvector(RHS)) {
8675     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8676     if (!LHS.getNode())
8677       return SDValue();
8678   }
8679
8680   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8681                      N->getOperand(0), LHS, RHS);
8682 }
8683
8684 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8685   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8686   unsigned ElemBits = ElemTy.getSizeInBits();
8687
8688   int64_t ShiftAmount;
8689   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8690     APInt SplatValue, SplatUndef;
8691     unsigned SplatBitSize;
8692     bool HasAnyUndefs;
8693     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8694                               HasAnyUndefs, ElemBits) ||
8695         SplatBitSize != ElemBits)
8696       return SDValue();
8697
8698     ShiftAmount = SplatValue.getSExtValue();
8699   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8700     ShiftAmount = CVN->getSExtValue();
8701   } else
8702     return SDValue();
8703
8704   unsigned Opcode;
8705   bool IsRightShift;
8706   switch (IID) {
8707   default:
8708     llvm_unreachable("Unknown shift intrinsic");
8709   case Intrinsic::aarch64_neon_sqshl:
8710     Opcode = AArch64ISD::SQSHL_I;
8711     IsRightShift = false;
8712     break;
8713   case Intrinsic::aarch64_neon_uqshl:
8714     Opcode = AArch64ISD::UQSHL_I;
8715     IsRightShift = false;
8716     break;
8717   case Intrinsic::aarch64_neon_srshl:
8718     Opcode = AArch64ISD::SRSHR_I;
8719     IsRightShift = true;
8720     break;
8721   case Intrinsic::aarch64_neon_urshl:
8722     Opcode = AArch64ISD::URSHR_I;
8723     IsRightShift = true;
8724     break;
8725   case Intrinsic::aarch64_neon_sqshlu:
8726     Opcode = AArch64ISD::SQSHLU_I;
8727     IsRightShift = false;
8728     break;
8729   }
8730
8731   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8732     SDLoc dl(N);
8733     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8734                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8735   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8736     SDLoc dl(N);
8737     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8738                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8739   }
8740
8741   return SDValue();
8742 }
8743
8744 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8745 // the intrinsics must be legal and take an i32, this means there's almost
8746 // certainly going to be a zext in the DAG which we can eliminate.
8747 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8748   SDValue AndN = N->getOperand(2);
8749   if (AndN.getOpcode() != ISD::AND)
8750     return SDValue();
8751
8752   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8753   if (!CMask || CMask->getZExtValue() != Mask)
8754     return SDValue();
8755
8756   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8757                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8758 }
8759
8760 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8761                                            SelectionDAG &DAG) {
8762   SDLoc dl(N);
8763   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8764                      DAG.getNode(Opc, dl,
8765                                  N->getOperand(1).getSimpleValueType(),
8766                                  N->getOperand(1)),
8767                      DAG.getConstant(0, dl, MVT::i64));
8768 }
8769
8770 static SDValue performIntrinsicCombine(SDNode *N,
8771                                        TargetLowering::DAGCombinerInfo &DCI,
8772                                        const AArch64Subtarget *Subtarget) {
8773   SelectionDAG &DAG = DCI.DAG;
8774   unsigned IID = getIntrinsicID(N);
8775   switch (IID) {
8776   default:
8777     break;
8778   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8779   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8780     return tryCombineFixedPointConvert(N, DCI, DAG);
8781   case Intrinsic::aarch64_neon_saddv:
8782     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8783   case Intrinsic::aarch64_neon_uaddv:
8784     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8785   case Intrinsic::aarch64_neon_sminv:
8786     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8787   case Intrinsic::aarch64_neon_uminv:
8788     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8789   case Intrinsic::aarch64_neon_smaxv:
8790     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8791   case Intrinsic::aarch64_neon_umaxv:
8792     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8793   case Intrinsic::aarch64_neon_fmax:
8794     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8795                        N->getOperand(1), N->getOperand(2));
8796   case Intrinsic::aarch64_neon_fmin:
8797     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8798                        N->getOperand(1), N->getOperand(2));
8799   case Intrinsic::aarch64_neon_fmaxnm:
8800     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8801                        N->getOperand(1), N->getOperand(2));
8802   case Intrinsic::aarch64_neon_fminnm:
8803     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8804                        N->getOperand(1), N->getOperand(2));
8805   case Intrinsic::aarch64_neon_smull:
8806   case Intrinsic::aarch64_neon_umull:
8807   case Intrinsic::aarch64_neon_pmull:
8808   case Intrinsic::aarch64_neon_sqdmull:
8809     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8810   case Intrinsic::aarch64_neon_sqshl:
8811   case Intrinsic::aarch64_neon_uqshl:
8812   case Intrinsic::aarch64_neon_sqshlu:
8813   case Intrinsic::aarch64_neon_srshl:
8814   case Intrinsic::aarch64_neon_urshl:
8815     return tryCombineShiftImm(IID, N, DAG);
8816   case Intrinsic::aarch64_crc32b:
8817   case Intrinsic::aarch64_crc32cb:
8818     return tryCombineCRC32(0xff, N, DAG);
8819   case Intrinsic::aarch64_crc32h:
8820   case Intrinsic::aarch64_crc32ch:
8821     return tryCombineCRC32(0xffff, N, DAG);
8822   }
8823   return SDValue();
8824 }
8825
8826 static SDValue performExtendCombine(SDNode *N,
8827                                     TargetLowering::DAGCombinerInfo &DCI,
8828                                     SelectionDAG &DAG) {
8829   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8830   // we can convert that DUP into another extract_high (of a bigger DUP), which
8831   // helps the backend to decide that an sabdl2 would be useful, saving a real
8832   // extract_high operation.
8833   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8834       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8835     SDNode *ABDNode = N->getOperand(0).getNode();
8836     unsigned IID = getIntrinsicID(ABDNode);
8837     if (IID == Intrinsic::aarch64_neon_sabd ||
8838         IID == Intrinsic::aarch64_neon_uabd) {
8839       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8840       if (!NewABD.getNode())
8841         return SDValue();
8842
8843       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8844                          NewABD);
8845     }
8846   }
8847
8848   // This is effectively a custom type legalization for AArch64.
8849   //
8850   // Type legalization will split an extend of a small, legal, type to a larger
8851   // illegal type by first splitting the destination type, often creating
8852   // illegal source types, which then get legalized in isel-confusing ways,
8853   // leading to really terrible codegen. E.g.,
8854   //   %result = v8i32 sext v8i8 %value
8855   // becomes
8856   //   %losrc = extract_subreg %value, ...
8857   //   %hisrc = extract_subreg %value, ...
8858   //   %lo = v4i32 sext v4i8 %losrc
8859   //   %hi = v4i32 sext v4i8 %hisrc
8860   // Things go rapidly downhill from there.
8861   //
8862   // For AArch64, the [sz]ext vector instructions can only go up one element
8863   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8864   // take two instructions.
8865   //
8866   // This implies that the most efficient way to do the extend from v8i8
8867   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8868   // the normal splitting to happen for the v8i16->v8i32.
8869
8870   // This is pre-legalization to catch some cases where the default
8871   // type legalization will create ill-tempered code.
8872   if (!DCI.isBeforeLegalizeOps())
8873     return SDValue();
8874
8875   // We're only interested in cleaning things up for non-legal vector types
8876   // here. If both the source and destination are legal, things will just
8877   // work naturally without any fiddling.
8878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8879   EVT ResVT = N->getValueType(0);
8880   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8881     return SDValue();
8882   // If the vector type isn't a simple VT, it's beyond the scope of what
8883   // we're  worried about here. Let legalization do its thing and hope for
8884   // the best.
8885   SDValue Src = N->getOperand(0);
8886   EVT SrcVT = Src->getValueType(0);
8887   if (!ResVT.isSimple() || !SrcVT.isSimple())
8888     return SDValue();
8889
8890   // If the source VT is a 64-bit vector, we can play games and get the
8891   // better results we want.
8892   if (SrcVT.getSizeInBits() != 64)
8893     return SDValue();
8894
8895   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8896   unsigned ElementCount = SrcVT.getVectorNumElements();
8897   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8898   SDLoc DL(N);
8899   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8900
8901   // Now split the rest of the operation into two halves, each with a 64
8902   // bit source.
8903   EVT LoVT, HiVT;
8904   SDValue Lo, Hi;
8905   unsigned NumElements = ResVT.getVectorNumElements();
8906   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8907   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8908                                  ResVT.getVectorElementType(), NumElements / 2);
8909
8910   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8911                                LoVT.getVectorNumElements());
8912   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8913                    DAG.getConstant(0, DL, MVT::i64));
8914   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8915                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8916   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8917   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8918
8919   // Now combine the parts back together so we still have a single result
8920   // like the combiner expects.
8921   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8922 }
8923
8924 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8925                                SDValue SplatVal, unsigned NumVecElts) {
8926   unsigned OrigAlignment = St.getAlignment();
8927   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
8928
8929   // Create scalar stores. This is at least as good as the code sequence for a
8930   // split unaligned store which is a dup.s, ext.b, and two stores.
8931   // Most of the time the three stores should be replaced by store pair
8932   // instructions (stp).
8933   SDLoc DL(&St);
8934   SDValue BasePtr = St.getBasePtr();
8935   SDValue NewST1 =
8936       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(),
8937                    OrigAlignment, St.getMemOperand()->getFlags());
8938
8939   unsigned Offset = EltOffset;
8940   while (--NumVecElts) {
8941     unsigned Alignment = MinAlign(OrigAlignment, Offset);
8942     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8943                                     DAG.getConstant(Offset, DL, MVT::i64));
8944     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8945                           St.getPointerInfo(), Alignment,
8946                           St.getMemOperand()->getFlags());
8947     Offset += EltOffset;
8948   }
8949   return NewST1;
8950 }
8951
8952 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
8953 /// load store optimizer pass will merge them to store pair stores.  This should
8954 /// be better than a movi to create the vector zero followed by a vector store
8955 /// if the zero constant is not re-used, since one instructions and one register
8956 /// live range will be removed.
8957 ///
8958 /// For example, the final generated code should be:
8959 ///
8960 ///   stp xzr, xzr, [x0]
8961 ///
8962 /// instead of:
8963 ///
8964 ///   movi v0.2d, #0
8965 ///   str q0, [x0]
8966 ///
8967 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8968   SDValue StVal = St.getValue();
8969   EVT VT = StVal.getValueType();
8970
8971   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8972   // 2, 3 or 4 i32 elements.
8973   int NumVecElts = VT.getVectorNumElements();
8974   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8975          VT.getVectorElementType().getSizeInBits() == 64) ||
8976         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8977          VT.getVectorElementType().getSizeInBits() == 32)))
8978     return SDValue();
8979
8980   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8981     return SDValue();
8982
8983   // If the zero constant has more than one use then the vector store could be
8984   // better since the constant mov will be amortized and stp q instructions
8985   // should be able to be formed.
8986   if (!StVal.hasOneUse())
8987     return SDValue();
8988
8989   // If the immediate offset of the address operand is too large for the stp
8990   // instruction, then bail out.
8991   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8992     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
8993     if (Offset < -512 || Offset > 504)
8994       return SDValue();
8995   }
8996
8997   for (int I = 0; I < NumVecElts; ++I) {
8998     SDValue EltVal = StVal.getOperand(I);
8999     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9000       return SDValue();
9001   }
9002
9003   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9004   // undoing this transformation.
9005   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9006                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
9007                          : DAG.getRegister(AArch64::XZR, MVT::i64);
9008   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9009 }
9010
9011 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9012 /// value. The load store optimizer pass will merge them to store pair stores.
9013 /// This has better performance than a splat of the scalar followed by a split
9014 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9015 /// followed by an ext.b and two stores.
9016 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9017   SDValue StVal = St.getValue();
9018   EVT VT = StVal.getValueType();
9019
9020   // Don't replace floating point stores, they possibly won't be transformed to
9021   // stp because of the store pair suppress pass.
9022   if (VT.isFloatingPoint())
9023     return SDValue();
9024
9025   // We can express a splat as store pair(s) for 2 or 4 elements.
9026   unsigned NumVecElts = VT.getVectorNumElements();
9027   if (NumVecElts != 4 && NumVecElts != 2)
9028     return SDValue();
9029
9030   // Check that this is a splat.
9031   // Make sure that each of the relevant vector element locations are inserted
9032   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9033   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9034   SDValue SplatVal;
9035   for (unsigned I = 0; I < NumVecElts; ++I) {
9036     // Check for insert vector elements.
9037     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9038       return SDValue();
9039
9040     // Check that same value is inserted at each vector element.
9041     if (I == 0)
9042       SplatVal = StVal.getOperand(1);
9043     else if (StVal.getOperand(1) != SplatVal)
9044       return SDValue();
9045
9046     // Check insert element index.
9047     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9048     if (!CIndex)
9049       return SDValue();
9050     uint64_t IndexVal = CIndex->getZExtValue();
9051     if (IndexVal >= NumVecElts)
9052       return SDValue();
9053     IndexNotInserted.reset(IndexVal);
9054
9055     StVal = StVal.getOperand(0);
9056   }
9057   // Check that all vector element locations were inserted to.
9058   if (IndexNotInserted.any())
9059       return SDValue();
9060
9061   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9062 }
9063
9064 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9065                            SelectionDAG &DAG,
9066                            const AArch64Subtarget *Subtarget) {
9067   if (!DCI.isBeforeLegalize())
9068     return SDValue();
9069
9070   StoreSDNode *S = cast<StoreSDNode>(N);
9071   if (S->isVolatile())
9072     return SDValue();
9073
9074   SDValue StVal = S->getValue();
9075   EVT VT = StVal.getValueType();
9076   if (!VT.isVector())
9077     return SDValue();
9078
9079   // If we get a splat of zeros, convert this vector store to a store of
9080   // scalars. They will be merged into store pairs of xzr thereby removing one
9081   // instruction and one register.
9082   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9083     return ReplacedZeroSplat;
9084
9085   // FIXME: The logic for deciding if an unaligned store should be split should
9086   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9087   // a call to that function here.
9088
9089   if (!Subtarget->isMisaligned128StoreSlow())
9090     return SDValue();
9091
9092   // Don't split at -Oz.
9093   if (DAG.getMachineFunction().getFunction()->optForMinSize())
9094     return SDValue();
9095
9096   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9097   // those up regresses performance on micro-benchmarks and olden/bh.
9098   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9099     return SDValue();
9100
9101   // Split unaligned 16B stores. They are terrible for performance.
9102   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9103   // extensions can use this to mark that it does not want splitting to happen
9104   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9105   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9106   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9107       S->getAlignment() <= 2)
9108     return SDValue();
9109
9110   // If we get a splat of a scalar convert this vector store to a store of
9111   // scalars. They will be merged into store pairs thereby removing two
9112   // instructions.
9113   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9114     return ReplacedSplat;
9115
9116   SDLoc DL(S);
9117   unsigned NumElts = VT.getVectorNumElements() / 2;
9118   // Split VT into two.
9119   EVT HalfVT =
9120       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9121   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9122                                    DAG.getConstant(0, DL, MVT::i64));
9123   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9124                                    DAG.getConstant(NumElts, DL, MVT::i64));
9125   SDValue BasePtr = S->getBasePtr();
9126   SDValue NewST1 =
9127       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9128                    S->getAlignment(), S->getMemOperand()->getFlags());
9129   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9130                                   DAG.getConstant(8, DL, MVT::i64));
9131   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9132                       S->getPointerInfo(), S->getAlignment(),
9133                       S->getMemOperand()->getFlags());
9134 }
9135
9136 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9137 /// post-increment LD1R.
9138 static SDValue performPostLD1Combine(SDNode *N,
9139                                      TargetLowering::DAGCombinerInfo &DCI,
9140                                      bool IsLaneOp) {
9141   if (DCI.isBeforeLegalizeOps())
9142     return SDValue();
9143
9144   SelectionDAG &DAG = DCI.DAG;
9145   EVT VT = N->getValueType(0);
9146
9147   unsigned LoadIdx = IsLaneOp ? 1 : 0;
9148   SDNode *LD = N->getOperand(LoadIdx).getNode();
9149   // If it is not LOAD, can not do such combine.
9150   if (LD->getOpcode() != ISD::LOAD)
9151     return SDValue();
9152
9153   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9154   EVT MemVT = LoadSDN->getMemoryVT();
9155   // Check if memory operand is the same type as the vector element.
9156   if (MemVT != VT.getVectorElementType())
9157     return SDValue();
9158
9159   // Check if there are other uses. If so, do not combine as it will introduce
9160   // an extra load.
9161   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9162        ++UI) {
9163     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9164       continue;
9165     if (*UI != N)
9166       return SDValue();
9167   }
9168
9169   SDValue Addr = LD->getOperand(1);
9170   SDValue Vector = N->getOperand(0);
9171   // Search for a use of the address operand that is an increment.
9172   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9173        Addr.getNode()->use_end(); UI != UE; ++UI) {
9174     SDNode *User = *UI;
9175     if (User->getOpcode() != ISD::ADD
9176         || UI.getUse().getResNo() != Addr.getResNo())
9177       continue;
9178
9179     // Check that the add is independent of the load.  Otherwise, folding it
9180     // would create a cycle.
9181     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9182       continue;
9183     // Also check that add is not used in the vector operand.  This would also
9184     // create a cycle.
9185     if (User->isPredecessorOf(Vector.getNode()))
9186       continue;
9187
9188     // If the increment is a constant, it must match the memory ref size.
9189     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9190     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9191       uint32_t IncVal = CInc->getZExtValue();
9192       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9193       if (IncVal != NumBytes)
9194         continue;
9195       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9196     }
9197
9198     // Finally, check that the vector doesn't depend on the load.
9199     // Again, this would create a cycle.
9200     // The load depending on the vector is fine, as that's the case for the
9201     // LD1*post we'll eventually generate anyway.
9202     if (LoadSDN->isPredecessorOf(Vector.getNode()))
9203       continue;
9204
9205     SmallVector<SDValue, 8> Ops;
9206     Ops.push_back(LD->getOperand(0));  // Chain
9207     if (IsLaneOp) {
9208       Ops.push_back(Vector);           // The vector to be inserted
9209       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9210     }
9211     Ops.push_back(Addr);
9212     Ops.push_back(Inc);
9213
9214     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9215     SDVTList SDTys = DAG.getVTList(Tys);
9216     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9217     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9218                                            MemVT,
9219                                            LoadSDN->getMemOperand());
9220
9221     // Update the uses.
9222     SDValue NewResults[] = {
9223         SDValue(LD, 0),            // The result of load
9224         SDValue(UpdN.getNode(), 2) // Chain
9225     };
9226     DCI.CombineTo(LD, NewResults);
9227     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
9228     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
9229
9230     break;
9231   }
9232   return SDValue();
9233 }
9234
9235 /// Simplify \Addr given that the top byte of it is ignored by HW during
9236 /// address translation.
9237 static bool performTBISimplification(SDValue Addr,
9238                                      TargetLowering::DAGCombinerInfo &DCI,
9239                                      SelectionDAG &DAG) {
9240   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9241   APInt KnownZero, KnownOne;
9242   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9243                                         DCI.isBeforeLegalizeOps());
9244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9245   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9246     DCI.CommitTargetLoweringOpt(TLO);
9247     return true;
9248   }
9249   return false;
9250 }
9251
9252 static SDValue performSTORECombine(SDNode *N,
9253                                    TargetLowering::DAGCombinerInfo &DCI,
9254                                    SelectionDAG &DAG,
9255                                    const AArch64Subtarget *Subtarget) {
9256   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9257     return Split;
9258
9259   if (Subtarget->supportsAddressTopByteIgnored() &&
9260       performTBISimplification(N->getOperand(2), DCI, DAG))
9261     return SDValue(N, 0);
9262
9263   return SDValue();
9264 }
9265
9266   /// This function handles the log2-shuffle pattern produced by the
9267 /// LoopVectorizer for the across vector reduction. It consists of
9268 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9269 /// are reduced, where s is an induction variable from 0 to
9270 /// log2(NumVectorElements).
9271 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9272                                                      unsigned Op,
9273                                                      SelectionDAG &DAG) {
9274   EVT VTy = OpV->getOperand(0).getValueType();
9275   if (!VTy.isVector())
9276     return SDValue();
9277
9278   int NumVecElts = VTy.getVectorNumElements();
9279   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9280     if (NumVecElts != 4)
9281       return SDValue();
9282   } else {
9283     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9284       return SDValue();
9285   }
9286
9287   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9288   SDValue PreOp = OpV;
9289   // Iterate over each step of the across vector reduction.
9290   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9291     SDValue CurOp = PreOp.getOperand(0);
9292     SDValue Shuffle = PreOp.getOperand(1);
9293     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9294       // Try to swap the 1st and 2nd operand as add and min/max instructions
9295       // are commutative.
9296       CurOp = PreOp.getOperand(1);
9297       Shuffle = PreOp.getOperand(0);
9298       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9299         return SDValue();
9300     }
9301
9302     // Check if the input vector is fed by the operator we want to handle,
9303     // except the last step; the very first input vector is not necessarily
9304     // the same operator we are handling.
9305     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9306       return SDValue();
9307
9308     // Check if it forms one step of the across vector reduction.
9309     // E.g.,
9310     //   %cur = add %1, %0
9311     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
9312     //   %pre = add %cur, %shuffle
9313     if (Shuffle.getOperand(0) != CurOp)
9314       return SDValue();
9315
9316     int NumMaskElts = 1 << CurStep;
9317     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9318     // Check mask values in each step.
9319     // We expect the shuffle mask in each step follows a specific pattern
9320     // denoted here by the <M, U> form, where M is a sequence of integers
9321     // starting from NumMaskElts, increasing by 1, and the number integers
9322     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9323     // of undef in U should be NumVecElts - NumMaskElts.
9324     // E.g., for <8 x i16>, mask values in each step should be :
9325     //   step 0 : <1,u,u,u,u,u,u,u>
9326     //   step 1 : <2,3,u,u,u,u,u,u>
9327     //   step 2 : <4,5,6,7,u,u,u,u>
9328     for (int i = 0; i < NumVecElts; ++i)
9329       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9330           (i >= NumMaskElts && !(Mask[i] < 0)))
9331         return SDValue();
9332
9333     PreOp = CurOp;
9334   }
9335   unsigned Opcode;
9336   bool IsIntrinsic = false;
9337
9338   switch (Op) {
9339   default:
9340     llvm_unreachable("Unexpected operator for across vector reduction");
9341   case ISD::ADD:
9342     Opcode = AArch64ISD::UADDV;
9343     break;
9344   case ISD::SMAX:
9345     Opcode = AArch64ISD::SMAXV;
9346     break;
9347   case ISD::UMAX:
9348     Opcode = AArch64ISD::UMAXV;
9349     break;
9350   case ISD::SMIN:
9351     Opcode = AArch64ISD::SMINV;
9352     break;
9353   case ISD::UMIN:
9354     Opcode = AArch64ISD::UMINV;
9355     break;
9356   case ISD::FMAXNUM:
9357     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9358     IsIntrinsic = true;
9359     break;
9360   case ISD::FMINNUM:
9361     Opcode = Intrinsic::aarch64_neon_fminnmv;
9362     IsIntrinsic = true;
9363     break;
9364   }
9365   SDLoc DL(N);
9366
9367   return IsIntrinsic
9368              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9369                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9370              : DAG.getNode(
9371                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9372                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9373                    DAG.getConstant(0, DL, MVT::i64));
9374 }
9375
9376 /// Target-specific DAG combine for the across vector min/max reductions.
9377 /// This function specifically handles the final clean-up step of the vector
9378 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9379 /// pattern, which narrows down and finds the final min/max value from all
9380 /// elements of the vector.
9381 /// For example, for a <16 x i8> vector :
9382 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9383 ///   %smax0 = smax %arr, svn0
9384 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9385 ///   %smax1 = smax %smax0, %svn1
9386 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9387 ///   %smax2 = smax %smax1, svn2
9388 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9389 ///   %sc = setcc %smax2, %svn3, gt
9390 ///   %n0 = extract_vector_elt %sc, #0
9391 ///   %n1 = extract_vector_elt %smax2, #0
9392 ///   %n2 = extract_vector_elt $smax2, #1
9393 ///   %result = select %n0, %n1, n2
9394 ///     becomes :
9395 ///   %1 = smaxv %0
9396 ///   %result = extract_vector_elt %1, 0
9397 static SDValue
9398 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9399                                         const AArch64Subtarget *Subtarget) {
9400   if (!Subtarget->hasNEON())
9401     return SDValue();
9402
9403   SDValue N0 = N->getOperand(0);
9404   SDValue IfTrue = N->getOperand(1);
9405   SDValue IfFalse = N->getOperand(2);
9406
9407   // Check if the SELECT merges up the final result of the min/max
9408   // from a vector.
9409   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9410       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9411       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9412     return SDValue();
9413
9414   // Expect N0 is fed by SETCC.
9415   SDValue SetCC = N0.getOperand(0);
9416   EVT SetCCVT = SetCC.getValueType();
9417   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9418       SetCCVT.getVectorElementType() != MVT::i1)
9419     return SDValue();
9420
9421   SDValue VectorOp = SetCC.getOperand(0);
9422   unsigned Op = VectorOp->getOpcode();
9423   // Check if the input vector is fed by the operator we want to handle.
9424   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9425       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9426     return SDValue();
9427
9428   EVT VTy = VectorOp.getValueType();
9429   if (!VTy.isVector())
9430     return SDValue();
9431
9432   if (VTy.getSizeInBits() < 64)
9433     return SDValue();
9434
9435   EVT EltTy = VTy.getVectorElementType();
9436   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9437     if (EltTy != MVT::f32)
9438       return SDValue();
9439   } else {
9440     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9441       return SDValue();
9442   }
9443
9444   // Check if extracting from the same vector.
9445   // For example,
9446   //   %sc = setcc %vector, %svn1, gt
9447   //   %n0 = extract_vector_elt %sc, #0
9448   //   %n1 = extract_vector_elt %vector, #0
9449   //   %n2 = extract_vector_elt $vector, #1
9450   if (!(VectorOp == IfTrue->getOperand(0) &&
9451         VectorOp == IfFalse->getOperand(0)))
9452     return SDValue();
9453
9454   // Check if the condition code is matched with the operator type.
9455   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9456   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9457       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9458       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9459       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9460       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9461        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9462        CC != ISD::SETGE) ||
9463       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9464        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9465        CC != ISD::SETLE))
9466     return SDValue();
9467
9468   // Expect to check only lane 0 from the vector SETCC.
9469   if (!isNullConstant(N0.getOperand(1)))
9470     return SDValue();
9471
9472   // Expect to extract the true value from lane 0.
9473   if (!isNullConstant(IfTrue.getOperand(1)))
9474     return SDValue();
9475
9476   // Expect to extract the false value from lane 1.
9477   if (!isOneConstant(IfFalse.getOperand(1)))
9478     return SDValue();
9479
9480   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9481 }
9482
9483 /// Target-specific DAG combine for the across vector add reduction.
9484 /// This function specifically handles the final clean-up step of the vector
9485 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9486 /// pattern, which adds all elements of a vector together.
9487 /// For example, for a <4 x i32> vector :
9488 ///   %1 = vector_shuffle %0, <2,3,u,u>
9489 ///   %2 = add %0, %1
9490 ///   %3 = vector_shuffle %2, <1,u,u,u>
9491 ///   %4 = add %2, %3
9492 ///   %result = extract_vector_elt %4, 0
9493 /// becomes :
9494 ///   %0 = uaddv %0
9495 ///   %result = extract_vector_elt %0, 0
9496 static SDValue
9497 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9498                                      const AArch64Subtarget *Subtarget) {
9499   if (!Subtarget->hasNEON())
9500     return SDValue();
9501   SDValue N0 = N->getOperand(0);
9502   SDValue N1 = N->getOperand(1);
9503
9504   // Check if the input vector is fed by the ADD.
9505   if (N0->getOpcode() != ISD::ADD)
9506     return SDValue();
9507
9508   // The vector extract idx must constant zero because we only expect the final
9509   // result of the reduction is placed in lane 0.
9510   if (!isNullConstant(N1))
9511     return SDValue();
9512
9513   EVT VTy = N0.getValueType();
9514   if (!VTy.isVector())
9515     return SDValue();
9516
9517   EVT EltTy = VTy.getVectorElementType();
9518   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9519     return SDValue();
9520
9521   if (VTy.getSizeInBits() < 64)
9522     return SDValue();
9523
9524   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9525 }
9526
9527 /// Target-specific DAG combine function for NEON load/store intrinsics
9528 /// to merge base address updates.
9529 static SDValue performNEONPostLDSTCombine(SDNode *N,
9530                                           TargetLowering::DAGCombinerInfo &DCI,
9531                                           SelectionDAG &DAG) {
9532   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9533     return SDValue();
9534
9535   unsigned AddrOpIdx = N->getNumOperands() - 1;
9536   SDValue Addr = N->getOperand(AddrOpIdx);
9537
9538   // Search for a use of the address operand that is an increment.
9539   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9540        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9541     SDNode *User = *UI;
9542     if (User->getOpcode() != ISD::ADD ||
9543         UI.getUse().getResNo() != Addr.getResNo())
9544       continue;
9545
9546     // Check that the add is independent of the load/store.  Otherwise, folding
9547     // it would create a cycle.
9548     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9549       continue;
9550
9551     // Find the new opcode for the updating load/store.
9552     bool IsStore = false;
9553     bool IsLaneOp = false;
9554     bool IsDupOp = false;
9555     unsigned NewOpc = 0;
9556     unsigned NumVecs = 0;
9557     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9558     switch (IntNo) {
9559     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9560     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9561       NumVecs = 2; break;
9562     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9563       NumVecs = 3; break;
9564     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9565       NumVecs = 4; break;
9566     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9567       NumVecs = 2; IsStore = true; break;
9568     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9569       NumVecs = 3; IsStore = true; break;
9570     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9571       NumVecs = 4; IsStore = true; break;
9572     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9573       NumVecs = 2; break;
9574     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9575       NumVecs = 3; break;
9576     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9577       NumVecs = 4; break;
9578     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9579       NumVecs = 2; IsStore = true; break;
9580     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9581       NumVecs = 3; IsStore = true; break;
9582     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9583       NumVecs = 4; IsStore = true; break;
9584     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9585       NumVecs = 2; IsDupOp = true; break;
9586     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9587       NumVecs = 3; IsDupOp = true; break;
9588     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9589       NumVecs = 4; IsDupOp = true; break;
9590     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9591       NumVecs = 2; IsLaneOp = true; break;
9592     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9593       NumVecs = 3; IsLaneOp = true; break;
9594     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9595       NumVecs = 4; IsLaneOp = true; break;
9596     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9597       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9598     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9599       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9600     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9601       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9602     }
9603
9604     EVT VecTy;
9605     if (IsStore)
9606       VecTy = N->getOperand(2).getValueType();
9607     else
9608       VecTy = N->getValueType(0);
9609
9610     // If the increment is a constant, it must match the memory ref size.
9611     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9612     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9613       uint32_t IncVal = CInc->getZExtValue();
9614       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9615       if (IsLaneOp || IsDupOp)
9616         NumBytes /= VecTy.getVectorNumElements();
9617       if (IncVal != NumBytes)
9618         continue;
9619       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9620     }
9621     SmallVector<SDValue, 8> Ops;
9622     Ops.push_back(N->getOperand(0)); // Incoming chain
9623     // Load lane and store have vector list as input.
9624     if (IsLaneOp || IsStore)
9625       for (unsigned i = 2; i < AddrOpIdx; ++i)
9626         Ops.push_back(N->getOperand(i));
9627     Ops.push_back(Addr); // Base register
9628     Ops.push_back(Inc);
9629
9630     // Return Types.
9631     EVT Tys[6];
9632     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9633     unsigned n;
9634     for (n = 0; n < NumResultVecs; ++n)
9635       Tys[n] = VecTy;
9636     Tys[n++] = MVT::i64;  // Type of write back register
9637     Tys[n] = MVT::Other;  // Type of the chain
9638     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9639
9640     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9641     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9642                                            MemInt->getMemoryVT(),
9643                                            MemInt->getMemOperand());
9644
9645     // Update the uses.
9646     std::vector<SDValue> NewResults;
9647     for (unsigned i = 0; i < NumResultVecs; ++i) {
9648       NewResults.push_back(SDValue(UpdN.getNode(), i));
9649     }
9650     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9651     DCI.CombineTo(N, NewResults);
9652     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9653
9654     break;
9655   }
9656   return SDValue();
9657 }
9658
9659 // Checks to see if the value is the prescribed width and returns information
9660 // about its extension mode.
9661 static
9662 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9663   ExtType = ISD::NON_EXTLOAD;
9664   switch(V.getNode()->getOpcode()) {
9665   default:
9666     return false;
9667   case ISD::LOAD: {
9668     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9669     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9670        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9671       ExtType = LoadNode->getExtensionType();
9672       return true;
9673     }
9674     return false;
9675   }
9676   case ISD::AssertSext: {
9677     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9678     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9679        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9680       ExtType = ISD::SEXTLOAD;
9681       return true;
9682     }
9683     return false;
9684   }
9685   case ISD::AssertZext: {
9686     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9687     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9688        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9689       ExtType = ISD::ZEXTLOAD;
9690       return true;
9691     }
9692     return false;
9693   }
9694   case ISD::Constant:
9695   case ISD::TargetConstant: {
9696     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9697            1LL << (width - 1);
9698   }
9699   }
9700
9701   return true;
9702 }
9703
9704 // This function does a whole lot of voodoo to determine if the tests are
9705 // equivalent without and with a mask. Essentially what happens is that given a
9706 // DAG resembling:
9707 //
9708 //  +-------------+ +-------------+ +-------------+ +-------------+
9709 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9710 //  +-------------+ +-------------+ +-------------+ +-------------+
9711 //           |           |           |               |
9712 //           V           V           |    +----------+
9713 //          +-------------+  +----+  |    |
9714 //          |     ADD     |  |0xff|  |    |
9715 //          +-------------+  +----+  |    |
9716 //                  |           |    |    |
9717 //                  V           V    |    |
9718 //                 +-------------+   |    |
9719 //                 |     AND     |   |    |
9720 //                 +-------------+   |    |
9721 //                      |            |    |
9722 //                      +-----+      |    |
9723 //                            |      |    |
9724 //                            V      V    V
9725 //                           +-------------+
9726 //                           |     CMP     |
9727 //                           +-------------+
9728 //
9729 // The AND node may be safely removed for some combinations of inputs. In
9730 // particular we need to take into account the extension type of the Input,
9731 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9732 // width of the input (this can work for any width inputs, the above graph is
9733 // specific to 8 bits.
9734 //
9735 // The specific equations were worked out by generating output tables for each
9736 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9737 // problem was simplified by working with 4 bit inputs, which means we only
9738 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9739 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9740 // patterns present in both extensions (0,7). For every distinct set of
9741 // AddConstant and CompConstants bit patterns we can consider the masked and
9742 // unmasked versions to be equivalent if the result of this function is true for
9743 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9744 //
9745 //   sub      w8, w0, w1
9746 //   and      w10, w8, #0x0f
9747 //   cmp      w8, w2
9748 //   cset     w9, AArch64CC
9749 //   cmp      w10, w2
9750 //   cset     w11, AArch64CC
9751 //   cmp      w9, w11
9752 //   cset     w0, eq
9753 //   ret
9754 //
9755 // Since the above function shows when the outputs are equivalent it defines
9756 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9757 // would be expensive to run during compiles. The equations below were written
9758 // in a test harness that confirmed they gave equivalent outputs to the above
9759 // for all inputs function, so they can be used determine if the removal is
9760 // legal instead.
9761 //
9762 // isEquivalentMaskless() is the code for testing if the AND can be removed
9763 // factored out of the DAG recognition as the DAG can take several forms.
9764
9765 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9766                                  ISD::LoadExtType ExtType, int AddConstant,
9767                                  int CompConstant) {
9768   // By being careful about our equations and only writing the in term
9769   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9770   // make them generally applicable to all bit widths.
9771   int MaxUInt = (1 << width);
9772
9773   // For the purposes of these comparisons sign extending the type is
9774   // equivalent to zero extending the add and displacing it by half the integer
9775   // width. Provided we are careful and make sure our equations are valid over
9776   // the whole range we can just adjust the input and avoid writing equations
9777   // for sign extended inputs.
9778   if (ExtType == ISD::SEXTLOAD)
9779     AddConstant -= (1 << (width-1));
9780
9781   switch(CC) {
9782   case AArch64CC::LE:
9783   case AArch64CC::GT:
9784     if ((AddConstant == 0) ||
9785         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9786         (AddConstant >= 0 && CompConstant < 0) ||
9787         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9788       return true;
9789     break;
9790   case AArch64CC::LT:
9791   case AArch64CC::GE:
9792     if ((AddConstant == 0) ||
9793         (AddConstant >= 0 && CompConstant <= 0) ||
9794         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9795       return true;
9796     break;
9797   case AArch64CC::HI:
9798   case AArch64CC::LS:
9799     if ((AddConstant >= 0 && CompConstant < 0) ||
9800        (AddConstant <= 0 && CompConstant >= -1 &&
9801         CompConstant < AddConstant + MaxUInt))
9802       return true;
9803    break;
9804   case AArch64CC::PL:
9805   case AArch64CC::MI:
9806     if ((AddConstant == 0) ||
9807         (AddConstant > 0 && CompConstant <= 0) ||
9808         (AddConstant < 0 && CompConstant <= AddConstant))
9809       return true;
9810     break;
9811   case AArch64CC::LO:
9812   case AArch64CC::HS:
9813     if ((AddConstant >= 0 && CompConstant <= 0) ||
9814         (AddConstant <= 0 && CompConstant >= 0 &&
9815          CompConstant <= AddConstant + MaxUInt))
9816       return true;
9817     break;
9818   case AArch64CC::EQ:
9819   case AArch64CC::NE:
9820     if ((AddConstant > 0 && CompConstant < 0) ||
9821         (AddConstant < 0 && CompConstant >= 0 &&
9822          CompConstant < AddConstant + MaxUInt) ||
9823         (AddConstant >= 0 && CompConstant >= 0 &&
9824          CompConstant >= AddConstant) ||
9825         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9826       return true;
9827     break;
9828   case AArch64CC::VS:
9829   case AArch64CC::VC:
9830   case AArch64CC::AL:
9831   case AArch64CC::NV:
9832     return true;
9833   case AArch64CC::Invalid:
9834     break;
9835   }
9836
9837   return false;
9838 }
9839
9840 static
9841 SDValue performCONDCombine(SDNode *N,
9842                            TargetLowering::DAGCombinerInfo &DCI,
9843                            SelectionDAG &DAG, unsigned CCIndex,
9844                            unsigned CmpIndex) {
9845   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9846   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9847   unsigned CondOpcode = SubsNode->getOpcode();
9848
9849   if (CondOpcode != AArch64ISD::SUBS)
9850     return SDValue();
9851
9852   // There is a SUBS feeding this condition. Is it fed by a mask we can
9853   // use?
9854
9855   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9856   unsigned MaskBits = 0;
9857
9858   if (AndNode->getOpcode() != ISD::AND)
9859     return SDValue();
9860
9861   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9862     uint32_t CNV = CN->getZExtValue();
9863     if (CNV == 255)
9864       MaskBits = 8;
9865     else if (CNV == 65535)
9866       MaskBits = 16;
9867   }
9868
9869   if (!MaskBits)
9870     return SDValue();
9871
9872   SDValue AddValue = AndNode->getOperand(0);
9873
9874   if (AddValue.getOpcode() != ISD::ADD)
9875     return SDValue();
9876
9877   // The basic dag structure is correct, grab the inputs and validate them.
9878
9879   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9880   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9881   SDValue SubsInputValue = SubsNode->getOperand(1);
9882
9883   // The mask is present and the provenance of all the values is a smaller type,
9884   // lets see if the mask is superfluous.
9885
9886   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9887       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9888     return SDValue();
9889
9890   ISD::LoadExtType ExtType;
9891
9892   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9893       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9894       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9895     return SDValue();
9896
9897   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9898                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9899                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9900     return SDValue();
9901
9902   // The AND is not necessary, remove it.
9903
9904   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9905                                SubsNode->getValueType(1));
9906   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9907
9908   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9909   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9910
9911   return SDValue(N, 0);
9912 }
9913
9914 // Optimize compare with zero and branch.
9915 static SDValue performBRCONDCombine(SDNode *N,
9916                                     TargetLowering::DAGCombinerInfo &DCI,
9917                                     SelectionDAG &DAG) {
9918   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9919     N = NV.getNode();
9920   SDValue Chain = N->getOperand(0);
9921   SDValue Dest = N->getOperand(1);
9922   SDValue CCVal = N->getOperand(2);
9923   SDValue Cmp = N->getOperand(3);
9924
9925   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9926   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9927   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9928     return SDValue();
9929
9930   unsigned CmpOpc = Cmp.getOpcode();
9931   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9932     return SDValue();
9933
9934   // Only attempt folding if there is only one use of the flag and no use of the
9935   // value.
9936   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9937     return SDValue();
9938
9939   SDValue LHS = Cmp.getOperand(0);
9940   SDValue RHS = Cmp.getOperand(1);
9941
9942   assert(LHS.getValueType() == RHS.getValueType() &&
9943          "Expected the value type to be the same for both operands!");
9944   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9945     return SDValue();
9946
9947   if (isNullConstant(LHS))
9948     std::swap(LHS, RHS);
9949
9950   if (!isNullConstant(RHS))
9951     return SDValue();
9952
9953   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9954       LHS.getOpcode() == ISD::SRL)
9955     return SDValue();
9956
9957   // Fold the compare into the branch instruction.
9958   SDValue BR;
9959   if (CC == AArch64CC::EQ)
9960     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9961   else
9962     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9963
9964   // Do not add new nodes to DAG combiner worklist.
9965   DCI.CombineTo(N, BR, false);
9966
9967   return SDValue();
9968 }
9969
9970 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9971 // as well as whether the test should be inverted.  This code is required to
9972 // catch these cases (as opposed to standard dag combines) because
9973 // AArch64ISD::TBZ is matched during legalization.
9974 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9975                                  SelectionDAG &DAG) {
9976
9977   if (!Op->hasOneUse())
9978     return Op;
9979
9980   // We don't handle undef/constant-fold cases below, as they should have
9981   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9982   // etc.)
9983
9984   // (tbz (trunc x), b) -> (tbz x, b)
9985   // This case is just here to enable more of the below cases to be caught.
9986   if (Op->getOpcode() == ISD::TRUNCATE &&
9987       Bit < Op->getValueType(0).getSizeInBits()) {
9988     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9989   }
9990
9991   if (Op->getNumOperands() != 2)
9992     return Op;
9993
9994   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9995   if (!C)
9996     return Op;
9997
9998   switch (Op->getOpcode()) {
9999   default:
10000     return Op;
10001
10002   // (tbz (and x, m), b) -> (tbz x, b)
10003   case ISD::AND:
10004     if ((C->getZExtValue() >> Bit) & 1)
10005       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10006     return Op;
10007
10008   // (tbz (shl x, c), b) -> (tbz x, b-c)
10009   case ISD::SHL:
10010     if (C->getZExtValue() <= Bit &&
10011         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10012       Bit = Bit - C->getZExtValue();
10013       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10014     }
10015     return Op;
10016
10017   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10018   case ISD::SRA:
10019     Bit = Bit + C->getZExtValue();
10020     if (Bit >= Op->getValueType(0).getSizeInBits())
10021       Bit = Op->getValueType(0).getSizeInBits() - 1;
10022     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10023
10024   // (tbz (srl x, c), b) -> (tbz x, b+c)
10025   case ISD::SRL:
10026     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10027       Bit = Bit + C->getZExtValue();
10028       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10029     }
10030     return Op;
10031
10032   // (tbz (xor x, -1), b) -> (tbnz x, b)
10033   case ISD::XOR:
10034     if ((C->getZExtValue() >> Bit) & 1)
10035       Invert = !Invert;
10036     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10037   }
10038 }
10039
10040 // Optimize test single bit zero/non-zero and branch.
10041 static SDValue performTBZCombine(SDNode *N,
10042                                  TargetLowering::DAGCombinerInfo &DCI,
10043                                  SelectionDAG &DAG) {
10044   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10045   bool Invert = false;
10046   SDValue TestSrc = N->getOperand(1);
10047   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10048
10049   if (TestSrc == NewTestSrc)
10050     return SDValue();
10051
10052   unsigned NewOpc = N->getOpcode();
10053   if (Invert) {
10054     if (NewOpc == AArch64ISD::TBZ)
10055       NewOpc = AArch64ISD::TBNZ;
10056     else {
10057       assert(NewOpc == AArch64ISD::TBNZ);
10058       NewOpc = AArch64ISD::TBZ;
10059     }
10060   }
10061
10062   SDLoc DL(N);
10063   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10064                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10065 }
10066
10067 // vselect (v1i1 setcc) ->
10068 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10069 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10070 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10071 // such VSELECT.
10072 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10073   SDValue N0 = N->getOperand(0);
10074   EVT CCVT = N0.getValueType();
10075
10076   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10077       CCVT.getVectorElementType() != MVT::i1)
10078     return SDValue();
10079
10080   EVT ResVT = N->getValueType(0);
10081   EVT CmpVT = N0.getOperand(0).getValueType();
10082   // Only combine when the result type is of the same size as the compared
10083   // operands.
10084   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10085     return SDValue();
10086
10087   SDValue IfTrue = N->getOperand(1);
10088   SDValue IfFalse = N->getOperand(2);
10089   SDValue SetCC =
10090       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10091                    N0.getOperand(0), N0.getOperand(1),
10092                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10093   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10094                      IfTrue, IfFalse);
10095 }
10096
10097 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10098 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10099 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10100 /// with a vector one followed by a DUP shuffle on the result.
10101 static SDValue performSelectCombine(SDNode *N,
10102                                     TargetLowering::DAGCombinerInfo &DCI) {
10103   SelectionDAG &DAG = DCI.DAG;
10104   SDValue N0 = N->getOperand(0);
10105   EVT ResVT = N->getValueType(0);
10106
10107   if (N0.getOpcode() != ISD::SETCC)
10108     return SDValue();
10109
10110   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10111   // scalar SetCCResultType. We also don't expect vectors, because we assume
10112   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10113   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10114          "Scalar-SETCC feeding SELECT has unexpected result type!");
10115
10116   // If NumMaskElts == 0, the comparison is larger than select result. The
10117   // largest real NEON comparison is 64-bits per lane, which means the result is
10118   // at most 32-bits and an illegal vector. Just bail out for now.
10119   EVT SrcVT = N0.getOperand(0).getValueType();
10120
10121   // Don't try to do this optimization when the setcc itself has i1 operands.
10122   // There are no legal vectors of i1, so this would be pointless.
10123   if (SrcVT == MVT::i1)
10124     return SDValue();
10125
10126   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10127   if (!ResVT.isVector() || NumMaskElts == 0)
10128     return SDValue();
10129
10130   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10131   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10132
10133   // Also bail out if the vector CCVT isn't the same size as ResVT.
10134   // This can happen if the SETCC operand size doesn't divide the ResVT size
10135   // (e.g., f64 vs v3f32).
10136   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10137     return SDValue();
10138
10139   // Make sure we didn't create illegal types, if we're not supposed to.
10140   assert(DCI.isBeforeLegalize() ||
10141          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10142
10143   // First perform a vector comparison, where lane 0 is the one we're interested
10144   // in.
10145   SDLoc DL(N0);
10146   SDValue LHS =
10147       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10148   SDValue RHS =
10149       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10150   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10151
10152   // Now duplicate the comparison mask we want across all other lanes.
10153   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10154   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10155   Mask = DAG.getNode(ISD::BITCAST, DL,
10156                      ResVT.changeVectorElementTypeToInteger(), Mask);
10157
10158   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10159 }
10160
10161 /// Get rid of unnecessary NVCASTs (that don't change the type).
10162 static SDValue performNVCASTCombine(SDNode *N) {
10163   if (N->getValueType(0) == N->getOperand(0).getValueType())
10164     return N->getOperand(0);
10165
10166   return SDValue();
10167 }
10168
10169 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10170                                                  DAGCombinerInfo &DCI) const {
10171   SelectionDAG &DAG = DCI.DAG;
10172   switch (N->getOpcode()) {
10173   default:
10174     break;
10175   case ISD::ADD:
10176   case ISD::SUB:
10177     return performAddSubLongCombine(N, DCI, DAG);
10178   case ISD::XOR:
10179     return performXorCombine(N, DAG, DCI, Subtarget);
10180   case ISD::MUL:
10181     return performMulCombine(N, DAG, DCI, Subtarget);
10182   case ISD::SINT_TO_FP:
10183   case ISD::UINT_TO_FP:
10184     return performIntToFpCombine(N, DAG, Subtarget);
10185   case ISD::FP_TO_SINT:
10186   case ISD::FP_TO_UINT:
10187     return performFpToIntCombine(N, DAG, DCI, Subtarget);
10188   case ISD::FDIV:
10189     return performFDivCombine(N, DAG, DCI, Subtarget);
10190   case ISD::OR:
10191     return performORCombine(N, DCI, Subtarget);
10192   case ISD::SRL:
10193     return performSRLCombine(N, DCI);
10194   case ISD::INTRINSIC_WO_CHAIN:
10195     return performIntrinsicCombine(N, DCI, Subtarget);
10196   case ISD::ANY_EXTEND:
10197   case ISD::ZERO_EXTEND:
10198   case ISD::SIGN_EXTEND:
10199     return performExtendCombine(N, DCI, DAG);
10200   case ISD::BITCAST:
10201     return performBitcastCombine(N, DCI, DAG);
10202   case ISD::CONCAT_VECTORS:
10203     return performConcatVectorsCombine(N, DCI, DAG);
10204   case ISD::SELECT: {
10205     SDValue RV = performSelectCombine(N, DCI);
10206     if (!RV.getNode())
10207       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10208     return RV;
10209   }
10210   case ISD::VSELECT:
10211     return performVSelectCombine(N, DCI.DAG);
10212   case ISD::LOAD:
10213     if (performTBISimplification(N->getOperand(1), DCI, DAG))
10214       return SDValue(N, 0);
10215     break;
10216   case ISD::STORE:
10217     return performSTORECombine(N, DCI, DAG, Subtarget);
10218   case AArch64ISD::BRCOND:
10219     return performBRCONDCombine(N, DCI, DAG);
10220   case AArch64ISD::TBNZ:
10221   case AArch64ISD::TBZ:
10222     return performTBZCombine(N, DCI, DAG);
10223   case AArch64ISD::CSEL:
10224     return performCONDCombine(N, DCI, DAG, 2, 3);
10225   case AArch64ISD::DUP:
10226     return performPostLD1Combine(N, DCI, false);
10227   case AArch64ISD::NVCAST:
10228     return performNVCASTCombine(N);
10229   case ISD::INSERT_VECTOR_ELT:
10230     return performPostLD1Combine(N, DCI, true);
10231   case ISD::EXTRACT_VECTOR_ELT:
10232     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10233   case ISD::INTRINSIC_VOID:
10234   case ISD::INTRINSIC_W_CHAIN:
10235     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10236     case Intrinsic::aarch64_neon_ld2:
10237     case Intrinsic::aarch64_neon_ld3:
10238     case Intrinsic::aarch64_neon_ld4:
10239     case Intrinsic::aarch64_neon_ld1x2:
10240     case Intrinsic::aarch64_neon_ld1x3:
10241     case Intrinsic::aarch64_neon_ld1x4:
10242     case Intrinsic::aarch64_neon_ld2lane:
10243     case Intrinsic::aarch64_neon_ld3lane:
10244     case Intrinsic::aarch64_neon_ld4lane:
10245     case Intrinsic::aarch64_neon_ld2r:
10246     case Intrinsic::aarch64_neon_ld3r:
10247     case Intrinsic::aarch64_neon_ld4r:
10248     case Intrinsic::aarch64_neon_st2:
10249     case Intrinsic::aarch64_neon_st3:
10250     case Intrinsic::aarch64_neon_st4:
10251     case Intrinsic::aarch64_neon_st1x2:
10252     case Intrinsic::aarch64_neon_st1x3:
10253     case Intrinsic::aarch64_neon_st1x4:
10254     case Intrinsic::aarch64_neon_st2lane:
10255     case Intrinsic::aarch64_neon_st3lane:
10256     case Intrinsic::aarch64_neon_st4lane:
10257       return performNEONPostLDSTCombine(N, DCI, DAG);
10258     default:
10259       break;
10260     }
10261   }
10262   return SDValue();
10263 }
10264
10265 // Check if the return value is used as only a return value, as otherwise
10266 // we can't perform a tail-call. In particular, we need to check for
10267 // target ISD nodes that are returns and any other "odd" constructs
10268 // that the generic analysis code won't necessarily catch.
10269 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10270                                                SDValue &Chain) const {
10271   if (N->getNumValues() != 1)
10272     return false;
10273   if (!N->hasNUsesOfValue(1, 0))
10274     return false;
10275
10276   SDValue TCChain = Chain;
10277   SDNode *Copy = *N->use_begin();
10278   if (Copy->getOpcode() == ISD::CopyToReg) {
10279     // If the copy has a glue operand, we conservatively assume it isn't safe to
10280     // perform a tail call.
10281     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10282         MVT::Glue)
10283       return false;
10284     TCChain = Copy->getOperand(0);
10285   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10286     return false;
10287
10288   bool HasRet = false;
10289   for (SDNode *Node : Copy->uses()) {
10290     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10291       return false;
10292     HasRet = true;
10293   }
10294
10295   if (!HasRet)
10296     return false;
10297
10298   Chain = TCChain;
10299   return true;
10300 }
10301
10302 // Return whether the an instruction can potentially be optimized to a tail
10303 // call. This will cause the optimizers to attempt to move, or duplicate,
10304 // return instructions to help enable tail call optimizations for this
10305 // instruction.
10306 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
10307   return CI->isTailCall();
10308 }
10309
10310 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10311                                                    SDValue &Offset,
10312                                                    ISD::MemIndexedMode &AM,
10313                                                    bool &IsInc,
10314                                                    SelectionDAG &DAG) const {
10315   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10316     return false;
10317
10318   Base = Op->getOperand(0);
10319   // All of the indexed addressing mode instructions take a signed
10320   // 9 bit immediate offset.
10321   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10322     int64_t RHSC = RHS->getSExtValue();
10323     if (Op->getOpcode() == ISD::SUB)
10324       RHSC = -(uint64_t)RHSC;
10325     if (!isInt<9>(RHSC))
10326       return false;
10327     IsInc = (Op->getOpcode() == ISD::ADD);
10328     Offset = Op->getOperand(1);
10329     return true;
10330   }
10331   return false;
10332 }
10333
10334 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10335                                                       SDValue &Offset,
10336                                                       ISD::MemIndexedMode &AM,
10337                                                       SelectionDAG &DAG) const {
10338   EVT VT;
10339   SDValue Ptr;
10340   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10341     VT = LD->getMemoryVT();
10342     Ptr = LD->getBasePtr();
10343   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10344     VT = ST->getMemoryVT();
10345     Ptr = ST->getBasePtr();
10346   } else
10347     return false;
10348
10349   bool IsInc;
10350   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10351     return false;
10352   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10353   return true;
10354 }
10355
10356 bool AArch64TargetLowering::getPostIndexedAddressParts(
10357     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10358     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10359   EVT VT;
10360   SDValue Ptr;
10361   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10362     VT = LD->getMemoryVT();
10363     Ptr = LD->getBasePtr();
10364   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10365     VT = ST->getMemoryVT();
10366     Ptr = ST->getBasePtr();
10367   } else
10368     return false;
10369
10370   bool IsInc;
10371   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10372     return false;
10373   // Post-indexing updates the base, so it's not a valid transform
10374   // if that's not the same as the load's pointer.
10375   if (Ptr != Base)
10376     return false;
10377   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10378   return true;
10379 }
10380
10381 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10382                                   SelectionDAG &DAG) {
10383   SDLoc DL(N);
10384   SDValue Op = N->getOperand(0);
10385
10386   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10387     return;
10388
10389   Op = SDValue(
10390       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10391                          DAG.getUNDEF(MVT::i32), Op,
10392                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10393       0);
10394   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10395   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10396 }
10397
10398 static void ReplaceReductionResults(SDNode *N,
10399                                     SmallVectorImpl<SDValue> &Results,
10400                                     SelectionDAG &DAG, unsigned InterOp,
10401                                     unsigned AcrossOp) {
10402   EVT LoVT, HiVT;
10403   SDValue Lo, Hi;
10404   SDLoc dl(N);
10405   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10406   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10407   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10408   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10409   Results.push_back(SplitVal);
10410 }
10411
10412 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10413   SDLoc DL(N);
10414   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10415   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10416                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10417                                        DAG.getConstant(64, DL, MVT::i64)));
10418   return std::make_pair(Lo, Hi);
10419 }
10420
10421 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10422                                        SmallVectorImpl<SDValue> & Results,
10423                                        SelectionDAG &DAG) {
10424   assert(N->getValueType(0) == MVT::i128 &&
10425          "AtomicCmpSwap on types less than 128 should be legal");
10426   auto Desired = splitInt128(N->getOperand(2), DAG);
10427   auto New = splitInt128(N->getOperand(3), DAG);
10428   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10429                    New.first,        New.second,    N->getOperand(0)};
10430   SDNode *CmpSwap = DAG.getMachineNode(
10431       AArch64::CMP_SWAP_128, SDLoc(N),
10432       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10433
10434   MachineFunction &MF = DAG.getMachineFunction();
10435   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10436   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10437   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10438
10439   Results.push_back(SDValue(CmpSwap, 0));
10440   Results.push_back(SDValue(CmpSwap, 1));
10441   Results.push_back(SDValue(CmpSwap, 3));
10442 }
10443
10444 void AArch64TargetLowering::ReplaceNodeResults(
10445     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10446   switch (N->getOpcode()) {
10447   default:
10448     llvm_unreachable("Don't know how to custom expand this");
10449   case ISD::BITCAST:
10450     ReplaceBITCASTResults(N, Results, DAG);
10451     return;
10452   case AArch64ISD::SADDV:
10453     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10454     return;
10455   case AArch64ISD::UADDV:
10456     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10457     return;
10458   case AArch64ISD::SMINV:
10459     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10460     return;
10461   case AArch64ISD::UMINV:
10462     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10463     return;
10464   case AArch64ISD::SMAXV:
10465     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10466     return;
10467   case AArch64ISD::UMAXV:
10468     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10469     return;
10470   case ISD::FP_TO_UINT:
10471   case ISD::FP_TO_SINT:
10472     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10473     // Let normal code take care of it by not adding anything to Results.
10474     return;
10475   case ISD::ATOMIC_CMP_SWAP:
10476     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10477     return;
10478   }
10479 }
10480
10481 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10482   if (!Subtarget->isTargetAndroid())
10483     return true;
10484   return TargetLowering::useLoadStackGuardNode();
10485 }
10486
10487 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10488   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10489   // reciprocal if there are three or more FDIVs.
10490   return 3;
10491 }
10492
10493 TargetLoweringBase::LegalizeTypeAction
10494 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10495   MVT SVT = VT.getSimpleVT();
10496   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10497   // v4i16, v2i32 instead of to promote.
10498   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10499       || SVT == MVT::v1f32)
10500     return TypeWidenVector;
10501
10502   return TargetLoweringBase::getPreferredVectorAction(VT);
10503 }
10504
10505 // Loads and stores less than 128-bits are already atomic; ones above that
10506 // are doomed anyway, so defer to the default libcall and blame the OS when
10507 // things go wrong.
10508 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10509   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10510   return Size == 128;
10511 }
10512
10513 // Loads and stores less than 128-bits are already atomic; ones above that
10514 // are doomed anyway, so defer to the default libcall and blame the OS when
10515 // things go wrong.
10516 TargetLowering::AtomicExpansionKind
10517 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10518   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10519   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10520 }
10521
10522 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10523 TargetLowering::AtomicExpansionKind
10524 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10525   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10526   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10527 }
10528
10529 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10530     AtomicCmpXchgInst *AI) const {
10531   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10532   // implement cmpxchg without spilling. If the address being exchanged is also
10533   // on the stack and close enough to the spill slot, this can lead to a
10534   // situation where the monitor always gets cleared and the atomic operation
10535   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10536   return getTargetMachine().getOptLevel() != 0;
10537 }
10538
10539 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10540                                              AtomicOrdering Ord) const {
10541   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10542   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10543   bool IsAcquire = isAcquireOrStronger(Ord);
10544
10545   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10546   // intrinsic must return {i64, i64} and we have to recombine them into a
10547   // single i128 here.
10548   if (ValTy->getPrimitiveSizeInBits() == 128) {
10549     Intrinsic::ID Int =
10550         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10551     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10552
10553     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10554     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10555
10556     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10557     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10558     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10559     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10560     return Builder.CreateOr(
10561         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10562   }
10563
10564   Type *Tys[] = { Addr->getType() };
10565   Intrinsic::ID Int =
10566       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10567   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10568
10569   return Builder.CreateTruncOrBitCast(
10570       Builder.CreateCall(Ldxr, Addr),
10571       cast<PointerType>(Addr->getType())->getElementType());
10572 }
10573
10574 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10575     IRBuilder<> &Builder) const {
10576   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10577   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10578 }
10579
10580 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10581                                                    Value *Val, Value *Addr,
10582                                                    AtomicOrdering Ord) const {
10583   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10584   bool IsRelease = isReleaseOrStronger(Ord);
10585
10586   // Since the intrinsics must have legal type, the i128 intrinsics take two
10587   // parameters: "i64, i64". We must marshal Val into the appropriate form
10588   // before the call.
10589   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10590     Intrinsic::ID Int =
10591         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10592     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10593     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10594
10595     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10596     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10597     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10598     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10599   }
10600
10601   Intrinsic::ID Int =
10602       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10603   Type *Tys[] = { Addr->getType() };
10604   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10605
10606   return Builder.CreateCall(Stxr,
10607                             {Builder.CreateZExtOrBitCast(
10608                                  Val, Stxr->getFunctionType()->getParamType(0)),
10609                              Addr});
10610 }
10611
10612 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10613     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10614   return Ty->isArrayTy();
10615 }
10616
10617 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10618                                                             EVT) const {
10619   return false;
10620 }
10621
10622 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10623   if (!Subtarget->isTargetAndroid())
10624     return TargetLowering::getIRStackGuard(IRB);
10625
10626   // Android provides a fixed TLS slot for the stack cookie. See the definition
10627   // of TLS_SLOT_STACK_GUARD in
10628   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10629   const unsigned TlsOffset = 0x28;
10630   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10631   Function *ThreadPointerFunc =
10632       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10633   return IRB.CreatePointerCast(
10634       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10635       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10636 }
10637
10638 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10639   if (!Subtarget->isTargetAndroid())
10640     return TargetLowering::getSafeStackPointerLocation(IRB);
10641
10642   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10643   // definition of TLS_SLOT_SAFESTACK in
10644   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10645   const unsigned TlsOffset = 0x48;
10646   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10647   Function *ThreadPointerFunc =
10648       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10649   return IRB.CreatePointerCast(
10650       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10651       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10652 }
10653
10654 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10655   // Update IsSplitCSR in AArch64unctionInfo.
10656   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10657   AFI->setIsSplitCSR(true);
10658 }
10659
10660 void AArch64TargetLowering::insertCopiesSplitCSR(
10661     MachineBasicBlock *Entry,
10662     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10663   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10664   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10665   if (!IStart)
10666     return;
10667
10668   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10669   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10670   MachineBasicBlock::iterator MBBI = Entry->begin();
10671   for (const MCPhysReg *I = IStart; *I; ++I) {
10672     const TargetRegisterClass *RC = nullptr;
10673     if (AArch64::GPR64RegClass.contains(*I))
10674       RC = &AArch64::GPR64RegClass;
10675     else if (AArch64::FPR64RegClass.contains(*I))
10676       RC = &AArch64::FPR64RegClass;
10677     else
10678       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10679
10680     unsigned NewVR = MRI->createVirtualRegister(RC);
10681     // Create copy from CSR to a virtual register.
10682     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10683     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10684     // nounwind. If we want to generalize this later, we may need to emit
10685     // CFI pseudo-instructions.
10686     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10687                Attribute::NoUnwind) &&
10688            "Function should be nounwind in insertCopiesSplitCSR!");
10689     Entry->addLiveIn(*I);
10690     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10691         .addReg(*I);
10692
10693     // Insert the copy-back instructions right before the terminator.
10694     for (auto *Exit : Exits)
10695       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10696               TII->get(TargetOpcode::COPY), *I)
10697           .addReg(NewVR);
10698   }
10699 }
10700
10701 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10702   // Integer division on AArch64 is expensive. However, when aggressively
10703   // optimizing for code size, we prefer to use a div instruction, as it is
10704   // usually smaller than the alternative sequence.
10705   // The exception to this is vector division. Since AArch64 doesn't have vector
10706   // integer division, leaving the division as-is is a loss even in terms of
10707   // size, because it will have to be scalarized, while the alternative code
10708   // sequence can be performed in vector form.
10709   bool OptSize =
10710       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10711   return OptSize && !VT.isVector();
10712 }