1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Use.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/MC/MCRegisterInfo.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "aarch64-lower"
92 
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96 
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99                            cl::desc("Allow AArch64 SLI/SRI formation"),
100                            cl::init(false));
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120                                              const AArch64Subtarget &STI)
121     : TargetLowering(TM), Subtarget(&STI) {
122   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123   // we have to make something up. Arbitrarily, choose ZeroOrOne.
124   setBooleanContents(ZeroOrOneBooleanContent);
125   // When comparing vectors the result sets the different elements in the
126   // vector to all-one or all-zero.
127   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128 
129   // Set up the register classes.
130   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132 
133   if (Subtarget->hasFPARMv8()) {
134     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138   }
139 
140   if (Subtarget->hasNEON()) {
141     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143     // Someone set us up the NEON.
144     addDRTypeForNEON(MVT::v2f32);
145     addDRTypeForNEON(MVT::v8i8);
146     addDRTypeForNEON(MVT::v4i16);
147     addDRTypeForNEON(MVT::v2i32);
148     addDRTypeForNEON(MVT::v1i64);
149     addDRTypeForNEON(MVT::v1f64);
150     addDRTypeForNEON(MVT::v4f16);
151 
152     addQRTypeForNEON(MVT::v4f32);
153     addQRTypeForNEON(MVT::v2f64);
154     addQRTypeForNEON(MVT::v16i8);
155     addQRTypeForNEON(MVT::v8i16);
156     addQRTypeForNEON(MVT::v4i32);
157     addQRTypeForNEON(MVT::v2i64);
158     addQRTypeForNEON(MVT::v8f16);
159   }
160 
161   // Compute derived properties from the register classes
162   computeRegisterProperties(Subtarget->getRegisterInfo());
163 
164   // Provide all sorts of operation actions
165   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167   setOperationAction(ISD::SETCC, MVT::i32, Custom);
168   setOperationAction(ISD::SETCC, MVT::i64, Custom);
169   setOperationAction(ISD::SETCC, MVT::f16, Custom);
170   setOperationAction(ISD::SETCC, MVT::f32, Custom);
171   setOperationAction(ISD::SETCC, MVT::f64, Custom);
172   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
174   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
177   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
178   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180   setOperationAction(ISD::SELECT, MVT::i32, Custom);
181   setOperationAction(ISD::SELECT, MVT::i64, Custom);
182   setOperationAction(ISD::SELECT, MVT::f16, Custom);
183   setOperationAction(ISD::SELECT, MVT::f32, Custom);
184   setOperationAction(ISD::SELECT, MVT::f64, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
187   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
188   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
190   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
191   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
192 
193   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
196 
197   setOperationAction(ISD::FREM, MVT::f32, Expand);
198   setOperationAction(ISD::FREM, MVT::f64, Expand);
199   setOperationAction(ISD::FREM, MVT::f80, Expand);
200 
201   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
202 
203   // Custom lowering hooks are needed for XOR
204   // to fold it into CSINC/CSINV.
205   setOperationAction(ISD::XOR, MVT::i32, Custom);
206   setOperationAction(ISD::XOR, MVT::i64, Custom);
207 
208   // Virtually no operation on f128 is legal, but LLVM can't expand them when
209   // there's a valid register class, so we need custom operations in most cases.
210   setOperationAction(ISD::FABS, MVT::f128, Expand);
211   setOperationAction(ISD::FADD, MVT::f128, Custom);
212   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
213   setOperationAction(ISD::FCOS, MVT::f128, Expand);
214   setOperationAction(ISD::FDIV, MVT::f128, Custom);
215   setOperationAction(ISD::FMA, MVT::f128, Expand);
216   setOperationAction(ISD::FMUL, MVT::f128, Custom);
217   setOperationAction(ISD::FNEG, MVT::f128, Expand);
218   setOperationAction(ISD::FPOW, MVT::f128, Expand);
219   setOperationAction(ISD::FREM, MVT::f128, Expand);
220   setOperationAction(ISD::FRINT, MVT::f128, Expand);
221   setOperationAction(ISD::FSIN, MVT::f128, Expand);
222   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
223   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
224   setOperationAction(ISD::FSUB, MVT::f128, Custom);
225   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
226   setOperationAction(ISD::SETCC, MVT::f128, Custom);
227   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
228   setOperationAction(ISD::SELECT, MVT::f128, Custom);
229   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
230   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
231 
232   // Lowering for many of the conversions is actually specified by the non-f128
233   // type. The LowerXXX function will be trivial when f128 isn't involved.
234   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
235   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
236   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
237   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
238   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
239   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
240   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
241   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
242   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
243   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
244   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
245   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
246   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
247   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
248 
249   // Variable arguments.
250   setOperationAction(ISD::VASTART, MVT::Other, Custom);
251   setOperationAction(ISD::VAARG, MVT::Other, Custom);
252   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
253   setOperationAction(ISD::VAEND, MVT::Other, Expand);
254 
255   // Variable-sized objects.
256   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
258 
259   if (Subtarget->isTargetWindows())
260     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
261   else
262     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
263 
264   // Constant pool entries
265   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
266 
267   // BlockAddress
268   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
269 
270   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
271   setOperationAction(ISD::ADDC, MVT::i32, Custom);
272   setOperationAction(ISD::ADDE, MVT::i32, Custom);
273   setOperationAction(ISD::SUBC, MVT::i32, Custom);
274   setOperationAction(ISD::SUBE, MVT::i32, Custom);
275   setOperationAction(ISD::ADDC, MVT::i64, Custom);
276   setOperationAction(ISD::ADDE, MVT::i64, Custom);
277   setOperationAction(ISD::SUBC, MVT::i64, Custom);
278   setOperationAction(ISD::SUBE, MVT::i64, Custom);
279 
280   // AArch64 lacks both left-rotate and popcount instructions.
281   setOperationAction(ISD::ROTL, MVT::i32, Expand);
282   setOperationAction(ISD::ROTL, MVT::i64, Expand);
283   for (MVT VT : MVT::vector_valuetypes()) {
284     setOperationAction(ISD::ROTL, VT, Expand);
285     setOperationAction(ISD::ROTR, VT, Expand);
286   }
287 
288   // AArch64 doesn't have {U|S}MUL_LOHI.
289   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
290   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
291 
292   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
293   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
294 
295   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
296   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
297   for (MVT VT : MVT::vector_valuetypes()) {
298     setOperationAction(ISD::SDIVREM, VT, Expand);
299     setOperationAction(ISD::UDIVREM, VT, Expand);
300   }
301   setOperationAction(ISD::SREM, MVT::i32, Expand);
302   setOperationAction(ISD::SREM, MVT::i64, Expand);
303   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
304   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
305   setOperationAction(ISD::UREM, MVT::i32, Expand);
306   setOperationAction(ISD::UREM, MVT::i64, Expand);
307 
308   // Custom lower Add/Sub/Mul with overflow.
309   setOperationAction(ISD::SADDO, MVT::i32, Custom);
310   setOperationAction(ISD::SADDO, MVT::i64, Custom);
311   setOperationAction(ISD::UADDO, MVT::i32, Custom);
312   setOperationAction(ISD::UADDO, MVT::i64, Custom);
313   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
314   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
315   setOperationAction(ISD::USUBO, MVT::i32, Custom);
316   setOperationAction(ISD::USUBO, MVT::i64, Custom);
317   setOperationAction(ISD::SMULO, MVT::i32, Custom);
318   setOperationAction(ISD::SMULO, MVT::i64, Custom);
319   setOperationAction(ISD::UMULO, MVT::i32, Custom);
320   setOperationAction(ISD::UMULO, MVT::i64, Custom);
321 
322   setOperationAction(ISD::FSIN, MVT::f32, Expand);
323   setOperationAction(ISD::FSIN, MVT::f64, Expand);
324   setOperationAction(ISD::FCOS, MVT::f32, Expand);
325   setOperationAction(ISD::FCOS, MVT::f64, Expand);
326   setOperationAction(ISD::FPOW, MVT::f32, Expand);
327   setOperationAction(ISD::FPOW, MVT::f64, Expand);
328   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330   if (Subtarget->hasFullFP16())
331     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
332   else
333     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
334 
335   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
336   setOperationAction(ISD::FREM,    MVT::v4f16, Promote);
337   setOperationAction(ISD::FREM,    MVT::v8f16, Promote);
338   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
339   setOperationAction(ISD::FPOW,    MVT::v4f16, Promote);
340   setOperationAction(ISD::FPOW,    MVT::v8f16, Promote);
341   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
342   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
343   setOperationAction(ISD::FCOS,    MVT::v4f16, Promote);
344   setOperationAction(ISD::FCOS,    MVT::v8f16, Promote);
345   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
346   setOperationAction(ISD::FSIN,    MVT::v4f16, Promote);
347   setOperationAction(ISD::FSIN,    MVT::v8f16, Promote);
348   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
349   setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
350   setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
351   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
352   setOperationAction(ISD::FEXP,    MVT::v4f16, Promote);
353   setOperationAction(ISD::FEXP,    MVT::v8f16, Promote);
354   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
355   setOperationAction(ISD::FEXP2,   MVT::v4f16, Promote);
356   setOperationAction(ISD::FEXP2,   MVT::v8f16, Promote);
357   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
358   setOperationAction(ISD::FLOG,    MVT::v4f16, Promote);
359   setOperationAction(ISD::FLOG,    MVT::v8f16, Promote);
360   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
361   setOperationAction(ISD::FLOG2,   MVT::v4f16, Promote);
362   setOperationAction(ISD::FLOG2,   MVT::v8f16, Promote);
363   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
364   setOperationAction(ISD::FLOG10,  MVT::v4f16, Promote);
365   setOperationAction(ISD::FLOG10,  MVT::v8f16, Promote);
366 
367   if (!Subtarget->hasFullFP16()) {
368     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
369     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
370     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
371     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
372     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
373     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
374     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
375     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
376     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
377     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
378     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
379     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
380     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
381     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
382     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
383     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
384     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
385     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
386     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
387     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
388     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
389     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
390 
391     // promote v4f16 to v4f32 when that is known to be safe.
392     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
393     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
394     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
395     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
396     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
397     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
398     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
399     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
400     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
401     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
402     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
403     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
404 
405     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
406     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
407     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
408     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
409     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
410     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
411     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
412     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
413     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
414     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
415     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
416     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
417     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
418     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
419     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
420 
421     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
422     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
423     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
424     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
425     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
426     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
427     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
428     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
429     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
430     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
431     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
432     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
433     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
434     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
435     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
436     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
437     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
438     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
439     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
440     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
441   }
442 
443   // AArch64 has implementations of a lot of rounding-like FP operations.
444   for (MVT Ty : {MVT::f32, MVT::f64}) {
445     setOperationAction(ISD::FFLOOR, Ty, Legal);
446     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
447     setOperationAction(ISD::FCEIL, Ty, Legal);
448     setOperationAction(ISD::FRINT, Ty, Legal);
449     setOperationAction(ISD::FTRUNC, Ty, Legal);
450     setOperationAction(ISD::FROUND, Ty, Legal);
451     setOperationAction(ISD::FMINNUM, Ty, Legal);
452     setOperationAction(ISD::FMAXNUM, Ty, Legal);
453     setOperationAction(ISD::FMINIMUM, Ty, Legal);
454     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
455   }
456 
457   if (Subtarget->hasFullFP16()) {
458     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
459     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
460     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
461     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
462     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
463     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
464     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
465     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
466     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
467     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
468   }
469 
470   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
471 
472   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
473 
474   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
475   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
476   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
477   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
478   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
479 
480   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481   // This requires the Performance Monitors extension.
482   if (Subtarget->hasPerfMon())
483     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
484 
485   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487     // Issue __sincos_stret if available.
488     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
489     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
490   } else {
491     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
492     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
493   }
494 
495   // Make floating-point constants legal for the large code model, so they don't
496   // become loads from the constant pool.
497   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
498     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
499     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
500   }
501 
502   // AArch64 does not have floating-point extending loads, i1 sign-extending
503   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
504   for (MVT VT : MVT::fp_valuetypes()) {
505     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
506     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
507     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
508     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
509   }
510   for (MVT VT : MVT::integer_valuetypes())
511     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
512 
513   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
514   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
515   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
516   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
517   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
518   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
519   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
520 
521   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523 
524   // Indexed loads and stores are supported.
525   for (unsigned im = (unsigned)ISD::PRE_INC;
526        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
527     setIndexedLoadAction(im, MVT::i8, Legal);
528     setIndexedLoadAction(im, MVT::i16, Legal);
529     setIndexedLoadAction(im, MVT::i32, Legal);
530     setIndexedLoadAction(im, MVT::i64, Legal);
531     setIndexedLoadAction(im, MVT::f64, Legal);
532     setIndexedLoadAction(im, MVT::f32, Legal);
533     setIndexedLoadAction(im, MVT::f16, Legal);
534     setIndexedStoreAction(im, MVT::i8, Legal);
535     setIndexedStoreAction(im, MVT::i16, Legal);
536     setIndexedStoreAction(im, MVT::i32, Legal);
537     setIndexedStoreAction(im, MVT::i64, Legal);
538     setIndexedStoreAction(im, MVT::f64, Legal);
539     setIndexedStoreAction(im, MVT::f32, Legal);
540     setIndexedStoreAction(im, MVT::f16, Legal);
541   }
542 
543   // Trap.
544   setOperationAction(ISD::TRAP, MVT::Other, Legal);
545 
546   // We combine OR nodes for bitfield operations.
547   setTargetDAGCombine(ISD::OR);
548 
549   // Vector add and sub nodes may conceal a high-half opportunity.
550   // Also, try to fold ADD into CSINC/CSINV..
551   setTargetDAGCombine(ISD::ADD);
552   setTargetDAGCombine(ISD::SUB);
553   setTargetDAGCombine(ISD::SRL);
554   setTargetDAGCombine(ISD::XOR);
555   setTargetDAGCombine(ISD::SINT_TO_FP);
556   setTargetDAGCombine(ISD::UINT_TO_FP);
557 
558   setTargetDAGCombine(ISD::FP_TO_SINT);
559   setTargetDAGCombine(ISD::FP_TO_UINT);
560   setTargetDAGCombine(ISD::FDIV);
561 
562   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563 
564   setTargetDAGCombine(ISD::ANY_EXTEND);
565   setTargetDAGCombine(ISD::ZERO_EXTEND);
566   setTargetDAGCombine(ISD::SIGN_EXTEND);
567   setTargetDAGCombine(ISD::BITCAST);
568   setTargetDAGCombine(ISD::CONCAT_VECTORS);
569   setTargetDAGCombine(ISD::STORE);
570   if (Subtarget->supportsAddressTopByteIgnored())
571     setTargetDAGCombine(ISD::LOAD);
572 
573   setTargetDAGCombine(ISD::MUL);
574 
575   setTargetDAGCombine(ISD::SELECT);
576   setTargetDAGCombine(ISD::VSELECT);
577 
578   setTargetDAGCombine(ISD::INTRINSIC_VOID);
579   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
581 
582   setTargetDAGCombine(ISD::GlobalAddress);
583 
584   // In case of strict alignment, avoid an excessive number of byte wide stores.
585   MaxStoresPerMemsetOptSize = 8;
586   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
587                        ? MaxStoresPerMemsetOptSize : 32;
588 
589   MaxGluedStoresPerMemcpy = 4;
590   MaxStoresPerMemcpyOptSize = 4;
591   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
592                        ? MaxStoresPerMemcpyOptSize : 16;
593 
594   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
595 
596   setStackPointerRegisterToSaveRestore(AArch64::SP);
597 
598   setSchedulingPreference(Sched::Hybrid);
599 
600   EnableExtLdPromotion = true;
601 
602   // Set required alignment.
603   setMinFunctionAlignment(2);
604   // Set preferred alignments.
605   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
606   setPrefLoopAlignment(STI.getPrefLoopAlignment());
607 
608   // Only change the limit for entries in a jump table if specified by
609   // the subtarget, but not at the command line.
610   unsigned MaxJT = STI.getMaximumJumpTableSize();
611   if (MaxJT && getMaximumJumpTableSize() == 0)
612     setMaximumJumpTableSize(MaxJT);
613 
614   setHasExtractBitsInsn(true);
615 
616   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
617 
618   if (Subtarget->hasNEON()) {
619     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620     // silliness like this:
621     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
622     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
623     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
624     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
625     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
626     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
627     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
628     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
629     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
630     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
631     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
632     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
633     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
634     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
635     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
636     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
637     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
638     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
639     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
641     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
642     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
643     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
644     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
645     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
646 
647     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
648     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
649     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
650     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
651     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
652 
653     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
654 
655     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656     // elements smaller than i32, so promote the input to i32 first.
657     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
658     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
659     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
660     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
661     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662     // -> v8f16 conversions.
663     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
664     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
665     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
666     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
667     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
668     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
669     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
670     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
671     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
672     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
673     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
674     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
675     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
676 
677     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
678     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
679 
680     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
681     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
682     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
683     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
684     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
685     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
686     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
687     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
688 
689     // AArch64 doesn't have MUL.2d:
690     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
691     // Custom handling for some quad-vector types to detect MULL.
692     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
693     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
694     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
695 
696     // Vector reductions
697     for (MVT VT : MVT::integer_valuetypes()) {
698       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
699       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
700       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
701       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
702       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
703     }
704     for (MVT VT : MVT::fp_valuetypes()) {
705       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
706       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
707     }
708 
709     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
710     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
711     // Likewise, narrowing and extending vector loads/stores aren't handled
712     // directly.
713     for (MVT VT : MVT::vector_valuetypes()) {
714       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
715 
716       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
717         setOperationAction(ISD::MULHS, VT, Legal);
718         setOperationAction(ISD::MULHU, VT, Legal);
719       } else {
720         setOperationAction(ISD::MULHS, VT, Expand);
721         setOperationAction(ISD::MULHU, VT, Expand);
722       }
723       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
724       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
725 
726       setOperationAction(ISD::BSWAP, VT, Expand);
727 
728       for (MVT InnerVT : MVT::vector_valuetypes()) {
729         setTruncStoreAction(VT, InnerVT, Expand);
730         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733       }
734     }
735 
736     // AArch64 has implementations of a lot of rounding-like FP operations.
737     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
738       setOperationAction(ISD::FFLOOR, Ty, Legal);
739       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
740       setOperationAction(ISD::FCEIL, Ty, Legal);
741       setOperationAction(ISD::FRINT, Ty, Legal);
742       setOperationAction(ISD::FTRUNC, Ty, Legal);
743       setOperationAction(ISD::FROUND, Ty, Legal);
744     }
745 
746     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
747   }
748 
749   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
750 }
751 
752 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
753   assert(VT.isVector() && "VT should be a vector type");
754 
755   if (VT.isFloatingPoint()) {
756     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
757     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
759   }
760 
761   // Mark vector float intrinsics as expand.
762   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
763     setOperationAction(ISD::FSIN, VT, Expand);
764     setOperationAction(ISD::FCOS, VT, Expand);
765     setOperationAction(ISD::FPOW, VT, Expand);
766     setOperationAction(ISD::FLOG, VT, Expand);
767     setOperationAction(ISD::FLOG2, VT, Expand);
768     setOperationAction(ISD::FLOG10, VT, Expand);
769     setOperationAction(ISD::FEXP, VT, Expand);
770     setOperationAction(ISD::FEXP2, VT, Expand);
771 
772     // But we do support custom-lowering for FCOPYSIGN.
773     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
774   }
775 
776   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
777   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
778   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
779   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
780   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
781   setOperationAction(ISD::SRA, VT, Custom);
782   setOperationAction(ISD::SRL, VT, Custom);
783   setOperationAction(ISD::SHL, VT, Custom);
784   setOperationAction(ISD::AND, VT, Custom);
785   setOperationAction(ISD::OR, VT, Custom);
786   setOperationAction(ISD::SETCC, VT, Custom);
787   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
788 
789   setOperationAction(ISD::SELECT, VT, Expand);
790   setOperationAction(ISD::SELECT_CC, VT, Expand);
791   setOperationAction(ISD::VSELECT, VT, Expand);
792   for (MVT InnerVT : MVT::all_valuetypes())
793     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
794 
795   // CNT supports only B element sizes, then use UADDLP to widen.
796   if (VT != MVT::v8i8 && VT != MVT::v16i8)
797     setOperationAction(ISD::CTPOP, VT, Custom);
798 
799   setOperationAction(ISD::UDIV, VT, Expand);
800   setOperationAction(ISD::SDIV, VT, Expand);
801   setOperationAction(ISD::UREM, VT, Expand);
802   setOperationAction(ISD::SREM, VT, Expand);
803   setOperationAction(ISD::FREM, VT, Expand);
804 
805   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
806   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
807 
808   if (!VT.isFloatingPoint())
809     setOperationAction(ISD::ABS, VT, Legal);
810 
811   // [SU][MIN|MAX] are available for all NEON types apart from i64.
812   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
813     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
814       setOperationAction(Opcode, VT, Legal);
815 
816   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817   if (VT.isFloatingPoint() &&
818       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
819     for (unsigned Opcode :
820          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
821       setOperationAction(Opcode, VT, Legal);
822 
823   if (Subtarget->isLittleEndian()) {
824     for (unsigned im = (unsigned)ISD::PRE_INC;
825          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
826       setIndexedLoadAction(im, VT, Legal);
827       setIndexedStoreAction(im, VT, Legal);
828     }
829   }
830 }
831 
832 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833   addRegisterClass(VT, &AArch64::FPR64RegClass);
834   addTypeForNEON(VT, MVT::v2i32);
835 }
836 
837 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838   addRegisterClass(VT, &AArch64::FPR128RegClass);
839   addTypeForNEON(VT, MVT::v4i32);
840 }
841 
842 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
843                                               EVT VT) const {
844   if (!VT.isVector())
845     return MVT::i32;
846   return VT.changeVectorElementTypeToInteger();
847 }
848 
849 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850                                const APInt &Demanded,
851                                TargetLowering::TargetLoweringOpt &TLO,
852                                unsigned NewOpc) {
853   uint64_t OldImm = Imm, NewImm, Enc;
854   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855 
856   // Return if the immediate is already all zeros, all ones, a bimm32 or a
857   // bimm64.
858   if (Imm == 0 || Imm == Mask ||
859       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860     return false;
861 
862   unsigned EltSize = Size;
863   uint64_t DemandedBits = Demanded.getZExtValue();
864 
865   // Clear bits that are not demanded.
866   Imm &= DemandedBits;
867 
868   while (true) {
869     // The goal here is to set the non-demanded bits in a way that minimizes
870     // the number of switching between 0 and 1. In order to achieve this goal,
871     // we set the non-demanded bits to the value of the preceding demanded bits.
872     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875     // The final result is 0b11000011.
876     uint64_t NonDemandedBits = ~DemandedBits;
877     uint64_t InvertedImm = ~Imm & DemandedBits;
878     uint64_t RotatedImm =
879         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880         NonDemandedBits;
881     uint64_t Sum = RotatedImm + NonDemandedBits;
882     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884     NewImm = (Imm | Ones) & Mask;
885 
886     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888     // we halve the element size and continue the search.
889     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890       break;
891 
892     // We cannot shrink the element size any further if it is 2-bits.
893     if (EltSize == 2)
894       return false;
895 
896     EltSize /= 2;
897     Mask >>= EltSize;
898     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899 
900     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902       return false;
903 
904     // Merge the upper and lower halves of Imm and DemandedBits.
905     Imm |= Hi;
906     DemandedBits |= DemandedBitsHi;
907   }
908 
909   ++NumOptimizedImms;
910 
911   // Replicate the element across the register width.
912   while (EltSize < Size) {
913     NewImm |= NewImm << EltSize;
914     EltSize *= 2;
915   }
916 
917   (void)OldImm;
918   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919          "demanded bits should never be altered");
920   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921 
922   // Create the new constant immediate node.
923   EVT VT = Op.getValueType();
924   SDLoc DL(Op);
925   SDValue New;
926 
927   // If the new constant immediate is all-zeros or all-ones, let the target
928   // independent DAG combine optimize this node.
929   if (NewImm == 0 || NewImm == OrigMask) {
930     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931                           TLO.DAG.getConstant(NewImm, DL, VT));
932   // Otherwise, create a machine node so that target independent DAG combine
933   // doesn't undo this optimization.
934   } else {
935     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937     New = SDValue(
938         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939   }
940 
941   return TLO.CombineTo(Op, New);
942 }
943 
944 bool AArch64TargetLowering::targetShrinkDemandedConstant(
945     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946   // Delay this optimization to as late as possible.
947   if (!TLO.LegalOps)
948     return false;
949 
950   if (!EnableOptimizeLogicalImm)
951     return false;
952 
953   EVT VT = Op.getValueType();
954   if (VT.isVector())
955     return false;
956 
957   unsigned Size = VT.getSizeInBits();
958   assert((Size == 32 || Size == 64) &&
959          "i32 or i64 is expected after legalization.");
960 
961   // Exit early if we demand all bits.
962   if (Demanded.countPopulation() == Size)
963     return false;
964 
965   unsigned NewOpc;
966   switch (Op.getOpcode()) {
967   default:
968     return false;
969   case ISD::AND:
970     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971     break;
972   case ISD::OR:
973     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974     break;
975   case ISD::XOR:
976     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977     break;
978   }
979   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
980   if (!C)
981     return false;
982   uint64_t Imm = C->getZExtValue();
983   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984 }
985 
986 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
987 /// Mask are known to be either zero or one and return them Known.
988 void AArch64TargetLowering::computeKnownBitsForTargetNode(
989     const SDValue Op, KnownBits &Known,
990     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
991   switch (Op.getOpcode()) {
992   default:
993     break;
994   case AArch64ISD::CSEL: {
995     KnownBits Known2;
996     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
997     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
998     Known.Zero &= Known2.Zero;
999     Known.One &= Known2.One;
1000     break;
1001   }
1002   case ISD::INTRINSIC_W_CHAIN: {
1003     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1004     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005     switch (IntID) {
1006     default: return;
1007     case Intrinsic::aarch64_ldaxr:
1008     case Intrinsic::aarch64_ldxr: {
1009       unsigned BitWidth = Known.getBitWidth();
1010       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1011       unsigned MemBits = VT.getScalarSizeInBits();
1012       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1013       return;
1014     }
1015     }
1016     break;
1017   }
1018   case ISD::INTRINSIC_WO_CHAIN:
1019   case ISD::INTRINSIC_VOID: {
1020     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021     switch (IntNo) {
1022     default:
1023       break;
1024     case Intrinsic::aarch64_neon_umaxv:
1025     case Intrinsic::aarch64_neon_uminv: {
1026       // Figure out the datatype of the vector operand. The UMINV instruction
1027       // will zero extend the result, so we can mark as known zero all the
1028       // bits larger than the element datatype. 32-bit or larget doesn't need
1029       // this as those are legal types and will be handled by isel directly.
1030       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1031       unsigned BitWidth = Known.getBitWidth();
1032       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033         assert(BitWidth >= 8 && "Unexpected width!");
1034         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1035         Known.Zero |= Mask;
1036       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037         assert(BitWidth >= 16 && "Unexpected width!");
1038         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1039         Known.Zero |= Mask;
1040       }
1041       break;
1042     } break;
1043     }
1044   }
1045   }
1046 }
1047 
1048 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1049                                                   EVT) const {
1050   return MVT::i64;
1051 }
1052 
1053 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1054                                                            unsigned AddrSpace,
1055                                                            unsigned Align,
1056                                                            bool *Fast) const {
1057   if (Subtarget->requiresStrictAlign())
1058     return false;
1059 
1060   if (Fast) {
1061     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1063             // See comments in performSTORECombine() for more details about
1064             // these conditions.
1065 
1066             // Code that uses clang vector extensions can mark that it
1067             // wants unaligned accesses to be treated as fast by
1068             // underspecifying alignment to be 1 or 2.
1069             Align <= 2 ||
1070 
1071             // Disregard v2i64. Memcpy lowering produces those and splitting
1072             // them regresses performance on micro-benchmarks and olden/bh.
1073             VT == MVT::v2i64;
1074   }
1075   return true;
1076 }
1077 
1078 FastISel *
1079 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1080                                       const TargetLibraryInfo *libInfo) const {
1081   return AArch64::createFastISel(funcInfo, libInfo);
1082 }
1083 
1084 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1085   switch ((AArch64ISD::NodeType)Opcode) {
1086   case AArch64ISD::FIRST_NUMBER:      break;
1087   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1088   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1089   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1090   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1091   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1092   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1093   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1094   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1095   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1096   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1097   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1098   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1099   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1100   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1101   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1102   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1103   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1104   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1105   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1106   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1107   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1108   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1109   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1110   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1111   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1112   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1113   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1114   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1115   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1116   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1117   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1118   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1119   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1120   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1121   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1122   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1123   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1124   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1125   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1126   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1127   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1128   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1129   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1130   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1131   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1132   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1133   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1134   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1135   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1136   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1137   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1138   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1139   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1140   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1141   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1142   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1143   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1144   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1145   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1146   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1147   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1148   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1149   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1150   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1151   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1152   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1153   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1154   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1155   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1156   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1157   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1158   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1159   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1160   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1161   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1162   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1163   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1164   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1165   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1166   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1167   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1168   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1169   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1170   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1171   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1172   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1173   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1174   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1175   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1176   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1177   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1178   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1179   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1180   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1181   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1182   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1183   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1184   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1185   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1186   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1187   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1188   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1189   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1190   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1191   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1192   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1193   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1194   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1195   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1196   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1197   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1198   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1199   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1200   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1201   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1202   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1203   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1204   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1205   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1206   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1207   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1208   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1209   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1210   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1211   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1212   }
1213   return nullptr;
1214 }
1215 
1216 MachineBasicBlock *
1217 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1218                                     MachineBasicBlock *MBB) const {
1219   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220   // phi node:
1221 
1222   // OrigBB:
1223   //     [... previous instrs leading to comparison ...]
1224   //     b.ne TrueBB
1225   //     b EndBB
1226   // TrueBB:
1227   //     ; Fallthrough
1228   // EndBB:
1229   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230 
1231   MachineFunction *MF = MBB->getParent();
1232   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1233   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1234   DebugLoc DL = MI.getDebugLoc();
1235   MachineFunction::iterator It = ++MBB->getIterator();
1236 
1237   unsigned DestReg = MI.getOperand(0).getReg();
1238   unsigned IfTrueReg = MI.getOperand(1).getReg();
1239   unsigned IfFalseReg = MI.getOperand(2).getReg();
1240   unsigned CondCode = MI.getOperand(3).getImm();
1241   bool NZCVKilled = MI.getOperand(4).isKill();
1242 
1243   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245   MF->insert(It, TrueBB);
1246   MF->insert(It, EndBB);
1247 
1248   // Transfer rest of current basic-block to EndBB
1249   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250                 MBB->end());
1251   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252 
1253   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255   MBB->addSuccessor(TrueBB);
1256   MBB->addSuccessor(EndBB);
1257 
1258   // TrueBB falls through to the end.
1259   TrueBB->addSuccessor(EndBB);
1260 
1261   if (!NZCVKilled) {
1262     TrueBB->addLiveIn(AArch64::NZCV);
1263     EndBB->addLiveIn(AArch64::NZCV);
1264   }
1265 
1266   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267       .addReg(IfTrueReg)
1268       .addMBB(TrueBB)
1269       .addReg(IfFalseReg)
1270       .addMBB(MBB);
1271 
1272   MI.eraseFromParent();
1273   return EndBB;
1274 }
1275 
1276 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1277        MachineInstr &MI, MachineBasicBlock *BB) const {
1278   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1279              BB->getParent()->getFunction().getPersonalityFn())) &&
1280          "SEH does not use catchret!");
1281   return BB;
1282 }
1283 
1284 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1285      MachineInstr &MI, MachineBasicBlock *BB) const {
1286   MI.eraseFromParent();
1287   return BB;
1288 }
1289 
1290 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1291     MachineInstr &MI, MachineBasicBlock *BB) const {
1292   switch (MI.getOpcode()) {
1293   default:
1294 #ifndef NDEBUG
1295     MI.dump();
1296 #endif
1297     llvm_unreachable("Unexpected instruction for custom inserter!");
1298 
1299   case AArch64::F128CSEL:
1300     return EmitF128CSEL(MI, BB);
1301 
1302   case TargetOpcode::STACKMAP:
1303   case TargetOpcode::PATCHPOINT:
1304     return emitPatchPoint(MI, BB);
1305 
1306   case AArch64::CATCHRET:
1307     return EmitLoweredCatchRet(MI, BB);
1308   case AArch64::CATCHPAD:
1309     return EmitLoweredCatchPad(MI, BB);
1310   }
1311 }
1312 
1313 //===----------------------------------------------------------------------===//
1314 // AArch64 Lowering private implementation.
1315 //===----------------------------------------------------------------------===//
1316 
1317 //===----------------------------------------------------------------------===//
1318 // Lowering Code
1319 //===----------------------------------------------------------------------===//
1320 
1321 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1322 /// CC
1323 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1324   switch (CC) {
1325   default:
1326     llvm_unreachable("Unknown condition code!");
1327   case ISD::SETNE:
1328     return AArch64CC::NE;
1329   case ISD::SETEQ:
1330     return AArch64CC::EQ;
1331   case ISD::SETGT:
1332     return AArch64CC::GT;
1333   case ISD::SETGE:
1334     return AArch64CC::GE;
1335   case ISD::SETLT:
1336     return AArch64CC::LT;
1337   case ISD::SETLE:
1338     return AArch64CC::LE;
1339   case ISD::SETUGT:
1340     return AArch64CC::HI;
1341   case ISD::SETUGE:
1342     return AArch64CC::HS;
1343   case ISD::SETULT:
1344     return AArch64CC::LO;
1345   case ISD::SETULE:
1346     return AArch64CC::LS;
1347   }
1348 }
1349 
1350 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1351 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1352                                   AArch64CC::CondCode &CondCode,
1353                                   AArch64CC::CondCode &CondCode2) {
1354   CondCode2 = AArch64CC::AL;
1355   switch (CC) {
1356   default:
1357     llvm_unreachable("Unknown FP condition!");
1358   case ISD::SETEQ:
1359   case ISD::SETOEQ:
1360     CondCode = AArch64CC::EQ;
1361     break;
1362   case ISD::SETGT:
1363   case ISD::SETOGT:
1364     CondCode = AArch64CC::GT;
1365     break;
1366   case ISD::SETGE:
1367   case ISD::SETOGE:
1368     CondCode = AArch64CC::GE;
1369     break;
1370   case ISD::SETOLT:
1371     CondCode = AArch64CC::MI;
1372     break;
1373   case ISD::SETOLE:
1374     CondCode = AArch64CC::LS;
1375     break;
1376   case ISD::SETONE:
1377     CondCode = AArch64CC::MI;
1378     CondCode2 = AArch64CC::GT;
1379     break;
1380   case ISD::SETO:
1381     CondCode = AArch64CC::VC;
1382     break;
1383   case ISD::SETUO:
1384     CondCode = AArch64CC::VS;
1385     break;
1386   case ISD::SETUEQ:
1387     CondCode = AArch64CC::EQ;
1388     CondCode2 = AArch64CC::VS;
1389     break;
1390   case ISD::SETUGT:
1391     CondCode = AArch64CC::HI;
1392     break;
1393   case ISD::SETUGE:
1394     CondCode = AArch64CC::PL;
1395     break;
1396   case ISD::SETLT:
1397   case ISD::SETULT:
1398     CondCode = AArch64CC::LT;
1399     break;
1400   case ISD::SETLE:
1401   case ISD::SETULE:
1402     CondCode = AArch64CC::LE;
1403     break;
1404   case ISD::SETNE:
1405   case ISD::SETUNE:
1406     CondCode = AArch64CC::NE;
1407     break;
1408   }
1409 }
1410 
1411 /// Convert a DAG fp condition code to an AArch64 CC.
1412 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1413 /// should be AND'ed instead of OR'ed.
1414 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1415                                      AArch64CC::CondCode &CondCode,
1416                                      AArch64CC::CondCode &CondCode2) {
1417   CondCode2 = AArch64CC::AL;
1418   switch (CC) {
1419   default:
1420     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1421     assert(CondCode2 == AArch64CC::AL);
1422     break;
1423   case ISD::SETONE:
1424     // (a one b)
1425     // == ((a olt b) || (a ogt b))
1426     // == ((a ord b) && (a une b))
1427     CondCode = AArch64CC::VC;
1428     CondCode2 = AArch64CC::NE;
1429     break;
1430   case ISD::SETUEQ:
1431     // (a ueq b)
1432     // == ((a uno b) || (a oeq b))
1433     // == ((a ule b) && (a uge b))
1434     CondCode = AArch64CC::PL;
1435     CondCode2 = AArch64CC::LE;
1436     break;
1437   }
1438 }
1439 
1440 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1441 /// CC usable with the vector instructions. Fewer operations are available
1442 /// without a real NZCV register, so we have to use less efficient combinations
1443 /// to get the same effect.
1444 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1445                                         AArch64CC::CondCode &CondCode,
1446                                         AArch64CC::CondCode &CondCode2,
1447                                         bool &Invert) {
1448   Invert = false;
1449   switch (CC) {
1450   default:
1451     // Mostly the scalar mappings work fine.
1452     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1453     break;
1454   case ISD::SETUO:
1455     Invert = true;
1456     LLVM_FALLTHROUGH;
1457   case ISD::SETO:
1458     CondCode = AArch64CC::MI;
1459     CondCode2 = AArch64CC::GE;
1460     break;
1461   case ISD::SETUEQ:
1462   case ISD::SETULT:
1463   case ISD::SETULE:
1464   case ISD::SETUGT:
1465   case ISD::SETUGE:
1466     // All of the compare-mask comparisons are ordered, but we can switch
1467     // between the two by a double inversion. E.g. ULE == !OGT.
1468     Invert = true;
1469     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1470     break;
1471   }
1472 }
1473 
1474 static bool isLegalArithImmed(uint64_t C) {
1475   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1476   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1477   LLVM_DEBUG(dbgs() << "Is imm " << C
1478                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1479   return IsLegal;
1480 }
1481 
1482 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1483 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1484 // can be set differently by this operation. It comes down to whether
1485 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1486 // everything is fine. If not then the optimization is wrong. Thus general
1487 // comparisons are only valid if op2 != 0.
1488 //
1489 // So, finally, the only LLVM-native comparisons that don't mention C and V
1490 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1491 // the absence of information about op2.
1492 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1493   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1494          (CC == ISD::SETEQ || CC == ISD::SETNE);
1495 }
1496 
1497 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1498                               const SDLoc &dl, SelectionDAG &DAG) {
1499   EVT VT = LHS.getValueType();
1500   const bool FullFP16 =
1501     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1502 
1503   if (VT.isFloatingPoint()) {
1504     assert(VT != MVT::f128);
1505     if (VT == MVT::f16 && !FullFP16) {
1506       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1507       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1508       VT = MVT::f32;
1509     }
1510     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1511   }
1512 
1513   // The CMP instruction is just an alias for SUBS, and representing it as
1514   // SUBS means that it's possible to get CSE with subtract operations.
1515   // A later phase can perform the optimization of setting the destination
1516   // register to WZR/XZR if it ends up being unused.
1517   unsigned Opcode = AArch64ISD::SUBS;
1518 
1519   if (isCMN(RHS, CC)) {
1520     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1521     Opcode = AArch64ISD::ADDS;
1522     RHS = RHS.getOperand(1);
1523   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1524              !isUnsignedIntSetCC(CC)) {
1525     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1526     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1527     // of the signed comparisons.
1528     Opcode = AArch64ISD::ANDS;
1529     RHS = LHS.getOperand(1);
1530     LHS = LHS.getOperand(0);
1531   }
1532 
1533   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1534       .getValue(1);
1535 }
1536 
1537 /// \defgroup AArch64CCMP CMP;CCMP matching
1538 ///
1539 /// These functions deal with the formation of CMP;CCMP;... sequences.
1540 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1541 /// a comparison. They set the NZCV flags to a predefined value if their
1542 /// predicate is false. This allows to express arbitrary conjunctions, for
1543 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1544 /// expressed as:
1545 ///   cmp A
1546 ///   ccmp B, inv(CB), CA
1547 ///   check for CB flags
1548 ///
1549 /// In general we can create code for arbitrary "... (and (and A B) C)"
1550 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1551 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1552 /// negation operations:
1553 /// We can negate the results of a single comparison by inverting the flags
1554 /// used when the predicate fails and inverting the flags tested in the next
1555 /// instruction; We can also negate the results of the whole previous
1556 /// conditional compare sequence by inverting the flags tested in the next
1557 /// instruction. However there is no way to negate the result of a partial
1558 /// sequence.
1559 ///
1560 /// Therefore on encountering an "or" expression we can negate the subtree on
1561 /// one side and have to be able to push the negate to the leafs of the subtree
1562 /// on the other side (see also the comments in code). As complete example:
1563 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1564 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1565 /// is transformed to
1566 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1567 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1568 /// and implemented as:
1569 ///   cmp C
1570 ///   ccmp D, inv(CD), CC
1571 ///   ccmp A, CA, inv(CD)
1572 ///   ccmp B, CB, inv(CA)
1573 ///   check for CB flags
1574 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1575 /// by conditional compare sequences.
1576 /// @{
1577 
1578 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1579 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1580                                          ISD::CondCode CC, SDValue CCOp,
1581                                          AArch64CC::CondCode Predicate,
1582                                          AArch64CC::CondCode OutCC,
1583                                          const SDLoc &DL, SelectionDAG &DAG) {
1584   unsigned Opcode = 0;
1585   const bool FullFP16 =
1586     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1587 
1588   if (LHS.getValueType().isFloatingPoint()) {
1589     assert(LHS.getValueType() != MVT::f128);
1590     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1591       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1592       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1593     }
1594     Opcode = AArch64ISD::FCCMP;
1595   } else if (RHS.getOpcode() == ISD::SUB) {
1596     SDValue SubOp0 = RHS.getOperand(0);
1597     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1598       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1599       Opcode = AArch64ISD::CCMN;
1600       RHS = RHS.getOperand(1);
1601     }
1602   }
1603   if (Opcode == 0)
1604     Opcode = AArch64ISD::CCMP;
1605 
1606   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1607   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1608   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1609   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1610   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1611 }
1612 
1613 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1614 /// expressed as a conjunction. See \ref AArch64CCMP.
1615 /// \param CanNegate        Set to true if we can also emit the negation of the
1616 ///                         tree as a conjunction.
1617 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1618                                unsigned Depth = 0) {
1619   if (!Val.hasOneUse())
1620     return false;
1621   unsigned Opcode = Val->getOpcode();
1622   if (Opcode == ISD::SETCC) {
1623     if (Val->getOperand(0).getValueType() == MVT::f128)
1624       return false;
1625     CanNegate = true;
1626     return true;
1627   }
1628   // Protect against exponential runtime and stack overflow.
1629   if (Depth > 6)
1630     return false;
1631   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1632     SDValue O0 = Val->getOperand(0);
1633     SDValue O1 = Val->getOperand(1);
1634     bool CanNegateL;
1635     if (!canEmitConjunction(O0, CanNegateL, Depth+1))
1636       return false;
1637     bool CanNegateR;
1638     if (!canEmitConjunction(O1, CanNegateR, Depth+1))
1639       return false;
1640 
1641     if (Opcode == ISD::OR) {
1642       // For an OR expression we need to be able to negate at least one side or
1643       // we cannot do the transformation at all.
1644       if (!CanNegateL && !CanNegateR)
1645         return false;
1646       // However if we can negate x and y, then we can change
1647       // (not (or x y))
1648       // into
1649       // (and (not x) (not y))
1650       // to eliminate the outer negation.
1651       CanNegate = CanNegateL && CanNegateR;
1652     } else {
1653       // If the operands are OR expressions then we finally need to negate their
1654       // outputs, we can only do that for the operand with emitted last by
1655       // negating OutCC, not for both operands.
1656       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1657       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1658       if (NeedsNegOutL && NeedsNegOutR)
1659         return false;
1660       // We cannot negate an AND operation.
1661       CanNegate = false;
1662     }
1663     return true;
1664   }
1665   return false;
1666 }
1667 
1668 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1669 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1670 /// Tries to transform the given i1 producing node @p Val to a series compare
1671 /// and conditional compare operations. @returns an NZCV flags producing node
1672 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1673 /// transformation was not possible.
1674 /// On recursive invocations @p PushNegate may be set to true to have negation
1675 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1676 /// for the comparisons in the current subtree; @p Depth limits the search
1677 /// depth to avoid stack overflow.
1678 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1679     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1680     AArch64CC::CondCode Predicate) {
1681   // We're at a tree leaf, produce a conditional comparison operation.
1682   unsigned Opcode = Val->getOpcode();
1683   if (Opcode == ISD::SETCC) {
1684     SDValue LHS = Val->getOperand(0);
1685     SDValue RHS = Val->getOperand(1);
1686     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1687     bool isInteger = LHS.getValueType().isInteger();
1688     if (Negate)
1689       CC = getSetCCInverse(CC, isInteger);
1690     SDLoc DL(Val);
1691     // Determine OutCC and handle FP special case.
1692     if (isInteger) {
1693       OutCC = changeIntCCToAArch64CC(CC);
1694     } else {
1695       assert(LHS.getValueType().isFloatingPoint());
1696       AArch64CC::CondCode ExtraCC;
1697       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1698       // Some floating point conditions can't be tested with a single condition
1699       // code. Construct an additional comparison in this case.
1700       if (ExtraCC != AArch64CC::AL) {
1701         SDValue ExtraCmp;
1702         if (!CCOp.getNode())
1703           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1704         else
1705           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1706                                                ExtraCC, DL, DAG);
1707         CCOp = ExtraCmp;
1708         Predicate = ExtraCC;
1709       }
1710     }
1711 
1712     // Produce a normal comparison if we are first in the chain
1713     if (!CCOp)
1714       return emitComparison(LHS, RHS, CC, DL, DAG);
1715     // Otherwise produce a ccmp.
1716     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1717                                      DAG);
1718   }
1719   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1720          "Valid conjunction/disjunction tree");
1721 
1722   // Check if both sides can be transformed.
1723   SDValue LHS = Val->getOperand(0);
1724   SDValue RHS = Val->getOperand(1);
1725 
1726   // In case of an OR we need to negate our operands and the result.
1727   // (A v B) <=> not(not(A) ^ not(B))
1728   bool NegateOpsAndResult = Opcode == ISD::OR;
1729   // We can negate the results of all previous operations by inverting the
1730   // predicate flags giving us a free negation for one side. The other side
1731   // must be negatable by itself.
1732   if (NegateOpsAndResult) {
1733     // See which side we can negate.
1734     bool CanNegateL;
1735     bool isValidL = canEmitConjunction(LHS, CanNegateL);
1736     assert(isValidL && "Valid conjunction/disjunction tree");
1737     (void)isValidL;
1738 
1739 #ifndef NDEBUG
1740     bool CanNegateR;
1741     bool isValidR = canEmitConjunction(RHS, CanNegateR);
1742     assert(isValidR && "Valid conjunction/disjunction tree");
1743     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1744 #endif
1745 
1746     // Order the side which we cannot negate to RHS so we can emit it first.
1747     if (!CanNegateL)
1748       std::swap(LHS, RHS);
1749   } else {
1750     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1751     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1752            "Valid conjunction/disjunction tree");
1753     // Order the side where we need to negate the output flags to RHS so it
1754     // gets emitted first.
1755     if (NeedsNegOutL)
1756       std::swap(LHS, RHS);
1757   }
1758 
1759   // Emit RHS. If we want to negate the tree we only need to push a negate
1760   // through if we are already in a PushNegate case, otherwise we can negate
1761   // the "flags to test" afterwards.
1762   AArch64CC::CondCode RHSCC;
1763   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, Negate,
1764                                                    CCOp, Predicate);
1765   if (NegateOpsAndResult && !Negate)
1766     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1767   // Emit LHS. We may need to negate it.
1768   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC,
1769                                                    NegateOpsAndResult, CmpR,
1770                                                    RHSCC);
1771   // If we transformed an OR to and AND then we have to negate the result
1772   // (or absorb the Negate parameter).
1773   if (NegateOpsAndResult && !Negate)
1774     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1775   return CmpL;
1776 }
1777 
1778 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1779 /// In some cases this is even possible with OR operations in the expression.
1780 /// See \ref AArch64CCMP.
1781 /// \see emitConjunctionRec().
1782 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1783                                AArch64CC::CondCode &OutCC) {
1784   bool DummyCanNegate;
1785   if (!canEmitConjunction(Val, DummyCanNegate))
1786     return SDValue();
1787 
1788   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1789 }
1790 
1791 /// @}
1792 
1793 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1794 /// extension operations.
1795 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1796   auto isSupportedExtend = [&](SDValue V) {
1797     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1798       return true;
1799 
1800     if (V.getOpcode() == ISD::AND)
1801       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1802         uint64_t Mask = MaskCst->getZExtValue();
1803         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1804       }
1805 
1806     return false;
1807   };
1808 
1809   if (!Op.hasOneUse())
1810     return 0;
1811 
1812   if (isSupportedExtend(Op))
1813     return 1;
1814 
1815   unsigned Opc = Op.getOpcode();
1816   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1817     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1818       uint64_t Shift = ShiftCst->getZExtValue();
1819       if (isSupportedExtend(Op.getOperand(0)))
1820         return (Shift <= 4) ? 2 : 1;
1821       EVT VT = Op.getValueType();
1822       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1823         return 1;
1824     }
1825 
1826   return 0;
1827 }
1828 
1829 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1830                              SDValue &AArch64cc, SelectionDAG &DAG,
1831                              const SDLoc &dl) {
1832   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1833     EVT VT = RHS.getValueType();
1834     uint64_t C = RHSC->getZExtValue();
1835     if (!isLegalArithImmed(C)) {
1836       // Constant does not fit, try adjusting it by one?
1837       switch (CC) {
1838       default:
1839         break;
1840       case ISD::SETLT:
1841       case ISD::SETGE:
1842         if ((VT == MVT::i32 && C != 0x80000000 &&
1843              isLegalArithImmed((uint32_t)(C - 1))) ||
1844             (VT == MVT::i64 && C != 0x80000000ULL &&
1845              isLegalArithImmed(C - 1ULL))) {
1846           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1847           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1848           RHS = DAG.getConstant(C, dl, VT);
1849         }
1850         break;
1851       case ISD::SETULT:
1852       case ISD::SETUGE:
1853         if ((VT == MVT::i32 && C != 0 &&
1854              isLegalArithImmed((uint32_t)(C - 1))) ||
1855             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1856           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1857           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1858           RHS = DAG.getConstant(C, dl, VT);
1859         }
1860         break;
1861       case ISD::SETLE:
1862       case ISD::SETGT:
1863         if ((VT == MVT::i32 && C != INT32_MAX &&
1864              isLegalArithImmed((uint32_t)(C + 1))) ||
1865             (VT == MVT::i64 && C != INT64_MAX &&
1866              isLegalArithImmed(C + 1ULL))) {
1867           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1868           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1869           RHS = DAG.getConstant(C, dl, VT);
1870         }
1871         break;
1872       case ISD::SETULE:
1873       case ISD::SETUGT:
1874         if ((VT == MVT::i32 && C != UINT32_MAX &&
1875              isLegalArithImmed((uint32_t)(C + 1))) ||
1876             (VT == MVT::i64 && C != UINT64_MAX &&
1877              isLegalArithImmed(C + 1ULL))) {
1878           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1879           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1880           RHS = DAG.getConstant(C, dl, VT);
1881         }
1882         break;
1883       }
1884     }
1885   }
1886 
1887   // Comparisons are canonicalized so that the RHS operand is simpler than the
1888   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1889   // can fold some shift+extend operations on the RHS operand, so swap the
1890   // operands if that can be done.
1891   //
1892   // For example:
1893   //    lsl     w13, w11, #1
1894   //    cmp     w13, w12
1895   // can be turned into:
1896   //    cmp     w12, w11, lsl #1
1897   if (!isa<ConstantSDNode>(RHS) ||
1898       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1899     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1900 
1901     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1902       std::swap(LHS, RHS);
1903       CC = ISD::getSetCCSwappedOperands(CC);
1904     }
1905   }
1906 
1907   SDValue Cmp;
1908   AArch64CC::CondCode AArch64CC;
1909   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1910     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1911 
1912     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1913     // For the i8 operand, the largest immediate is 255, so this can be easily
1914     // encoded in the compare instruction. For the i16 operand, however, the
1915     // largest immediate cannot be encoded in the compare.
1916     // Therefore, use a sign extending load and cmn to avoid materializing the
1917     // -1 constant. For example,
1918     // movz w1, #65535
1919     // ldrh w0, [x0, #0]
1920     // cmp w0, w1
1921     // >
1922     // ldrsh w0, [x0, #0]
1923     // cmn w0, #1
1924     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1925     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1926     // ensure both the LHS and RHS are truly zero extended and to make sure the
1927     // transformation is profitable.
1928     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1929         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1930         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1931         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1932       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1933       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1934         SDValue SExt =
1935             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1936                         DAG.getValueType(MVT::i16));
1937         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1938                                                    RHS.getValueType()),
1939                              CC, dl, DAG);
1940         AArch64CC = changeIntCCToAArch64CC(CC);
1941       }
1942     }
1943 
1944     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1945       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
1946         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1947           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1948       }
1949     }
1950   }
1951 
1952   if (!Cmp) {
1953     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1954     AArch64CC = changeIntCCToAArch64CC(CC);
1955   }
1956   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1957   return Cmp;
1958 }
1959 
1960 static std::pair<SDValue, SDValue>
1961 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1962   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1963          "Unsupported value type");
1964   SDValue Value, Overflow;
1965   SDLoc DL(Op);
1966   SDValue LHS = Op.getOperand(0);
1967   SDValue RHS = Op.getOperand(1);
1968   unsigned Opc = 0;
1969   switch (Op.getOpcode()) {
1970   default:
1971     llvm_unreachable("Unknown overflow instruction!");
1972   case ISD::SADDO:
1973     Opc = AArch64ISD::ADDS;
1974     CC = AArch64CC::VS;
1975     break;
1976   case ISD::UADDO:
1977     Opc = AArch64ISD::ADDS;
1978     CC = AArch64CC::HS;
1979     break;
1980   case ISD::SSUBO:
1981     Opc = AArch64ISD::SUBS;
1982     CC = AArch64CC::VS;
1983     break;
1984   case ISD::USUBO:
1985     Opc = AArch64ISD::SUBS;
1986     CC = AArch64CC::LO;
1987     break;
1988   // Multiply needs a little bit extra work.
1989   case ISD::SMULO:
1990   case ISD::UMULO: {
1991     CC = AArch64CC::NE;
1992     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1993     if (Op.getValueType() == MVT::i32) {
1994       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1995       // For a 32 bit multiply with overflow check we want the instruction
1996       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1997       // need to generate the following pattern:
1998       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1999       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2000       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2001       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2002       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2003                                 DAG.getConstant(0, DL, MVT::i64));
2004       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2005       // operation. We need to clear out the upper 32 bits, because we used a
2006       // widening multiply that wrote all 64 bits. In the end this should be a
2007       // noop.
2008       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2009       if (IsSigned) {
2010         // The signed overflow check requires more than just a simple check for
2011         // any bit set in the upper 32 bits of the result. These bits could be
2012         // just the sign bits of a negative number. To perform the overflow
2013         // check we have to arithmetic shift right the 32nd bit of the result by
2014         // 31 bits. Then we compare the result to the upper 32 bits.
2015         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2016                                         DAG.getConstant(32, DL, MVT::i64));
2017         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2018         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2019                                         DAG.getConstant(31, DL, MVT::i64));
2020         // It is important that LowerBits is last, otherwise the arithmetic
2021         // shift will not be folded into the compare (SUBS).
2022         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2023         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2024                        .getValue(1);
2025       } else {
2026         // The overflow check for unsigned multiply is easy. We only need to
2027         // check if any of the upper 32 bits are set. This can be done with a
2028         // CMP (shifted register). For that we need to generate the following
2029         // pattern:
2030         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2031         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2032                                         DAG.getConstant(32, DL, MVT::i64));
2033         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2034         Overflow =
2035             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2036                         DAG.getConstant(0, DL, MVT::i64),
2037                         UpperBits).getValue(1);
2038       }
2039       break;
2040     }
2041     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2042     // For the 64 bit multiply
2043     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2044     if (IsSigned) {
2045       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2046       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2047                                       DAG.getConstant(63, DL, MVT::i64));
2048       // It is important that LowerBits is last, otherwise the arithmetic
2049       // shift will not be folded into the compare (SUBS).
2050       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2051       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2052                      .getValue(1);
2053     } else {
2054       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2055       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2056       Overflow =
2057           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2058                       DAG.getConstant(0, DL, MVT::i64),
2059                       UpperBits).getValue(1);
2060     }
2061     break;
2062   }
2063   } // switch (...)
2064 
2065   if (Opc) {
2066     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2067 
2068     // Emit the AArch64 operation with overflow check.
2069     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2070     Overflow = Value.getValue(1);
2071   }
2072   return std::make_pair(Value, Overflow);
2073 }
2074 
2075 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2076                                              RTLIB::Libcall Call) const {
2077   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2078   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
2079 }
2080 
2081 // Returns true if the given Op is the overflow flag result of an overflow
2082 // intrinsic operation.
2083 static bool isOverflowIntrOpRes(SDValue Op) {
2084   unsigned Opc = Op.getOpcode();
2085   return (Op.getResNo() == 1 &&
2086           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2087            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2088 }
2089 
2090 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2091   SDValue Sel = Op.getOperand(0);
2092   SDValue Other = Op.getOperand(1);
2093   SDLoc dl(Sel);
2094 
2095   // If the operand is an overflow checking operation, invert the condition
2096   // code and kill the Not operation. I.e., transform:
2097   // (xor (overflow_op_bool, 1))
2098   //   -->
2099   // (csel 1, 0, invert(cc), overflow_op_bool)
2100   // ... which later gets transformed to just a cset instruction with an
2101   // inverted condition code, rather than a cset + eor sequence.
2102   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2103     // Only lower legal XALUO ops.
2104     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2105       return SDValue();
2106 
2107     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2108     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2109     AArch64CC::CondCode CC;
2110     SDValue Value, Overflow;
2111     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2112     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2113     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2114                        CCVal, Overflow);
2115   }
2116   // If neither operand is a SELECT_CC, give up.
2117   if (Sel.getOpcode() != ISD::SELECT_CC)
2118     std::swap(Sel, Other);
2119   if (Sel.getOpcode() != ISD::SELECT_CC)
2120     return Op;
2121 
2122   // The folding we want to perform is:
2123   // (xor x, (select_cc a, b, cc, 0, -1) )
2124   //   -->
2125   // (csel x, (xor x, -1), cc ...)
2126   //
2127   // The latter will get matched to a CSINV instruction.
2128 
2129   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2130   SDValue LHS = Sel.getOperand(0);
2131   SDValue RHS = Sel.getOperand(1);
2132   SDValue TVal = Sel.getOperand(2);
2133   SDValue FVal = Sel.getOperand(3);
2134 
2135   // FIXME: This could be generalized to non-integer comparisons.
2136   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2137     return Op;
2138 
2139   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2140   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2141 
2142   // The values aren't constants, this isn't the pattern we're looking for.
2143   if (!CFVal || !CTVal)
2144     return Op;
2145 
2146   // We can commute the SELECT_CC by inverting the condition.  This
2147   // might be needed to make this fit into a CSINV pattern.
2148   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2149     std::swap(TVal, FVal);
2150     std::swap(CTVal, CFVal);
2151     CC = ISD::getSetCCInverse(CC, true);
2152   }
2153 
2154   // If the constants line up, perform the transform!
2155   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2156     SDValue CCVal;
2157     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2158 
2159     FVal = Other;
2160     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2161                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2162 
2163     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2164                        CCVal, Cmp);
2165   }
2166 
2167   return Op;
2168 }
2169 
2170 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2171   EVT VT = Op.getValueType();
2172 
2173   // Let legalize expand this if it isn't a legal type yet.
2174   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2175     return SDValue();
2176 
2177   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2178 
2179   unsigned Opc;
2180   bool ExtraOp = false;
2181   switch (Op.getOpcode()) {
2182   default:
2183     llvm_unreachable("Invalid code");
2184   case ISD::ADDC:
2185     Opc = AArch64ISD::ADDS;
2186     break;
2187   case ISD::SUBC:
2188     Opc = AArch64ISD::SUBS;
2189     break;
2190   case ISD::ADDE:
2191     Opc = AArch64ISD::ADCS;
2192     ExtraOp = true;
2193     break;
2194   case ISD::SUBE:
2195     Opc = AArch64ISD::SBCS;
2196     ExtraOp = true;
2197     break;
2198   }
2199 
2200   if (!ExtraOp)
2201     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2202   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2203                      Op.getOperand(2));
2204 }
2205 
2206 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2207   // Let legalize expand this if it isn't a legal type yet.
2208   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2209     return SDValue();
2210 
2211   SDLoc dl(Op);
2212   AArch64CC::CondCode CC;
2213   // The actual operation that sets the overflow or carry flag.
2214   SDValue Value, Overflow;
2215   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2216 
2217   // We use 0 and 1 as false and true values.
2218   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2219   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2220 
2221   // We use an inverted condition, because the conditional select is inverted
2222   // too. This will allow it to be selected to a single instruction:
2223   // CSINC Wd, WZR, WZR, invert(cond).
2224   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2225   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2226                          CCVal, Overflow);
2227 
2228   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2229   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2230 }
2231 
2232 // Prefetch operands are:
2233 // 1: Address to prefetch
2234 // 2: bool isWrite
2235 // 3: int locality (0 = no locality ... 3 = extreme locality)
2236 // 4: bool isDataCache
2237 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2238   SDLoc DL(Op);
2239   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2240   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2241   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2242 
2243   bool IsStream = !Locality;
2244   // When the locality number is set
2245   if (Locality) {
2246     // The front-end should have filtered out the out-of-range values
2247     assert(Locality <= 3 && "Prefetch locality out-of-range");
2248     // The locality degree is the opposite of the cache speed.
2249     // Put the number the other way around.
2250     // The encoding starts at 0 for level 1
2251     Locality = 3 - Locality;
2252   }
2253 
2254   // built the mask value encoding the expected behavior.
2255   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2256                    (!IsData << 3) |     // IsDataCache bit
2257                    (Locality << 1) |    // Cache level bits
2258                    (unsigned)IsStream;  // Stream bit
2259   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2260                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2261 }
2262 
2263 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2264                                               SelectionDAG &DAG) const {
2265   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2266 
2267   RTLIB::Libcall LC;
2268   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2269 
2270   return LowerF128Call(Op, DAG, LC);
2271 }
2272 
2273 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2274                                              SelectionDAG &DAG) const {
2275   if (Op.getOperand(0).getValueType() != MVT::f128) {
2276     // It's legal except when f128 is involved
2277     return Op;
2278   }
2279 
2280   RTLIB::Libcall LC;
2281   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2282 
2283   // FP_ROUND node has a second operand indicating whether it is known to be
2284   // precise. That doesn't take part in the LibCall so we can't directly use
2285   // LowerF128Call.
2286   SDValue SrcVal = Op.getOperand(0);
2287   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2288                      SDLoc(Op)).first;
2289 }
2290 
2291 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2292   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2293   // Any additional optimization in this function should be recorded
2294   // in the cost tables.
2295   EVT InVT = Op.getOperand(0).getValueType();
2296   EVT VT = Op.getValueType();
2297   unsigned NumElts = InVT.getVectorNumElements();
2298 
2299   // f16 vectors are promoted to f32 before a conversion.
2300   if (InVT.getVectorElementType() == MVT::f16) {
2301     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2302     SDLoc dl(Op);
2303     return DAG.getNode(
2304         Op.getOpcode(), dl, Op.getValueType(),
2305         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2306   }
2307 
2308   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2309     SDLoc dl(Op);
2310     SDValue Cv =
2311         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2312                     Op.getOperand(0));
2313     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2314   }
2315 
2316   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2317     SDLoc dl(Op);
2318     MVT ExtVT =
2319         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2320                          VT.getVectorNumElements());
2321     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2322     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2323   }
2324 
2325   // Type changing conversions are illegal.
2326   return Op;
2327 }
2328 
2329 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2330                                               SelectionDAG &DAG) const {
2331   if (Op.getOperand(0).getValueType().isVector())
2332     return LowerVectorFP_TO_INT(Op, DAG);
2333 
2334   // f16 conversions are promoted to f32 when full fp16 is not supported.
2335   if (Op.getOperand(0).getValueType() == MVT::f16 &&
2336       !Subtarget->hasFullFP16()) {
2337     SDLoc dl(Op);
2338     return DAG.getNode(
2339         Op.getOpcode(), dl, Op.getValueType(),
2340         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2341   }
2342 
2343   if (Op.getOperand(0).getValueType() != MVT::f128) {
2344     // It's legal except when f128 is involved
2345     return Op;
2346   }
2347 
2348   RTLIB::Libcall LC;
2349   if (Op.getOpcode() == ISD::FP_TO_SINT)
2350     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2351   else
2352     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2353 
2354   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2355   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2356 }
2357 
2358 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2359   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2360   // Any additional optimization in this function should be recorded
2361   // in the cost tables.
2362   EVT VT = Op.getValueType();
2363   SDLoc dl(Op);
2364   SDValue In = Op.getOperand(0);
2365   EVT InVT = In.getValueType();
2366 
2367   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2368     MVT CastVT =
2369         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2370                          InVT.getVectorNumElements());
2371     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2372     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2373   }
2374 
2375   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2376     unsigned CastOpc =
2377         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2378     EVT CastVT = VT.changeVectorElementTypeToInteger();
2379     In = DAG.getNode(CastOpc, dl, CastVT, In);
2380     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2381   }
2382 
2383   return Op;
2384 }
2385 
2386 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2387                                             SelectionDAG &DAG) const {
2388   if (Op.getValueType().isVector())
2389     return LowerVectorINT_TO_FP(Op, DAG);
2390 
2391   // f16 conversions are promoted to f32 when full fp16 is not supported.
2392   if (Op.getValueType() == MVT::f16 &&
2393       !Subtarget->hasFullFP16()) {
2394     SDLoc dl(Op);
2395     return DAG.getNode(
2396         ISD::FP_ROUND, dl, MVT::f16,
2397         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2398         DAG.getIntPtrConstant(0, dl));
2399   }
2400 
2401   // i128 conversions are libcalls.
2402   if (Op.getOperand(0).getValueType() == MVT::i128)
2403     return SDValue();
2404 
2405   // Other conversions are legal, unless it's to the completely software-based
2406   // fp128.
2407   if (Op.getValueType() != MVT::f128)
2408     return Op;
2409 
2410   RTLIB::Libcall LC;
2411   if (Op.getOpcode() == ISD::SINT_TO_FP)
2412     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2413   else
2414     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2415 
2416   return LowerF128Call(Op, DAG, LC);
2417 }
2418 
2419 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2420                                             SelectionDAG &DAG) const {
2421   // For iOS, we want to call an alternative entry point: __sincos_stret,
2422   // which returns the values in two S / D registers.
2423   SDLoc dl(Op);
2424   SDValue Arg = Op.getOperand(0);
2425   EVT ArgVT = Arg.getValueType();
2426   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2427 
2428   ArgListTy Args;
2429   ArgListEntry Entry;
2430 
2431   Entry.Node = Arg;
2432   Entry.Ty = ArgTy;
2433   Entry.IsSExt = false;
2434   Entry.IsZExt = false;
2435   Args.push_back(Entry);
2436 
2437   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2438                                         : RTLIB::SINCOS_STRET_F32;
2439   const char *LibcallName = getLibcallName(LC);
2440   SDValue Callee =
2441       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2442 
2443   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2444   TargetLowering::CallLoweringInfo CLI(DAG);
2445   CLI.setDebugLoc(dl)
2446       .setChain(DAG.getEntryNode())
2447       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2448 
2449   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2450   return CallResult.first;
2451 }
2452 
2453 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2454   if (Op.getValueType() != MVT::f16)
2455     return SDValue();
2456 
2457   assert(Op.getOperand(0).getValueType() == MVT::i16);
2458   SDLoc DL(Op);
2459 
2460   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2461   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2462   return SDValue(
2463       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2464                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2465       0);
2466 }
2467 
2468 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2469   if (OrigVT.getSizeInBits() >= 64)
2470     return OrigVT;
2471 
2472   assert(OrigVT.isSimple() && "Expecting a simple value type");
2473 
2474   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2475   switch (OrigSimpleTy) {
2476   default: llvm_unreachable("Unexpected Vector Type");
2477   case MVT::v2i8:
2478   case MVT::v2i16:
2479      return MVT::v2i32;
2480   case MVT::v4i8:
2481     return  MVT::v4i16;
2482   }
2483 }
2484 
2485 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2486                                                  const EVT &OrigTy,
2487                                                  const EVT &ExtTy,
2488                                                  unsigned ExtOpcode) {
2489   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2490   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2491   // 64-bits we need to insert a new extension so that it will be 64-bits.
2492   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2493   if (OrigTy.getSizeInBits() >= 64)
2494     return N;
2495 
2496   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2497   EVT NewVT = getExtensionTo64Bits(OrigTy);
2498 
2499   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2500 }
2501 
2502 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2503                                    bool isSigned) {
2504   EVT VT = N->getValueType(0);
2505 
2506   if (N->getOpcode() != ISD::BUILD_VECTOR)
2507     return false;
2508 
2509   for (const SDValue &Elt : N->op_values()) {
2510     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2511       unsigned EltSize = VT.getScalarSizeInBits();
2512       unsigned HalfSize = EltSize / 2;
2513       if (isSigned) {
2514         if (!isIntN(HalfSize, C->getSExtValue()))
2515           return false;
2516       } else {
2517         if (!isUIntN(HalfSize, C->getZExtValue()))
2518           return false;
2519       }
2520       continue;
2521     }
2522     return false;
2523   }
2524 
2525   return true;
2526 }
2527 
2528 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2529   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2530     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2531                                              N->getOperand(0)->getValueType(0),
2532                                              N->getValueType(0),
2533                                              N->getOpcode());
2534 
2535   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2536   EVT VT = N->getValueType(0);
2537   SDLoc dl(N);
2538   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2539   unsigned NumElts = VT.getVectorNumElements();
2540   MVT TruncVT = MVT::getIntegerVT(EltSize);
2541   SmallVector<SDValue, 8> Ops;
2542   for (unsigned i = 0; i != NumElts; ++i) {
2543     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2544     const APInt &CInt = C->getAPIntValue();
2545     // Element types smaller than 32 bits are not legal, so use i32 elements.
2546     // The values are implicitly truncated so sext vs. zext doesn't matter.
2547     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2548   }
2549   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2550 }
2551 
2552 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2553   return N->getOpcode() == ISD::SIGN_EXTEND ||
2554          isExtendedBUILD_VECTOR(N, DAG, true);
2555 }
2556 
2557 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2558   return N->getOpcode() == ISD::ZERO_EXTEND ||
2559          isExtendedBUILD_VECTOR(N, DAG, false);
2560 }
2561 
2562 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2563   unsigned Opcode = N->getOpcode();
2564   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2565     SDNode *N0 = N->getOperand(0).getNode();
2566     SDNode *N1 = N->getOperand(1).getNode();
2567     return N0->hasOneUse() && N1->hasOneUse() &&
2568       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2569   }
2570   return false;
2571 }
2572 
2573 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2574   unsigned Opcode = N->getOpcode();
2575   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2576     SDNode *N0 = N->getOperand(0).getNode();
2577     SDNode *N1 = N->getOperand(1).getNode();
2578     return N0->hasOneUse() && N1->hasOneUse() &&
2579       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2580   }
2581   return false;
2582 }
2583 
2584 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2585                                                 SelectionDAG &DAG) const {
2586   // The rounding mode is in bits 23:22 of the FPSCR.
2587   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2588   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2589   // so that the shift + and get folded into a bitfield extract.
2590   SDLoc dl(Op);
2591 
2592   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2593                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2594                                                 MVT::i64));
2595   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2596   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2597                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2598   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2599                               DAG.getConstant(22, dl, MVT::i32));
2600   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2601                      DAG.getConstant(3, dl, MVT::i32));
2602 }
2603 
2604 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2605   // Multiplications are only custom-lowered for 128-bit vectors so that
2606   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2607   EVT VT = Op.getValueType();
2608   assert(VT.is128BitVector() && VT.isInteger() &&
2609          "unexpected type for custom-lowering ISD::MUL");
2610   SDNode *N0 = Op.getOperand(0).getNode();
2611   SDNode *N1 = Op.getOperand(1).getNode();
2612   unsigned NewOpc = 0;
2613   bool isMLA = false;
2614   bool isN0SExt = isSignExtended(N0, DAG);
2615   bool isN1SExt = isSignExtended(N1, DAG);
2616   if (isN0SExt && isN1SExt)
2617     NewOpc = AArch64ISD::SMULL;
2618   else {
2619     bool isN0ZExt = isZeroExtended(N0, DAG);
2620     bool isN1ZExt = isZeroExtended(N1, DAG);
2621     if (isN0ZExt && isN1ZExt)
2622       NewOpc = AArch64ISD::UMULL;
2623     else if (isN1SExt || isN1ZExt) {
2624       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2625       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2626       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2627         NewOpc = AArch64ISD::SMULL;
2628         isMLA = true;
2629       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2630         NewOpc =  AArch64ISD::UMULL;
2631         isMLA = true;
2632       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2633         std::swap(N0, N1);
2634         NewOpc =  AArch64ISD::UMULL;
2635         isMLA = true;
2636       }
2637     }
2638 
2639     if (!NewOpc) {
2640       if (VT == MVT::v2i64)
2641         // Fall through to expand this.  It is not legal.
2642         return SDValue();
2643       else
2644         // Other vector multiplications are legal.
2645         return Op;
2646     }
2647   }
2648 
2649   // Legalize to a S/UMULL instruction
2650   SDLoc DL(Op);
2651   SDValue Op0;
2652   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2653   if (!isMLA) {
2654     Op0 = skipExtensionForVectorMULL(N0, DAG);
2655     assert(Op0.getValueType().is64BitVector() &&
2656            Op1.getValueType().is64BitVector() &&
2657            "unexpected types for extended operands to VMULL");
2658     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2659   }
2660   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2661   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2662   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2663   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2664   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2665   EVT Op1VT = Op1.getValueType();
2666   return DAG.getNode(N0->getOpcode(), DL, VT,
2667                      DAG.getNode(NewOpc, DL, VT,
2668                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2669                      DAG.getNode(NewOpc, DL, VT,
2670                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2671 }
2672 
2673 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2674                                                      SelectionDAG &DAG) const {
2675   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2676   SDLoc dl(Op);
2677   switch (IntNo) {
2678   default: return SDValue();    // Don't custom lower most intrinsics.
2679   case Intrinsic::thread_pointer: {
2680     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2681     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2682   }
2683   case Intrinsic::aarch64_neon_abs:
2684     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2685                        Op.getOperand(1));
2686   case Intrinsic::aarch64_neon_smax:
2687     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2688                        Op.getOperand(1), Op.getOperand(2));
2689   case Intrinsic::aarch64_neon_umax:
2690     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2691                        Op.getOperand(1), Op.getOperand(2));
2692   case Intrinsic::aarch64_neon_smin:
2693     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2694                        Op.getOperand(1), Op.getOperand(2));
2695   case Intrinsic::aarch64_neon_umin:
2696     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2697                        Op.getOperand(1), Op.getOperand(2));
2698   }
2699 }
2700 
2701 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2702 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2703                                         EVT VT, EVT MemVT,
2704                                         SelectionDAG &DAG) {
2705   assert(VT.isVector() && "VT should be a vector type");
2706   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2707 
2708   SDValue Value = ST->getValue();
2709 
2710   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2711   // the word lane which represent the v4i8 subvector.  It optimizes the store
2712   // to:
2713   //
2714   //   xtn  v0.8b, v0.8h
2715   //   str  s0, [x0]
2716 
2717   SDValue Undef = DAG.getUNDEF(MVT::i16);
2718   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2719                                         {Undef, Undef, Undef, Undef});
2720 
2721   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2722                                  Value, UndefVec);
2723   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2724 
2725   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2726   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2727                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
2728 
2729   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2730                       ST->getBasePtr(), ST->getMemOperand());
2731 }
2732 
2733 // Custom lowering for any store, vector or scalar and/or default or with
2734 // a truncate operations.  Currently only custom lower truncate operation
2735 // from vector v4i16 to v4i8.
2736 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2737                                           SelectionDAG &DAG) const {
2738   SDLoc Dl(Op);
2739   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2740   assert (StoreNode && "Can only custom lower store nodes");
2741 
2742   SDValue Value = StoreNode->getValue();
2743 
2744   EVT VT = Value.getValueType();
2745   EVT MemVT = StoreNode->getMemoryVT();
2746 
2747   assert (VT.isVector() && "Can only custom lower vector store types");
2748 
2749   unsigned AS = StoreNode->getAddressSpace();
2750   unsigned Align = StoreNode->getAlignment();
2751   if (Align < MemVT.getStoreSize() &&
2752       !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2753     return scalarizeVectorStore(StoreNode, DAG);
2754   }
2755 
2756   if (StoreNode->isTruncatingStore()) {
2757     return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2758   }
2759 
2760   return SDValue();
2761 }
2762 
2763 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2764                                               SelectionDAG &DAG) const {
2765   LLVM_DEBUG(dbgs() << "Custom lowering: ");
2766   LLVM_DEBUG(Op.dump());
2767 
2768   switch (Op.getOpcode()) {
2769   default:
2770     llvm_unreachable("unimplemented operand");
2771     return SDValue();
2772   case ISD::BITCAST:
2773     return LowerBITCAST(Op, DAG);
2774   case ISD::GlobalAddress:
2775     return LowerGlobalAddress(Op, DAG);
2776   case ISD::GlobalTLSAddress:
2777     return LowerGlobalTLSAddress(Op, DAG);
2778   case ISD::SETCC:
2779     return LowerSETCC(Op, DAG);
2780   case ISD::BR_CC:
2781     return LowerBR_CC(Op, DAG);
2782   case ISD::SELECT:
2783     return LowerSELECT(Op, DAG);
2784   case ISD::SELECT_CC:
2785     return LowerSELECT_CC(Op, DAG);
2786   case ISD::JumpTable:
2787     return LowerJumpTable(Op, DAG);
2788   case ISD::BR_JT:
2789     return LowerBR_JT(Op, DAG);
2790   case ISD::ConstantPool:
2791     return LowerConstantPool(Op, DAG);
2792   case ISD::BlockAddress:
2793     return LowerBlockAddress(Op, DAG);
2794   case ISD::VASTART:
2795     return LowerVASTART(Op, DAG);
2796   case ISD::VACOPY:
2797     return LowerVACOPY(Op, DAG);
2798   case ISD::VAARG:
2799     return LowerVAARG(Op, DAG);
2800   case ISD::ADDC:
2801   case ISD::ADDE:
2802   case ISD::SUBC:
2803   case ISD::SUBE:
2804     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2805   case ISD::SADDO:
2806   case ISD::UADDO:
2807   case ISD::SSUBO:
2808   case ISD::USUBO:
2809   case ISD::SMULO:
2810   case ISD::UMULO:
2811     return LowerXALUO(Op, DAG);
2812   case ISD::FADD:
2813     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2814   case ISD::FSUB:
2815     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2816   case ISD::FMUL:
2817     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2818   case ISD::FDIV:
2819     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2820   case ISD::FP_ROUND:
2821     return LowerFP_ROUND(Op, DAG);
2822   case ISD::FP_EXTEND:
2823     return LowerFP_EXTEND(Op, DAG);
2824   case ISD::FRAMEADDR:
2825     return LowerFRAMEADDR(Op, DAG);
2826   case ISD::SPONENTRY:
2827     return LowerSPONENTRY(Op, DAG);
2828   case ISD::RETURNADDR:
2829     return LowerRETURNADDR(Op, DAG);
2830   case ISD::ADDROFRETURNADDR:
2831     return LowerADDROFRETURNADDR(Op, DAG);
2832   case ISD::INSERT_VECTOR_ELT:
2833     return LowerINSERT_VECTOR_ELT(Op, DAG);
2834   case ISD::EXTRACT_VECTOR_ELT:
2835     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2836   case ISD::BUILD_VECTOR:
2837     return LowerBUILD_VECTOR(Op, DAG);
2838   case ISD::VECTOR_SHUFFLE:
2839     return LowerVECTOR_SHUFFLE(Op, DAG);
2840   case ISD::EXTRACT_SUBVECTOR:
2841     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2842   case ISD::SRA:
2843   case ISD::SRL:
2844   case ISD::SHL:
2845     return LowerVectorSRA_SRL_SHL(Op, DAG);
2846   case ISD::SHL_PARTS:
2847     return LowerShiftLeftParts(Op, DAG);
2848   case ISD::SRL_PARTS:
2849   case ISD::SRA_PARTS:
2850     return LowerShiftRightParts(Op, DAG);
2851   case ISD::CTPOP:
2852     return LowerCTPOP(Op, DAG);
2853   case ISD::FCOPYSIGN:
2854     return LowerFCOPYSIGN(Op, DAG);
2855   case ISD::AND:
2856     return LowerVectorAND(Op, DAG);
2857   case ISD::OR:
2858     return LowerVectorOR(Op, DAG);
2859   case ISD::XOR:
2860     return LowerXOR(Op, DAG);
2861   case ISD::PREFETCH:
2862     return LowerPREFETCH(Op, DAG);
2863   case ISD::SINT_TO_FP:
2864   case ISD::UINT_TO_FP:
2865     return LowerINT_TO_FP(Op, DAG);
2866   case ISD::FP_TO_SINT:
2867   case ISD::FP_TO_UINT:
2868     return LowerFP_TO_INT(Op, DAG);
2869   case ISD::FSINCOS:
2870     return LowerFSINCOS(Op, DAG);
2871   case ISD::FLT_ROUNDS_:
2872     return LowerFLT_ROUNDS_(Op, DAG);
2873   case ISD::MUL:
2874     return LowerMUL(Op, DAG);
2875   case ISD::INTRINSIC_WO_CHAIN:
2876     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2877   case ISD::STORE:
2878     return LowerSTORE(Op, DAG);
2879   case ISD::VECREDUCE_ADD:
2880   case ISD::VECREDUCE_SMAX:
2881   case ISD::VECREDUCE_SMIN:
2882   case ISD::VECREDUCE_UMAX:
2883   case ISD::VECREDUCE_UMIN:
2884   case ISD::VECREDUCE_FMAX:
2885   case ISD::VECREDUCE_FMIN:
2886     return LowerVECREDUCE(Op, DAG);
2887   case ISD::ATOMIC_LOAD_SUB:
2888     return LowerATOMIC_LOAD_SUB(Op, DAG);
2889   case ISD::ATOMIC_LOAD_AND:
2890     return LowerATOMIC_LOAD_AND(Op, DAG);
2891   case ISD::DYNAMIC_STACKALLOC:
2892     return LowerDYNAMIC_STACKALLOC(Op, DAG);
2893   }
2894 }
2895 
2896 //===----------------------------------------------------------------------===//
2897 //                      Calling Convention Implementation
2898 //===----------------------------------------------------------------------===//
2899 
2900 #include "AArch64GenCallingConv.inc"
2901 
2902 /// Selects the correct CCAssignFn for a given CallingConvention value.
2903 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2904                                                      bool IsVarArg) const {
2905   switch (CC) {
2906   default:
2907     report_fatal_error("Unsupported calling convention.");
2908   case CallingConv::WebKit_JS:
2909     return CC_AArch64_WebKit_JS;
2910   case CallingConv::GHC:
2911     return CC_AArch64_GHC;
2912   case CallingConv::C:
2913   case CallingConv::Fast:
2914   case CallingConv::PreserveMost:
2915   case CallingConv::CXX_FAST_TLS:
2916   case CallingConv::Swift:
2917     if (Subtarget->isTargetWindows() && IsVarArg)
2918       return CC_AArch64_Win64_VarArg;
2919     if (!Subtarget->isTargetDarwin())
2920       return CC_AArch64_AAPCS;
2921     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2922   case CallingConv::Win64:
2923     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2924   case CallingConv::AArch64_VectorCall:
2925     return CC_AArch64_AAPCS;
2926   }
2927 }
2928 
2929 CCAssignFn *
2930 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2931   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2932                                       : RetCC_AArch64_AAPCS;
2933 }
2934 
2935 SDValue AArch64TargetLowering::LowerFormalArguments(
2936     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2937     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2938     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2939   MachineFunction &MF = DAG.getMachineFunction();
2940   MachineFrameInfo &MFI = MF.getFrameInfo();
2941   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2942 
2943   // Assign locations to all of the incoming arguments.
2944   SmallVector<CCValAssign, 16> ArgLocs;
2945   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2946                  *DAG.getContext());
2947 
2948   // At this point, Ins[].VT may already be promoted to i32. To correctly
2949   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2950   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2951   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2952   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2953   // LocVT.
2954   unsigned NumArgs = Ins.size();
2955   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
2956   unsigned CurArgIdx = 0;
2957   for (unsigned i = 0; i != NumArgs; ++i) {
2958     MVT ValVT = Ins[i].VT;
2959     if (Ins[i].isOrigArg()) {
2960       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2961       CurArgIdx = Ins[i].getOrigArgIndex();
2962 
2963       // Get type of the original argument.
2964       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2965                                   /*AllowUnknown*/ true);
2966       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2967       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2968       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2969         ValVT = MVT::i8;
2970       else if (ActualMVT == MVT::i16)
2971         ValVT = MVT::i16;
2972     }
2973     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2974     bool Res =
2975         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2976     assert(!Res && "Call operand has unhandled type");
2977     (void)Res;
2978   }
2979   assert(ArgLocs.size() == Ins.size());
2980   SmallVector<SDValue, 16> ArgValues;
2981   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2982     CCValAssign &VA = ArgLocs[i];
2983 
2984     if (Ins[i].Flags.isByVal()) {
2985       // Byval is used for HFAs in the PCS, but the system should work in a
2986       // non-compliant manner for larger structs.
2987       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2988       int Size = Ins[i].Flags.getByValSize();
2989       unsigned NumRegs = (Size + 7) / 8;
2990 
2991       // FIXME: This works on big-endian for composite byvals, which are the common
2992       // case. It should also work for fundamental types too.
2993       unsigned FrameIdx =
2994         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2995       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2996       InVals.push_back(FrameIdxN);
2997 
2998       continue;
2999     }
3000 
3001     if (VA.isRegLoc()) {
3002       // Arguments stored in registers.
3003       EVT RegVT = VA.getLocVT();
3004 
3005       SDValue ArgValue;
3006       const TargetRegisterClass *RC;
3007 
3008       if (RegVT == MVT::i32)
3009         RC = &AArch64::GPR32RegClass;
3010       else if (RegVT == MVT::i64)
3011         RC = &AArch64::GPR64RegClass;
3012       else if (RegVT == MVT::f16)
3013         RC = &AArch64::FPR16RegClass;
3014       else if (RegVT == MVT::f32)
3015         RC = &AArch64::FPR32RegClass;
3016       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3017         RC = &AArch64::FPR64RegClass;
3018       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3019         RC = &AArch64::FPR128RegClass;
3020       else
3021         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3022 
3023       // Transform the arguments in physical registers into virtual ones.
3024       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3025       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3026 
3027       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3028       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3029       // truncate to the right size.
3030       switch (VA.getLocInfo()) {
3031       default:
3032         llvm_unreachable("Unknown loc info!");
3033       case CCValAssign::Full:
3034         break;
3035       case CCValAssign::BCvt:
3036         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3037         break;
3038       case CCValAssign::AExt:
3039       case CCValAssign::SExt:
3040       case CCValAssign::ZExt:
3041         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3042         // nodes after our lowering.
3043         assert(RegVT == Ins[i].VT && "incorrect register location selected");
3044         break;
3045       }
3046 
3047       InVals.push_back(ArgValue);
3048 
3049     } else { // VA.isRegLoc()
3050       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3051       unsigned ArgOffset = VA.getLocMemOffset();
3052       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3053 
3054       uint32_t BEAlign = 0;
3055       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3056           !Ins[i].Flags.isInConsecutiveRegs())
3057         BEAlign = 8 - ArgSize;
3058 
3059       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3060 
3061       // Create load nodes to retrieve arguments from the stack.
3062       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3063       SDValue ArgValue;
3064 
3065       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3066       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3067       MVT MemVT = VA.getValVT();
3068 
3069       switch (VA.getLocInfo()) {
3070       default:
3071         break;
3072       case CCValAssign::BCvt:
3073         MemVT = VA.getLocVT();
3074         break;
3075       case CCValAssign::SExt:
3076         ExtType = ISD::SEXTLOAD;
3077         break;
3078       case CCValAssign::ZExt:
3079         ExtType = ISD::ZEXTLOAD;
3080         break;
3081       case CCValAssign::AExt:
3082         ExtType = ISD::EXTLOAD;
3083         break;
3084       }
3085 
3086       ArgValue = DAG.getExtLoad(
3087           ExtType, DL, VA.getLocVT(), Chain, FIN,
3088           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3089           MemVT);
3090 
3091       InVals.push_back(ArgValue);
3092     }
3093   }
3094 
3095   // varargs
3096   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3097   if (isVarArg) {
3098     if (!Subtarget->isTargetDarwin() || IsWin64) {
3099       // The AAPCS variadic function ABI is identical to the non-variadic
3100       // one. As a result there may be more arguments in registers and we should
3101       // save them for future reference.
3102       // Win64 variadic functions also pass arguments in registers, but all float
3103       // arguments are passed in integer registers.
3104       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3105     }
3106 
3107     // This will point to the next argument passed via stack.
3108     unsigned StackOffset = CCInfo.getNextStackOffset();
3109     // We currently pass all varargs at 8-byte alignment.
3110     StackOffset = ((StackOffset + 7) & ~7);
3111     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3112 
3113     if (MFI.hasMustTailInVarArgFunc()) {
3114       SmallVector<MVT, 2> RegParmTypes;
3115       RegParmTypes.push_back(MVT::i64);
3116       RegParmTypes.push_back(MVT::f128);
3117       // Compute the set of forwarded registers. The rest are scratch.
3118       SmallVectorImpl<ForwardedRegister> &Forwards =
3119                                        FuncInfo->getForwardedMustTailRegParms();
3120       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3121                                                CC_AArch64_AAPCS);
3122     }
3123   }
3124 
3125   unsigned StackArgSize = CCInfo.getNextStackOffset();
3126   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3127   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3128     // This is a non-standard ABI so by fiat I say we're allowed to make full
3129     // use of the stack area to be popped, which must be aligned to 16 bytes in
3130     // any case:
3131     StackArgSize = alignTo(StackArgSize, 16);
3132 
3133     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3134     // a multiple of 16.
3135     FuncInfo->setArgumentStackToRestore(StackArgSize);
3136 
3137     // This realignment carries over to the available bytes below. Our own
3138     // callers will guarantee the space is free by giving an aligned value to
3139     // CALLSEQ_START.
3140   }
3141   // Even if we're not expected to free up the space, it's useful to know how
3142   // much is there while considering tail calls (because we can reuse it).
3143   FuncInfo->setBytesInStackArgArea(StackArgSize);
3144 
3145   if (Subtarget->hasCustomCallingConv())
3146     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3147 
3148   return Chain;
3149 }
3150 
3151 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3152                                                 SelectionDAG &DAG,
3153                                                 const SDLoc &DL,
3154                                                 SDValue &Chain) const {
3155   MachineFunction &MF = DAG.getMachineFunction();
3156   MachineFrameInfo &MFI = MF.getFrameInfo();
3157   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3158   auto PtrVT = getPointerTy(DAG.getDataLayout());
3159   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3160 
3161   SmallVector<SDValue, 8> MemOps;
3162 
3163   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3164                                           AArch64::X3, AArch64::X4, AArch64::X5,
3165                                           AArch64::X6, AArch64::X7 };
3166   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3167   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3168 
3169   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3170   int GPRIdx = 0;
3171   if (GPRSaveSize != 0) {
3172     if (IsWin64) {
3173       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3174       if (GPRSaveSize & 15)
3175         // The extra size here, if triggered, will always be 8.
3176         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3177     } else
3178       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3179 
3180     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3181 
3182     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3183       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3184       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3185       SDValue Store = DAG.getStore(
3186           Val.getValue(1), DL, Val, FIN,
3187           IsWin64
3188               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3189                                                   GPRIdx,
3190                                                   (i - FirstVariadicGPR) * 8)
3191               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3192       MemOps.push_back(Store);
3193       FIN =
3194           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3195     }
3196   }
3197   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3198   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3199 
3200   if (Subtarget->hasFPARMv8() && !IsWin64) {
3201     static const MCPhysReg FPRArgRegs[] = {
3202         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3203         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3204     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3205     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3206 
3207     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3208     int FPRIdx = 0;
3209     if (FPRSaveSize != 0) {
3210       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3211 
3212       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3213 
3214       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3215         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3216         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3217 
3218         SDValue Store = DAG.getStore(
3219             Val.getValue(1), DL, Val, FIN,
3220             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3221         MemOps.push_back(Store);
3222         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3223                           DAG.getConstant(16, DL, PtrVT));
3224       }
3225     }
3226     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3227     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3228   }
3229 
3230   if (!MemOps.empty()) {
3231     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3232   }
3233 }
3234 
3235 /// LowerCallResult - Lower the result values of a call into the
3236 /// appropriate copies out of appropriate physical registers.
3237 SDValue AArch64TargetLowering::LowerCallResult(
3238     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3239     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3240     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3241     SDValue ThisVal) const {
3242   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3243                           ? RetCC_AArch64_WebKit_JS
3244                           : RetCC_AArch64_AAPCS;
3245   // Assign locations to each value returned by this call.
3246   SmallVector<CCValAssign, 16> RVLocs;
3247   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3248                  *DAG.getContext());
3249   CCInfo.AnalyzeCallResult(Ins, RetCC);
3250 
3251   // Copy all of the result registers out of their specified physreg.
3252   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3253     CCValAssign VA = RVLocs[i];
3254 
3255     // Pass 'this' value directly from the argument to return value, to avoid
3256     // reg unit interference
3257     if (i == 0 && isThisReturn) {
3258       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3259              "unexpected return calling convention register assignment");
3260       InVals.push_back(ThisVal);
3261       continue;
3262     }
3263 
3264     SDValue Val =
3265         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3266     Chain = Val.getValue(1);
3267     InFlag = Val.getValue(2);
3268 
3269     switch (VA.getLocInfo()) {
3270     default:
3271       llvm_unreachable("Unknown loc info!");
3272     case CCValAssign::Full:
3273       break;
3274     case CCValAssign::BCvt:
3275       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3276       break;
3277     }
3278 
3279     InVals.push_back(Val);
3280   }
3281 
3282   return Chain;
3283 }
3284 
3285 /// Return true if the calling convention is one that we can guarantee TCO for.
3286 static bool canGuaranteeTCO(CallingConv::ID CC) {
3287   return CC == CallingConv::Fast;
3288 }
3289 
3290 /// Return true if we might ever do TCO for calls with this calling convention.
3291 static bool mayTailCallThisCC(CallingConv::ID CC) {
3292   switch (CC) {
3293   case CallingConv::C:
3294   case CallingConv::PreserveMost:
3295   case CallingConv::Swift:
3296     return true;
3297   default:
3298     return canGuaranteeTCO(CC);
3299   }
3300 }
3301 
3302 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3303     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3304     const SmallVectorImpl<ISD::OutputArg> &Outs,
3305     const SmallVectorImpl<SDValue> &OutVals,
3306     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3307   if (!mayTailCallThisCC(CalleeCC))
3308     return false;
3309 
3310   MachineFunction &MF = DAG.getMachineFunction();
3311   const Function &CallerF = MF.getFunction();
3312   CallingConv::ID CallerCC = CallerF.getCallingConv();
3313   bool CCMatch = CallerCC == CalleeCC;
3314 
3315   // Byval parameters hand the function a pointer directly into the stack area
3316   // we want to reuse during a tail call. Working around this *is* possible (see
3317   // X86) but less efficient and uglier in LowerCall.
3318   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3319                                     e = CallerF.arg_end();
3320        i != e; ++i)
3321     if (i->hasByValAttr())
3322       return false;
3323 
3324   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3325     return canGuaranteeTCO(CalleeCC) && CCMatch;
3326 
3327   // Externally-defined functions with weak linkage should not be
3328   // tail-called on AArch64 when the OS does not support dynamic
3329   // pre-emption of symbols, as the AAELF spec requires normal calls
3330   // to undefined weak functions to be replaced with a NOP or jump to the
3331   // next instruction. The behaviour of branch instructions in this
3332   // situation (as used for tail calls) is implementation-defined, so we
3333   // cannot rely on the linker replacing the tail call with a return.
3334   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3335     const GlobalValue *GV = G->getGlobal();
3336     const Triple &TT = getTargetMachine().getTargetTriple();
3337     if (GV->hasExternalWeakLinkage() &&
3338         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3339       return false;
3340   }
3341 
3342   // Now we search for cases where we can use a tail call without changing the
3343   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3344   // concept.
3345 
3346   // I want anyone implementing a new calling convention to think long and hard
3347   // about this assert.
3348   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3349          "Unexpected variadic calling convention");
3350 
3351   LLVMContext &C = *DAG.getContext();
3352   if (isVarArg && !Outs.empty()) {
3353     // At least two cases here: if caller is fastcc then we can't have any
3354     // memory arguments (we'd be expected to clean up the stack afterwards). If
3355     // caller is C then we could potentially use its argument area.
3356 
3357     // FIXME: for now we take the most conservative of these in both cases:
3358     // disallow all variadic memory operands.
3359     SmallVector<CCValAssign, 16> ArgLocs;
3360     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3361 
3362     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3363     for (const CCValAssign &ArgLoc : ArgLocs)
3364       if (!ArgLoc.isRegLoc())
3365         return false;
3366   }
3367 
3368   // Check that the call results are passed in the same way.
3369   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3370                                   CCAssignFnForCall(CalleeCC, isVarArg),
3371                                   CCAssignFnForCall(CallerCC, isVarArg)))
3372     return false;
3373   // The callee has to preserve all registers the caller needs to preserve.
3374   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3375   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3376   if (!CCMatch) {
3377     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3378     if (Subtarget->hasCustomCallingConv()) {
3379       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3380       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3381     }
3382     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3383       return false;
3384   }
3385 
3386   // Nothing more to check if the callee is taking no arguments
3387   if (Outs.empty())
3388     return true;
3389 
3390   SmallVector<CCValAssign, 16> ArgLocs;
3391   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3392 
3393   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3394 
3395   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3396 
3397   // If the stack arguments for this call do not fit into our own save area then
3398   // the call cannot be made tail.
3399   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3400     return false;
3401 
3402   const MachineRegisterInfo &MRI = MF.getRegInfo();
3403   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3404     return false;
3405 
3406   return true;
3407 }
3408 
3409 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3410                                                    SelectionDAG &DAG,
3411                                                    MachineFrameInfo &MFI,
3412                                                    int ClobberedFI) const {
3413   SmallVector<SDValue, 8> ArgChains;
3414   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3415   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3416 
3417   // Include the original chain at the beginning of the list. When this is
3418   // used by target LowerCall hooks, this helps legalize find the
3419   // CALLSEQ_BEGIN node.
3420   ArgChains.push_back(Chain);
3421 
3422   // Add a chain value for each stack argument corresponding
3423   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3424                             UE = DAG.getEntryNode().getNode()->use_end();
3425        U != UE; ++U)
3426     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3427       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3428         if (FI->getIndex() < 0) {
3429           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3430           int64_t InLastByte = InFirstByte;
3431           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3432 
3433           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3434               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3435             ArgChains.push_back(SDValue(L, 1));
3436         }
3437 
3438   // Build a tokenfactor for all the chains.
3439   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3440 }
3441 
3442 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3443                                                    bool TailCallOpt) const {
3444   return CallCC == CallingConv::Fast && TailCallOpt;
3445 }
3446 
3447 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3448 /// and add input and output parameter nodes.
3449 SDValue
3450 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3451                                  SmallVectorImpl<SDValue> &InVals) const {
3452   SelectionDAG &DAG = CLI.DAG;
3453   SDLoc &DL = CLI.DL;
3454   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3455   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3456   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3457   SDValue Chain = CLI.Chain;
3458   SDValue Callee = CLI.Callee;
3459   bool &IsTailCall = CLI.IsTailCall;
3460   CallingConv::ID CallConv = CLI.CallConv;
3461   bool IsVarArg = CLI.IsVarArg;
3462 
3463   MachineFunction &MF = DAG.getMachineFunction();
3464   bool IsThisReturn = false;
3465 
3466   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3467   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3468   bool IsSibCall = false;
3469 
3470   if (IsTailCall) {
3471     // Check if it's really possible to do a tail call.
3472     IsTailCall = isEligibleForTailCallOptimization(
3473         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3474     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3475       report_fatal_error("failed to perform tail call elimination on a call "
3476                          "site marked musttail");
3477 
3478     // A sibling call is one where we're under the usual C ABI and not planning
3479     // to change that but can still do a tail call:
3480     if (!TailCallOpt && IsTailCall)
3481       IsSibCall = true;
3482 
3483     if (IsTailCall)
3484       ++NumTailCalls;
3485   }
3486 
3487   // Analyze operands of the call, assigning locations to each operand.
3488   SmallVector<CCValAssign, 16> ArgLocs;
3489   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3490                  *DAG.getContext());
3491 
3492   if (IsVarArg) {
3493     // Handle fixed and variable vector arguments differently.
3494     // Variable vector arguments always go into memory.
3495     unsigned NumArgs = Outs.size();
3496 
3497     for (unsigned i = 0; i != NumArgs; ++i) {
3498       MVT ArgVT = Outs[i].VT;
3499       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3500       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3501                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3502       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3503       assert(!Res && "Call operand has unhandled type");
3504       (void)Res;
3505     }
3506   } else {
3507     // At this point, Outs[].VT may already be promoted to i32. To correctly
3508     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3509     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3510     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3511     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3512     // LocVT.
3513     unsigned NumArgs = Outs.size();
3514     for (unsigned i = 0; i != NumArgs; ++i) {
3515       MVT ValVT = Outs[i].VT;
3516       // Get type of the original argument.
3517       EVT ActualVT = getValueType(DAG.getDataLayout(),
3518                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3519                                   /*AllowUnknown*/ true);
3520       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3521       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3522       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3523       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3524         ValVT = MVT::i8;
3525       else if (ActualMVT == MVT::i16)
3526         ValVT = MVT::i16;
3527 
3528       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3529       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3530       assert(!Res && "Call operand has unhandled type");
3531       (void)Res;
3532     }
3533   }
3534 
3535   // Get a count of how many bytes are to be pushed on the stack.
3536   unsigned NumBytes = CCInfo.getNextStackOffset();
3537 
3538   if (IsSibCall) {
3539     // Since we're not changing the ABI to make this a tail call, the memory
3540     // operands are already available in the caller's incoming argument space.
3541     NumBytes = 0;
3542   }
3543 
3544   // FPDiff is the byte offset of the call's argument area from the callee's.
3545   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3546   // by this amount for a tail call. In a sibling call it must be 0 because the
3547   // caller will deallocate the entire stack and the callee still expects its
3548   // arguments to begin at SP+0. Completely unused for non-tail calls.
3549   int FPDiff = 0;
3550 
3551   if (IsTailCall && !IsSibCall) {
3552     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3553 
3554     // Since callee will pop argument stack as a tail call, we must keep the
3555     // popped size 16-byte aligned.
3556     NumBytes = alignTo(NumBytes, 16);
3557 
3558     // FPDiff will be negative if this tail call requires more space than we
3559     // would automatically have in our incoming argument space. Positive if we
3560     // can actually shrink the stack.
3561     FPDiff = NumReusableBytes - NumBytes;
3562 
3563     // The stack pointer must be 16-byte aligned at all times it's used for a
3564     // memory operation, which in practice means at *all* times and in
3565     // particular across call boundaries. Therefore our own arguments started at
3566     // a 16-byte aligned SP and the delta applied for the tail call should
3567     // satisfy the same constraint.
3568     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3569   }
3570 
3571   // Adjust the stack pointer for the new arguments...
3572   // These operations are automatically eliminated by the prolog/epilog pass
3573   if (!IsSibCall)
3574     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3575 
3576   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3577                                         getPointerTy(DAG.getDataLayout()));
3578 
3579   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3580   SmallVector<SDValue, 8> MemOpChains;
3581   auto PtrVT = getPointerTy(DAG.getDataLayout());
3582 
3583   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3584     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3585     for (const auto &F : Forwards) {
3586       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3587        RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3588     }
3589   }
3590 
3591   // Walk the register/memloc assignments, inserting copies/loads.
3592   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3593        ++i, ++realArgIdx) {
3594     CCValAssign &VA = ArgLocs[i];
3595     SDValue Arg = OutVals[realArgIdx];
3596     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3597 
3598     // Promote the value if needed.
3599     switch (VA.getLocInfo()) {
3600     default:
3601       llvm_unreachable("Unknown loc info!");
3602     case CCValAssign::Full:
3603       break;
3604     case CCValAssign::SExt:
3605       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3606       break;
3607     case CCValAssign::ZExt:
3608       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3609       break;
3610     case CCValAssign::AExt:
3611       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3612         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3613         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3614         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3615       }
3616       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3617       break;
3618     case CCValAssign::BCvt:
3619       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3620       break;
3621     case CCValAssign::FPExt:
3622       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3623       break;
3624     }
3625 
3626     if (VA.isRegLoc()) {
3627       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3628           Outs[0].VT == MVT::i64) {
3629         assert(VA.getLocVT() == MVT::i64 &&
3630                "unexpected calling convention register assignment");
3631         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3632                "unexpected use of 'returned'");
3633         IsThisReturn = true;
3634       }
3635       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3636     } else {
3637       assert(VA.isMemLoc());
3638 
3639       SDValue DstAddr;
3640       MachinePointerInfo DstInfo;
3641 
3642       // FIXME: This works on big-endian for composite byvals, which are the
3643       // common case. It should also work for fundamental types too.
3644       uint32_t BEAlign = 0;
3645       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3646                                         : VA.getValVT().getSizeInBits();
3647       OpSize = (OpSize + 7) / 8;
3648       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3649           !Flags.isInConsecutiveRegs()) {
3650         if (OpSize < 8)
3651           BEAlign = 8 - OpSize;
3652       }
3653       unsigned LocMemOffset = VA.getLocMemOffset();
3654       int32_t Offset = LocMemOffset + BEAlign;
3655       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3656       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3657 
3658       if (IsTailCall) {
3659         Offset = Offset + FPDiff;
3660         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3661 
3662         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3663         DstInfo =
3664             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3665 
3666         // Make sure any stack arguments overlapping with where we're storing
3667         // are loaded before this eventual operation. Otherwise they'll be
3668         // clobbered.
3669         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3670       } else {
3671         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3672 
3673         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3674         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3675                                                LocMemOffset);
3676       }
3677 
3678       if (Outs[i].Flags.isByVal()) {
3679         SDValue SizeNode =
3680             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3681         SDValue Cpy = DAG.getMemcpy(
3682             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3683             /*isVol = */ false, /*AlwaysInline = */ false,
3684             /*isTailCall = */ false,
3685             DstInfo, MachinePointerInfo());
3686 
3687         MemOpChains.push_back(Cpy);
3688       } else {
3689         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3690         // promoted to a legal register type i32, we should truncate Arg back to
3691         // i1/i8/i16.
3692         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3693             VA.getValVT() == MVT::i16)
3694           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3695 
3696         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3697         MemOpChains.push_back(Store);
3698       }
3699     }
3700   }
3701 
3702   if (!MemOpChains.empty())
3703     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3704 
3705   // Build a sequence of copy-to-reg nodes chained together with token chain
3706   // and flag operands which copy the outgoing args into the appropriate regs.
3707   SDValue InFlag;
3708   for (auto &RegToPass : RegsToPass) {
3709     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3710                              RegToPass.second, InFlag);
3711     InFlag = Chain.getValue(1);
3712   }
3713 
3714   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3715   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3716   // node so that legalize doesn't hack it.
3717   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3718     auto GV = G->getGlobal();
3719     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3720         AArch64II::MO_GOT) {
3721       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3722       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3723     } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3724       assert(Subtarget->isTargetWindows() &&
3725              "Windows is the only supported COFF target");
3726       Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3727     } else {
3728       const GlobalValue *GV = G->getGlobal();
3729       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3730     }
3731   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3732     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3733         Subtarget->isTargetMachO()) {
3734       const char *Sym = S->getSymbol();
3735       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3736       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3737     } else {
3738       const char *Sym = S->getSymbol();
3739       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3740     }
3741   }
3742 
3743   // We don't usually want to end the call-sequence here because we would tidy
3744   // the frame up *after* the call, however in the ABI-changing tail-call case
3745   // we've carefully laid out the parameters so that when sp is reset they'll be
3746   // in the correct location.
3747   if (IsTailCall && !IsSibCall) {
3748     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3749                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3750     InFlag = Chain.getValue(1);
3751   }
3752 
3753   std::vector<SDValue> Ops;
3754   Ops.push_back(Chain);
3755   Ops.push_back(Callee);
3756 
3757   if (IsTailCall) {
3758     // Each tail call may have to adjust the stack by a different amount, so
3759     // this information must travel along with the operation for eventual
3760     // consumption by emitEpilogue.
3761     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3762   }
3763 
3764   // Add argument registers to the end of the list so that they are known live
3765   // into the call.
3766   for (auto &RegToPass : RegsToPass)
3767     Ops.push_back(DAG.getRegister(RegToPass.first,
3768                                   RegToPass.second.getValueType()));
3769 
3770   // Add a register mask operand representing the call-preserved registers.
3771   const uint32_t *Mask;
3772   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3773   if (IsThisReturn) {
3774     // For 'this' returns, use the X0-preserving mask if applicable
3775     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3776     if (!Mask) {
3777       IsThisReturn = false;
3778       Mask = TRI->getCallPreservedMask(MF, CallConv);
3779     }
3780   } else
3781     Mask = TRI->getCallPreservedMask(MF, CallConv);
3782 
3783   if (Subtarget->hasCustomCallingConv())
3784     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3785 
3786   if (TRI->isAnyArgRegReserved(MF))
3787     TRI->emitReservedArgRegCallError(MF);
3788 
3789   assert(Mask && "Missing call preserved mask for calling convention");
3790   Ops.push_back(DAG.getRegisterMask(Mask));
3791 
3792   if (InFlag.getNode())
3793     Ops.push_back(InFlag);
3794 
3795   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3796 
3797   // If we're doing a tall call, use a TC_RETURN here rather than an
3798   // actual call instruction.
3799   if (IsTailCall) {
3800     MF.getFrameInfo().setHasTailCall();
3801     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3802   }
3803 
3804   // Returns a chain and a flag for retval copy to use.
3805   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3806   InFlag = Chain.getValue(1);
3807 
3808   uint64_t CalleePopBytes =
3809       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3810 
3811   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3812                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3813                              InFlag, DL);
3814   if (!Ins.empty())
3815     InFlag = Chain.getValue(1);
3816 
3817   // Handle result values, copying them out of physregs into vregs that we
3818   // return.
3819   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3820                          InVals, IsThisReturn,
3821                          IsThisReturn ? OutVals[0] : SDValue());
3822 }
3823 
3824 bool AArch64TargetLowering::CanLowerReturn(
3825     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3826     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3827   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3828                           ? RetCC_AArch64_WebKit_JS
3829                           : RetCC_AArch64_AAPCS;
3830   SmallVector<CCValAssign, 16> RVLocs;
3831   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3832   return CCInfo.CheckReturn(Outs, RetCC);
3833 }
3834 
3835 SDValue
3836 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3837                                    bool isVarArg,
3838                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3839                                    const SmallVectorImpl<SDValue> &OutVals,
3840                                    const SDLoc &DL, SelectionDAG &DAG) const {
3841   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3842                           ? RetCC_AArch64_WebKit_JS
3843                           : RetCC_AArch64_AAPCS;
3844   SmallVector<CCValAssign, 16> RVLocs;
3845   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3846                  *DAG.getContext());
3847   CCInfo.AnalyzeReturn(Outs, RetCC);
3848 
3849   // Copy the result values into the output registers.
3850   SDValue Flag;
3851   SmallVector<SDValue, 4> RetOps(1, Chain);
3852   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3853        ++i, ++realRVLocIdx) {
3854     CCValAssign &VA = RVLocs[i];
3855     assert(VA.isRegLoc() && "Can only return in registers!");
3856     SDValue Arg = OutVals[realRVLocIdx];
3857 
3858     switch (VA.getLocInfo()) {
3859     default:
3860       llvm_unreachable("Unknown loc info!");
3861     case CCValAssign::Full:
3862       if (Outs[i].ArgVT == MVT::i1) {
3863         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3864         // value. This is strictly redundant on Darwin (which uses "zeroext
3865         // i1"), but will be optimised out before ISel.
3866         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3867         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3868       }
3869       break;
3870     case CCValAssign::BCvt:
3871       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3872       break;
3873     }
3874 
3875     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3876     Flag = Chain.getValue(1);
3877     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3878   }
3879   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3880   const MCPhysReg *I =
3881       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3882   if (I) {
3883     for (; *I; ++I) {
3884       if (AArch64::GPR64RegClass.contains(*I))
3885         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3886       else if (AArch64::FPR64RegClass.contains(*I))
3887         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3888       else
3889         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3890     }
3891   }
3892 
3893   RetOps[0] = Chain; // Update chain.
3894 
3895   // Add the flag if we have it.
3896   if (Flag.getNode())
3897     RetOps.push_back(Flag);
3898 
3899   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3900 }
3901 
3902 //===----------------------------------------------------------------------===//
3903 //  Other Lowering Code
3904 //===----------------------------------------------------------------------===//
3905 
3906 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3907                                              SelectionDAG &DAG,
3908                                              unsigned Flag) const {
3909   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3910                                     N->getOffset(), Flag);
3911 }
3912 
3913 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3914                                              SelectionDAG &DAG,
3915                                              unsigned Flag) const {
3916   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3917 }
3918 
3919 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3920                                              SelectionDAG &DAG,
3921                                              unsigned Flag) const {
3922   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3923                                    N->getOffset(), Flag);
3924 }
3925 
3926 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3927                                              SelectionDAG &DAG,
3928                                              unsigned Flag) const {
3929   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3930 }
3931 
3932 // (loadGOT sym)
3933 template <class NodeTy>
3934 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3935                                       unsigned Flags) const {
3936   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3937   SDLoc DL(N);
3938   EVT Ty = getPointerTy(DAG.getDataLayout());
3939   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
3940   // FIXME: Once remat is capable of dealing with instructions with register
3941   // operands, expand this into two nodes instead of using a wrapper node.
3942   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3943 }
3944 
3945 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3946 template <class NodeTy>
3947 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3948                                             unsigned Flags) const {
3949   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3950   SDLoc DL(N);
3951   EVT Ty = getPointerTy(DAG.getDataLayout());
3952   const unsigned char MO_NC = AArch64II::MO_NC;
3953   return DAG.getNode(
3954       AArch64ISD::WrapperLarge, DL, Ty,
3955       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3956       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3957       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3958       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
3959 }
3960 
3961 // (addlow (adrp %hi(sym)) %lo(sym))
3962 template <class NodeTy>
3963 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3964                                        unsigned Flags) const {
3965   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3966   SDLoc DL(N);
3967   EVT Ty = getPointerTy(DAG.getDataLayout());
3968   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
3969   SDValue Lo = getTargetNode(N, Ty, DAG,
3970                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
3971   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3972   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3973 }
3974 
3975 // (adr sym)
3976 template <class NodeTy>
3977 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
3978                                            unsigned Flags) const {
3979   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
3980   SDLoc DL(N);
3981   EVT Ty = getPointerTy(DAG.getDataLayout());
3982   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
3983   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
3984 }
3985 
3986 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3987                                                   SelectionDAG &DAG) const {
3988   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3989   const GlobalValue *GV = GN->getGlobal();
3990   unsigned char OpFlags =
3991       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3992 
3993   if (OpFlags != AArch64II::MO_NO_FLAG)
3994     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3995            "unexpected offset in global node");
3996 
3997   // This also catches the large code model case for Darwin, and tiny code
3998   // model with got relocations.
3999   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4000     return getGOT(GN, DAG, OpFlags);
4001   }
4002 
4003   SDValue Result;
4004   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4005     Result = getAddrLarge(GN, DAG, OpFlags);
4006   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4007     Result = getAddrTiny(GN, DAG, OpFlags);
4008   } else {
4009     Result = getAddr(GN, DAG, OpFlags);
4010   }
4011   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4012   SDLoc DL(GN);
4013   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4014     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4015                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4016   return Result;
4017 }
4018 
4019 /// Convert a TLS address reference into the correct sequence of loads
4020 /// and calls to compute the variable's address (for Darwin, currently) and
4021 /// return an SDValue containing the final node.
4022 
4023 /// Darwin only has one TLS scheme which must be capable of dealing with the
4024 /// fully general situation, in the worst case. This means:
4025 ///     + "extern __thread" declaration.
4026 ///     + Defined in a possibly unknown dynamic library.
4027 ///
4028 /// The general system is that each __thread variable has a [3 x i64] descriptor
4029 /// which contains information used by the runtime to calculate the address. The
4030 /// only part of this the compiler needs to know about is the first xword, which
4031 /// contains a function pointer that must be called with the address of the
4032 /// entire descriptor in "x0".
4033 ///
4034 /// Since this descriptor may be in a different unit, in general even the
4035 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4036 /// is:
4037 ///     adrp x0, _var@TLVPPAGE
4038 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4039 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4040 ///                                      ; the function pointer
4041 ///     blr x1                           ; Uses descriptor address in x0
4042 ///     ; Address of _var is now in x0.
4043 ///
4044 /// If the address of _var's descriptor *is* known to the linker, then it can
4045 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4046 /// a slight efficiency gain.
4047 SDValue
4048 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4049                                                    SelectionDAG &DAG) const {
4050   assert(Subtarget->isTargetDarwin() &&
4051          "This function expects a Darwin target");
4052 
4053   SDLoc DL(Op);
4054   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4055   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4056 
4057   SDValue TLVPAddr =
4058       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4059   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4060 
4061   // The first entry in the descriptor is a function pointer that we must call
4062   // to obtain the address of the variable.
4063   SDValue Chain = DAG.getEntryNode();
4064   SDValue FuncTLVGet = DAG.getLoad(
4065       MVT::i64, DL, Chain, DescAddr,
4066       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4067       /* Alignment = */ 8,
4068       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4069           MachineMemOperand::MODereferenceable);
4070   Chain = FuncTLVGet.getValue(1);
4071 
4072   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4073   MFI.setAdjustsStack(true);
4074 
4075   // TLS calls preserve all registers except those that absolutely must be
4076   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4077   // silly).
4078   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4079   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4080   if (Subtarget->hasCustomCallingConv())
4081     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4082 
4083   // Finally, we can make the call. This is just a degenerate version of a
4084   // normal AArch64 call node: x0 takes the address of the descriptor, and
4085   // returns the address of the variable in this thread.
4086   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4087   Chain =
4088       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4089                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4090                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4091   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4092 }
4093 
4094 /// When accessing thread-local variables under either the general-dynamic or
4095 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4096 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4097 /// is a function pointer to carry out the resolution.
4098 ///
4099 /// The sequence is:
4100 ///    adrp  x0, :tlsdesc:var
4101 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4102 ///    add   x0, x0, #:tlsdesc_lo12:var
4103 ///    .tlsdesccall var
4104 ///    blr   x1
4105 ///    (TPIDR_EL0 offset now in x0)
4106 ///
4107 ///  The above sequence must be produced unscheduled, to enable the linker to
4108 ///  optimize/relax this sequence.
4109 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4110 ///  above sequence, and expanded really late in the compilation flow, to ensure
4111 ///  the sequence is produced as per above.
4112 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4113                                                       const SDLoc &DL,
4114                                                       SelectionDAG &DAG) const {
4115   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4116 
4117   SDValue Chain = DAG.getEntryNode();
4118   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4119 
4120   Chain =
4121       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4122   SDValue Glue = Chain.getValue(1);
4123 
4124   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4125 }
4126 
4127 SDValue
4128 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4129                                                 SelectionDAG &DAG) const {
4130   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4131   if (getTargetMachine().getCodeModel() == CodeModel::Large)
4132     report_fatal_error("ELF TLS only supported in small memory model");
4133   // Different choices can be made for the maximum size of the TLS area for a
4134   // module. For the small address model, the default TLS size is 16MiB and the
4135   // maximum TLS size is 4GiB.
4136   // FIXME: add -mtls-size command line option and make it control the 16MiB
4137   // vs. 4GiB code sequence generation.
4138   // FIXME: add tiny codemodel support. We currently generate the same code as
4139   // small, which may be larger than needed.
4140   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4141 
4142   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4143 
4144   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4145     if (Model == TLSModel::LocalDynamic)
4146       Model = TLSModel::GeneralDynamic;
4147   }
4148 
4149   SDValue TPOff;
4150   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4151   SDLoc DL(Op);
4152   const GlobalValue *GV = GA->getGlobal();
4153 
4154   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4155 
4156   if (Model == TLSModel::LocalExec) {
4157     SDValue HiVar = DAG.getTargetGlobalAddress(
4158         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4159     SDValue LoVar = DAG.getTargetGlobalAddress(
4160         GV, DL, PtrVT, 0,
4161         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4162 
4163     SDValue TPWithOff_lo =
4164         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4165                                    HiVar,
4166                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4167                 0);
4168     SDValue TPWithOff =
4169         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4170                                    LoVar,
4171                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4172                 0);
4173     return TPWithOff;
4174   } else if (Model == TLSModel::InitialExec) {
4175     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4176     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4177   } else if (Model == TLSModel::LocalDynamic) {
4178     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4179     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4180     // the beginning of the module's TLS region, followed by a DTPREL offset
4181     // calculation.
4182 
4183     // These accesses will need deduplicating if there's more than one.
4184     AArch64FunctionInfo *MFI =
4185         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4186     MFI->incNumLocalDynamicTLSAccesses();
4187 
4188     // The call needs a relocation too for linker relaxation. It doesn't make
4189     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4190     // the address.
4191     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4192                                                   AArch64II::MO_TLS);
4193 
4194     // Now we can calculate the offset from TPIDR_EL0 to this module's
4195     // thread-local area.
4196     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4197 
4198     // Now use :dtprel_whatever: operations to calculate this variable's offset
4199     // in its thread-storage area.
4200     SDValue HiVar = DAG.getTargetGlobalAddress(
4201         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4202     SDValue LoVar = DAG.getTargetGlobalAddress(
4203         GV, DL, MVT::i64, 0,
4204         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4205 
4206     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4207                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4208                     0);
4209     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4210                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4211                     0);
4212   } else if (Model == TLSModel::GeneralDynamic) {
4213     // The call needs a relocation too for linker relaxation. It doesn't make
4214     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4215     // the address.
4216     SDValue SymAddr =
4217         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4218 
4219     // Finally we can make a call to calculate the offset from tpidr_el0.
4220     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4221   } else
4222     llvm_unreachable("Unsupported ELF TLS access model");
4223 
4224   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4225 }
4226 
4227 SDValue
4228 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4229                                                     SelectionDAG &DAG) const {
4230   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4231 
4232   SDValue Chain = DAG.getEntryNode();
4233   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4234   SDLoc DL(Op);
4235 
4236   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4237 
4238   // Load the ThreadLocalStoragePointer from the TEB
4239   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4240   SDValue TLSArray =
4241       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4242   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4243   Chain = TLSArray.getValue(1);
4244 
4245   // Load the TLS index from the C runtime;
4246   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4247   // This also does the same as LOADgot, but using a generic i32 load,
4248   // while LOADgot only loads i64.
4249   SDValue TLSIndexHi =
4250       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4251   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4252       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4253   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4254   SDValue TLSIndex =
4255       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4256   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4257   Chain = TLSIndex.getValue(1);
4258 
4259   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4260   // offset into the TLSArray.
4261   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4262   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4263                              DAG.getConstant(3, DL, PtrVT));
4264   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4265                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4266                             MachinePointerInfo());
4267   Chain = TLS.getValue(1);
4268 
4269   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4270   const GlobalValue *GV = GA->getGlobal();
4271   SDValue TGAHi = DAG.getTargetGlobalAddress(
4272       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4273   SDValue TGALo = DAG.getTargetGlobalAddress(
4274       GV, DL, PtrVT, 0,
4275       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4276 
4277   // Add the offset from the start of the .tls section (section base).
4278   SDValue Addr =
4279       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4280                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4281               0);
4282   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4283   return Addr;
4284 }
4285 
4286 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4287                                                      SelectionDAG &DAG) const {
4288   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4289   if (DAG.getTarget().useEmulatedTLS())
4290     return LowerToTLSEmulatedModel(GA, DAG);
4291 
4292   if (Subtarget->isTargetDarwin())
4293     return LowerDarwinGlobalTLSAddress(Op, DAG);
4294   if (Subtarget->isTargetELF())
4295     return LowerELFGlobalTLSAddress(Op, DAG);
4296   if (Subtarget->isTargetWindows())
4297     return LowerWindowsGlobalTLSAddress(Op, DAG);
4298 
4299   llvm_unreachable("Unexpected platform trying to use TLS");
4300 }
4301 
4302 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4303   SDValue Chain = Op.getOperand(0);
4304   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4305   SDValue LHS = Op.getOperand(2);
4306   SDValue RHS = Op.getOperand(3);
4307   SDValue Dest = Op.getOperand(4);
4308   SDLoc dl(Op);
4309 
4310   // Handle f128 first, since lowering it will result in comparing the return
4311   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4312   // is expecting to deal with.
4313   if (LHS.getValueType() == MVT::f128) {
4314     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4315 
4316     // If softenSetCCOperands returned a scalar, we need to compare the result
4317     // against zero to select between true and false values.
4318     if (!RHS.getNode()) {
4319       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4320       CC = ISD::SETNE;
4321     }
4322   }
4323 
4324   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4325   // instruction.
4326   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4327       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4328     // Only lower legal XALUO ops.
4329     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4330       return SDValue();
4331 
4332     // The actual operation with overflow check.
4333     AArch64CC::CondCode OFCC;
4334     SDValue Value, Overflow;
4335     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4336 
4337     if (CC == ISD::SETNE)
4338       OFCC = getInvertedCondCode(OFCC);
4339     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4340 
4341     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4342                        Overflow);
4343   }
4344 
4345   if (LHS.getValueType().isInteger()) {
4346     assert((LHS.getValueType() == RHS.getValueType()) &&
4347            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4348 
4349     // If the RHS of the comparison is zero, we can potentially fold this
4350     // to a specialized branch.
4351     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4352     if (RHSC && RHSC->getZExtValue() == 0) {
4353       if (CC == ISD::SETEQ) {
4354         // See if we can use a TBZ to fold in an AND as well.
4355         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4356         // out of bounds, a late MI-layer pass rewrites branches.
4357         // 403.gcc is an example that hits this case.
4358         if (LHS.getOpcode() == ISD::AND &&
4359             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4360             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4361           SDValue Test = LHS.getOperand(0);
4362           uint64_t Mask = LHS.getConstantOperandVal(1);
4363           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4364                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4365                              Dest);
4366         }
4367 
4368         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4369       } else if (CC == ISD::SETNE) {
4370         // See if we can use a TBZ to fold in an AND as well.
4371         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4372         // out of bounds, a late MI-layer pass rewrites branches.
4373         // 403.gcc is an example that hits this case.
4374         if (LHS.getOpcode() == ISD::AND &&
4375             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4376             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4377           SDValue Test = LHS.getOperand(0);
4378           uint64_t Mask = LHS.getConstantOperandVal(1);
4379           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4380                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4381                              Dest);
4382         }
4383 
4384         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4385       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4386         // Don't combine AND since emitComparison converts the AND to an ANDS
4387         // (a.k.a. TST) and the test in the test bit and branch instruction
4388         // becomes redundant.  This would also increase register pressure.
4389         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4390         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4391                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4392       }
4393     }
4394     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4395         LHS.getOpcode() != ISD::AND) {
4396       // Don't combine AND since emitComparison converts the AND to an ANDS
4397       // (a.k.a. TST) and the test in the test bit and branch instruction
4398       // becomes redundant.  This would also increase register pressure.
4399       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4400       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4401                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4402     }
4403 
4404     SDValue CCVal;
4405     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4406     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4407                        Cmp);
4408   }
4409 
4410   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4411          LHS.getValueType() == MVT::f64);
4412 
4413   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4414   // clean.  Some of them require two branches to implement.
4415   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4416   AArch64CC::CondCode CC1, CC2;
4417   changeFPCCToAArch64CC(CC, CC1, CC2);
4418   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4419   SDValue BR1 =
4420       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4421   if (CC2 != AArch64CC::AL) {
4422     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4423     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4424                        Cmp);
4425   }
4426 
4427   return BR1;
4428 }
4429 
4430 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4431                                               SelectionDAG &DAG) const {
4432   EVT VT = Op.getValueType();
4433   SDLoc DL(Op);
4434 
4435   SDValue In1 = Op.getOperand(0);
4436   SDValue In2 = Op.getOperand(1);
4437   EVT SrcVT = In2.getValueType();
4438 
4439   if (SrcVT.bitsLT(VT))
4440     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4441   else if (SrcVT.bitsGT(VT))
4442     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4443 
4444   EVT VecVT;
4445   uint64_t EltMask;
4446   SDValue VecVal1, VecVal2;
4447 
4448   auto setVecVal = [&] (int Idx) {
4449     if (!VT.isVector()) {
4450       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4451                                           DAG.getUNDEF(VecVT), In1);
4452       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4453                                           DAG.getUNDEF(VecVT), In2);
4454     } else {
4455       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4456       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4457     }
4458   };
4459 
4460   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4461     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4462     EltMask = 0x80000000ULL;
4463     setVecVal(AArch64::ssub);
4464   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4465     VecVT = MVT::v2i64;
4466 
4467     // We want to materialize a mask with the high bit set, but the AdvSIMD
4468     // immediate moves cannot materialize that in a single instruction for
4469     // 64-bit elements. Instead, materialize zero and then negate it.
4470     EltMask = 0;
4471 
4472     setVecVal(AArch64::dsub);
4473   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4474     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4475     EltMask = 0x8000ULL;
4476     setVecVal(AArch64::hsub);
4477   } else {
4478     llvm_unreachable("Invalid type for copysign!");
4479   }
4480 
4481   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4482 
4483   // If we couldn't materialize the mask above, then the mask vector will be
4484   // the zero vector, and we need to negate it here.
4485   if (VT == MVT::f64 || VT == MVT::v2f64) {
4486     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4487     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4488     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4489   }
4490 
4491   SDValue Sel =
4492       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4493 
4494   if (VT == MVT::f16)
4495     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4496   if (VT == MVT::f32)
4497     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4498   else if (VT == MVT::f64)
4499     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4500   else
4501     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4502 }
4503 
4504 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4505   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4506           Attribute::NoImplicitFloat))
4507     return SDValue();
4508 
4509   if (!Subtarget->hasNEON())
4510     return SDValue();
4511 
4512   // While there is no integer popcount instruction, it can
4513   // be more efficiently lowered to the following sequence that uses
4514   // AdvSIMD registers/instructions as long as the copies to/from
4515   // the AdvSIMD registers are cheap.
4516   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4517   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4518   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4519   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4520   SDValue Val = Op.getOperand(0);
4521   SDLoc DL(Op);
4522   EVT VT = Op.getValueType();
4523 
4524   if (VT == MVT::i32 || VT == MVT::i64) {
4525     if (VT == MVT::i32)
4526       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4527     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4528 
4529     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4530     SDValue UaddLV = DAG.getNode(
4531         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4532         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4533 
4534     if (VT == MVT::i64)
4535       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4536     return UaddLV;
4537   }
4538 
4539   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4540           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4541          "Unexpected type for custom ctpop lowering");
4542 
4543   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4544   Val = DAG.getBitcast(VT8Bit, Val);
4545   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4546 
4547   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4548   unsigned EltSize = 8;
4549   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4550   while (EltSize != VT.getScalarSizeInBits()) {
4551     EltSize *= 2;
4552     NumElts /= 2;
4553     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4554     Val = DAG.getNode(
4555         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4556         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4557   }
4558 
4559   return Val;
4560 }
4561 
4562 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4563 
4564   if (Op.getValueType().isVector())
4565     return LowerVSETCC(Op, DAG);
4566 
4567   SDValue LHS = Op.getOperand(0);
4568   SDValue RHS = Op.getOperand(1);
4569   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4570   SDLoc dl(Op);
4571 
4572   // We chose ZeroOrOneBooleanContents, so use zero and one.
4573   EVT VT = Op.getValueType();
4574   SDValue TVal = DAG.getConstant(1, dl, VT);
4575   SDValue FVal = DAG.getConstant(0, dl, VT);
4576 
4577   // Handle f128 first, since one possible outcome is a normal integer
4578   // comparison which gets picked up by the next if statement.
4579   if (LHS.getValueType() == MVT::f128) {
4580     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4581 
4582     // If softenSetCCOperands returned a scalar, use it.
4583     if (!RHS.getNode()) {
4584       assert(LHS.getValueType() == Op.getValueType() &&
4585              "Unexpected setcc expansion!");
4586       return LHS;
4587     }
4588   }
4589 
4590   if (LHS.getValueType().isInteger()) {
4591     SDValue CCVal;
4592     SDValue Cmp =
4593         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4594 
4595     // Note that we inverted the condition above, so we reverse the order of
4596     // the true and false operands here.  This will allow the setcc to be
4597     // matched to a single CSINC instruction.
4598     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4599   }
4600 
4601   // Now we know we're dealing with FP values.
4602   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4603          LHS.getValueType() == MVT::f64);
4604 
4605   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4606   // and do the comparison.
4607   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4608 
4609   AArch64CC::CondCode CC1, CC2;
4610   changeFPCCToAArch64CC(CC, CC1, CC2);
4611   if (CC2 == AArch64CC::AL) {
4612     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4613     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4614 
4615     // Note that we inverted the condition above, so we reverse the order of
4616     // the true and false operands here.  This will allow the setcc to be
4617     // matched to a single CSINC instruction.
4618     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4619   } else {
4620     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4621     // totally clean.  Some of them require two CSELs to implement.  As is in
4622     // this case, we emit the first CSEL and then emit a second using the output
4623     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4624 
4625     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4626     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4627     SDValue CS1 =
4628         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4629 
4630     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4631     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4632   }
4633 }
4634 
4635 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4636                                               SDValue RHS, SDValue TVal,
4637                                               SDValue FVal, const SDLoc &dl,
4638                                               SelectionDAG &DAG) const {
4639   // Handle f128 first, because it will result in a comparison of some RTLIB
4640   // call result against zero.
4641   if (LHS.getValueType() == MVT::f128) {
4642     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4643 
4644     // If softenSetCCOperands returned a scalar, we need to compare the result
4645     // against zero to select between true and false values.
4646     if (!RHS.getNode()) {
4647       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4648       CC = ISD::SETNE;
4649     }
4650   }
4651 
4652   // Also handle f16, for which we need to do a f32 comparison.
4653   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4654     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4655     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4656   }
4657 
4658   // Next, handle integers.
4659   if (LHS.getValueType().isInteger()) {
4660     assert((LHS.getValueType() == RHS.getValueType()) &&
4661            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4662 
4663     unsigned Opcode = AArch64ISD::CSEL;
4664 
4665     // If both the TVal and the FVal are constants, see if we can swap them in
4666     // order to for a CSINV or CSINC out of them.
4667     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4668     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4669 
4670     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4671       std::swap(TVal, FVal);
4672       std::swap(CTVal, CFVal);
4673       CC = ISD::getSetCCInverse(CC, true);
4674     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4675       std::swap(TVal, FVal);
4676       std::swap(CTVal, CFVal);
4677       CC = ISD::getSetCCInverse(CC, true);
4678     } else if (TVal.getOpcode() == ISD::XOR) {
4679       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4680       // with a CSINV rather than a CSEL.
4681       if (isAllOnesConstant(TVal.getOperand(1))) {
4682         std::swap(TVal, FVal);
4683         std::swap(CTVal, CFVal);
4684         CC = ISD::getSetCCInverse(CC, true);
4685       }
4686     } else if (TVal.getOpcode() == ISD::SUB) {
4687       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4688       // that we can match with a CSNEG rather than a CSEL.
4689       if (isNullConstant(TVal.getOperand(0))) {
4690         std::swap(TVal, FVal);
4691         std::swap(CTVal, CFVal);
4692         CC = ISD::getSetCCInverse(CC, true);
4693       }
4694     } else if (CTVal && CFVal) {
4695       const int64_t TrueVal = CTVal->getSExtValue();
4696       const int64_t FalseVal = CFVal->getSExtValue();
4697       bool Swap = false;
4698 
4699       // If both TVal and FVal are constants, see if FVal is the
4700       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4701       // instead of a CSEL in that case.
4702       if (TrueVal == ~FalseVal) {
4703         Opcode = AArch64ISD::CSINV;
4704       } else if (TrueVal == -FalseVal) {
4705         Opcode = AArch64ISD::CSNEG;
4706       } else if (TVal.getValueType() == MVT::i32) {
4707         // If our operands are only 32-bit wide, make sure we use 32-bit
4708         // arithmetic for the check whether we can use CSINC. This ensures that
4709         // the addition in the check will wrap around properly in case there is
4710         // an overflow (which would not be the case if we do the check with
4711         // 64-bit arithmetic).
4712         const uint32_t TrueVal32 = CTVal->getZExtValue();
4713         const uint32_t FalseVal32 = CFVal->getZExtValue();
4714 
4715         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4716           Opcode = AArch64ISD::CSINC;
4717 
4718           if (TrueVal32 > FalseVal32) {
4719             Swap = true;
4720           }
4721         }
4722         // 64-bit check whether we can use CSINC.
4723       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4724         Opcode = AArch64ISD::CSINC;
4725 
4726         if (TrueVal > FalseVal) {
4727           Swap = true;
4728         }
4729       }
4730 
4731       // Swap TVal and FVal if necessary.
4732       if (Swap) {
4733         std::swap(TVal, FVal);
4734         std::swap(CTVal, CFVal);
4735         CC = ISD::getSetCCInverse(CC, true);
4736       }
4737 
4738       if (Opcode != AArch64ISD::CSEL) {
4739         // Drop FVal since we can get its value by simply inverting/negating
4740         // TVal.
4741         FVal = TVal;
4742       }
4743     }
4744 
4745     // Avoid materializing a constant when possible by reusing a known value in
4746     // a register.  However, don't perform this optimization if the known value
4747     // is one, zero or negative one in the case of a CSEL.  We can always
4748     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4749     // FVal, respectively.
4750     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4751     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4752         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4753       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4754       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4755       // "a != C ? x : a" to avoid materializing C.
4756       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4757         TVal = LHS;
4758       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4759         FVal = LHS;
4760     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4761       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4762       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4763       // avoid materializing C.
4764       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4765       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4766         Opcode = AArch64ISD::CSINV;
4767         TVal = LHS;
4768         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4769       }
4770     }
4771 
4772     SDValue CCVal;
4773     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4774     EVT VT = TVal.getValueType();
4775     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4776   }
4777 
4778   // Now we know we're dealing with FP values.
4779   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4780          LHS.getValueType() == MVT::f64);
4781   assert(LHS.getValueType() == RHS.getValueType());
4782   EVT VT = TVal.getValueType();
4783   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4784 
4785   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4786   // clean.  Some of them require two CSELs to implement.
4787   AArch64CC::CondCode CC1, CC2;
4788   changeFPCCToAArch64CC(CC, CC1, CC2);
4789 
4790   if (DAG.getTarget().Options.UnsafeFPMath) {
4791     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4792     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4793     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4794     if (RHSVal && RHSVal->isZero()) {
4795       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4796       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4797 
4798       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4799           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4800         TVal = LHS;
4801       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4802                CFVal && CFVal->isZero() &&
4803                FVal.getValueType() == LHS.getValueType())
4804         FVal = LHS;
4805     }
4806   }
4807 
4808   // Emit first, and possibly only, CSEL.
4809   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4810   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4811 
4812   // If we need a second CSEL, emit it, using the output of the first as the
4813   // RHS.  We're effectively OR'ing the two CC's together.
4814   if (CC2 != AArch64CC::AL) {
4815     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4816     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4817   }
4818 
4819   // Otherwise, return the output of the first CSEL.
4820   return CS1;
4821 }
4822 
4823 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4824                                               SelectionDAG &DAG) const {
4825   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4826   SDValue LHS = Op.getOperand(0);
4827   SDValue RHS = Op.getOperand(1);
4828   SDValue TVal = Op.getOperand(2);
4829   SDValue FVal = Op.getOperand(3);
4830   SDLoc DL(Op);
4831   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4832 }
4833 
4834 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4835                                            SelectionDAG &DAG) const {
4836   SDValue CCVal = Op->getOperand(0);
4837   SDValue TVal = Op->getOperand(1);
4838   SDValue FVal = Op->getOperand(2);
4839   SDLoc DL(Op);
4840 
4841   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4842   // instruction.
4843   if (isOverflowIntrOpRes(CCVal)) {
4844     // Only lower legal XALUO ops.
4845     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4846       return SDValue();
4847 
4848     AArch64CC::CondCode OFCC;
4849     SDValue Value, Overflow;
4850     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4851     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4852 
4853     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4854                        CCVal, Overflow);
4855   }
4856 
4857   // Lower it the same way as we would lower a SELECT_CC node.
4858   ISD::CondCode CC;
4859   SDValue LHS, RHS;
4860   if (CCVal.getOpcode() == ISD::SETCC) {
4861     LHS = CCVal.getOperand(0);
4862     RHS = CCVal.getOperand(1);
4863     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4864   } else {
4865     LHS = CCVal;
4866     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4867     CC = ISD::SETNE;
4868   }
4869   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4870 }
4871 
4872 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4873                                               SelectionDAG &DAG) const {
4874   // Jump table entries as PC relative offsets. No additional tweaking
4875   // is necessary here. Just get the address of the jump table.
4876   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4877 
4878   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4879       !Subtarget->isTargetMachO()) {
4880     return getAddrLarge(JT, DAG);
4881   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4882     return getAddrTiny(JT, DAG);
4883   }
4884   return getAddr(JT, DAG);
4885 }
4886 
4887 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4888                                           SelectionDAG &DAG) const {
4889   // Jump table entries as PC relative offsets. No additional tweaking
4890   // is necessary here. Just get the address of the jump table.
4891   SDLoc DL(Op);
4892   SDValue JT = Op.getOperand(1);
4893   SDValue Entry = Op.getOperand(2);
4894   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4895 
4896   SDNode *Dest =
4897       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4898                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4899   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4900                      SDValue(Dest, 0));
4901 }
4902 
4903 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4904                                                  SelectionDAG &DAG) const {
4905   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4906 
4907   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4908     // Use the GOT for the large code model on iOS.
4909     if (Subtarget->isTargetMachO()) {
4910       return getGOT(CP, DAG);
4911     }
4912     return getAddrLarge(CP, DAG);
4913   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4914     return getAddrTiny(CP, DAG);
4915   } else {
4916     return getAddr(CP, DAG);
4917   }
4918 }
4919 
4920 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4921                                                SelectionDAG &DAG) const {
4922   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4923   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4924       !Subtarget->isTargetMachO()) {
4925     return getAddrLarge(BA, DAG);
4926   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4927     return getAddrTiny(BA, DAG);
4928   }
4929   return getAddr(BA, DAG);
4930 }
4931 
4932 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4933                                                  SelectionDAG &DAG) const {
4934   AArch64FunctionInfo *FuncInfo =
4935       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4936 
4937   SDLoc DL(Op);
4938   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4939                                  getPointerTy(DAG.getDataLayout()));
4940   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4941   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4942                       MachinePointerInfo(SV));
4943 }
4944 
4945 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4946                                                   SelectionDAG &DAG) const {
4947   AArch64FunctionInfo *FuncInfo =
4948       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4949 
4950   SDLoc DL(Op);
4951   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4952                                      ? FuncInfo->getVarArgsGPRIndex()
4953                                      : FuncInfo->getVarArgsStackIndex(),
4954                                  getPointerTy(DAG.getDataLayout()));
4955   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4956   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4957                       MachinePointerInfo(SV));
4958 }
4959 
4960 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4961                                                 SelectionDAG &DAG) const {
4962   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4963   // Standard, section B.3.
4964   MachineFunction &MF = DAG.getMachineFunction();
4965   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4966   auto PtrVT = getPointerTy(DAG.getDataLayout());
4967   SDLoc DL(Op);
4968 
4969   SDValue Chain = Op.getOperand(0);
4970   SDValue VAList = Op.getOperand(1);
4971   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4972   SmallVector<SDValue, 4> MemOps;
4973 
4974   // void *__stack at offset 0
4975   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4976   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4977                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4978 
4979   // void *__gr_top at offset 8
4980   int GPRSize = FuncInfo->getVarArgsGPRSize();
4981   if (GPRSize > 0) {
4982     SDValue GRTop, GRTopAddr;
4983 
4984     GRTopAddr =
4985         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4986 
4987     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4988     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4989                         DAG.getConstant(GPRSize, DL, PtrVT));
4990 
4991     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4992                                   MachinePointerInfo(SV, 8),
4993                                   /* Alignment = */ 8));
4994   }
4995 
4996   // void *__vr_top at offset 16
4997   int FPRSize = FuncInfo->getVarArgsFPRSize();
4998   if (FPRSize > 0) {
4999     SDValue VRTop, VRTopAddr;
5000     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5001                             DAG.getConstant(16, DL, PtrVT));
5002 
5003     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5004     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5005                         DAG.getConstant(FPRSize, DL, PtrVT));
5006 
5007     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5008                                   MachinePointerInfo(SV, 16),
5009                                   /* Alignment = */ 8));
5010   }
5011 
5012   // int __gr_offs at offset 24
5013   SDValue GROffsAddr =
5014       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5015   MemOps.push_back(DAG.getStore(
5016       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5017       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5018 
5019   // int __vr_offs at offset 28
5020   SDValue VROffsAddr =
5021       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5022   MemOps.push_back(DAG.getStore(
5023       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5024       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5025 
5026   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5027 }
5028 
5029 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5030                                             SelectionDAG &DAG) const {
5031   MachineFunction &MF = DAG.getMachineFunction();
5032 
5033   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5034     return LowerWin64_VASTART(Op, DAG);
5035   else if (Subtarget->isTargetDarwin())
5036     return LowerDarwin_VASTART(Op, DAG);
5037   else
5038     return LowerAAPCS_VASTART(Op, DAG);
5039 }
5040 
5041 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5042                                            SelectionDAG &DAG) const {
5043   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5044   // pointer.
5045   SDLoc DL(Op);
5046   unsigned VaListSize =
5047       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5048   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5049   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5050 
5051   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5052                        Op.getOperand(2),
5053                        DAG.getConstant(VaListSize, DL, MVT::i32),
5054                        8, false, false, false, MachinePointerInfo(DestSV),
5055                        MachinePointerInfo(SrcSV));
5056 }
5057 
5058 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5059   assert(Subtarget->isTargetDarwin() &&
5060          "automatic va_arg instruction only works on Darwin");
5061 
5062   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5063   EVT VT = Op.getValueType();
5064   SDLoc DL(Op);
5065   SDValue Chain = Op.getOperand(0);
5066   SDValue Addr = Op.getOperand(1);
5067   unsigned Align = Op.getConstantOperandVal(3);
5068   auto PtrVT = getPointerTy(DAG.getDataLayout());
5069 
5070   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5071   Chain = VAList.getValue(1);
5072 
5073   if (Align > 8) {
5074     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5075     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5076                          DAG.getConstant(Align - 1, DL, PtrVT));
5077     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5078                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5079   }
5080 
5081   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5082   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5083 
5084   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5085   // up to 64 bits.  At the very least, we have to increase the striding of the
5086   // vaargs list to match this, and for FP values we need to introduce
5087   // FP_ROUND nodes as well.
5088   if (VT.isInteger() && !VT.isVector())
5089     ArgSize = 8;
5090   bool NeedFPTrunc = false;
5091   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5092     ArgSize = 8;
5093     NeedFPTrunc = true;
5094   }
5095 
5096   // Increment the pointer, VAList, to the next vaarg
5097   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5098                                DAG.getConstant(ArgSize, DL, PtrVT));
5099   // Store the incremented VAList to the legalized pointer
5100   SDValue APStore =
5101       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5102 
5103   // Load the actual argument out of the pointer VAList
5104   if (NeedFPTrunc) {
5105     // Load the value as an f64.
5106     SDValue WideFP =
5107         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5108     // Round the value down to an f32.
5109     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5110                                    DAG.getIntPtrConstant(1, DL));
5111     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5112     // Merge the rounded value with the chain output of the load.
5113     return DAG.getMergeValues(Ops, DL);
5114   }
5115 
5116   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5117 }
5118 
5119 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5120                                               SelectionDAG &DAG) const {
5121   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5122   MFI.setFrameAddressIsTaken(true);
5123 
5124   EVT VT = Op.getValueType();
5125   SDLoc DL(Op);
5126   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5127   SDValue FrameAddr =
5128       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5129   while (Depth--)
5130     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5131                             MachinePointerInfo());
5132   return FrameAddr;
5133 }
5134 
5135 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5136                                               SelectionDAG &DAG) const {
5137   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5138 
5139   EVT VT = getPointerTy(DAG.getDataLayout());
5140   SDLoc DL(Op);
5141   int FI = MFI.CreateFixedObject(4, 0, false);
5142   return DAG.getFrameIndex(FI, VT);
5143 }
5144 
5145 // FIXME? Maybe this could be a TableGen attribute on some registers and
5146 // this table could be generated automatically from RegInfo.
5147 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5148                                                   SelectionDAG &DAG) const {
5149   unsigned Reg = StringSwitch<unsigned>(RegName)
5150                        .Case("sp", AArch64::SP)
5151                        .Case("x1", AArch64::X1)
5152                        .Case("w1", AArch64::W1)
5153                        .Case("x2", AArch64::X2)
5154                        .Case("w2", AArch64::W2)
5155                        .Case("x3", AArch64::X3)
5156                        .Case("w3", AArch64::W3)
5157                        .Case("x4", AArch64::X4)
5158                        .Case("w4", AArch64::W4)
5159                        .Case("x5", AArch64::X5)
5160                        .Case("w5", AArch64::W5)
5161                        .Case("x6", AArch64::X6)
5162                        .Case("w6", AArch64::W6)
5163                        .Case("x7", AArch64::X7)
5164                        .Case("w7", AArch64::W7)
5165                        .Case("x18", AArch64::X18)
5166                        .Case("w18", AArch64::W18)
5167                        .Case("x20", AArch64::X20)
5168                        .Case("w20", AArch64::W20)
5169                        .Default(0);
5170   if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5171       !Subtarget->isXRegisterReserved(1)) ||
5172       ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5173       !Subtarget->isXRegisterReserved(2)) ||
5174       ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5175       !Subtarget->isXRegisterReserved(3)) ||
5176       ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5177       !Subtarget->isXRegisterReserved(4)) ||
5178       ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5179       !Subtarget->isXRegisterReserved(5)) ||
5180       ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5181       !Subtarget->isXRegisterReserved(6)) ||
5182       ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5183       !Subtarget->isXRegisterReserved(7)) ||
5184       ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5185       !Subtarget->isXRegisterReserved(18)) ||
5186       ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
5187       !Subtarget->isXRegisterReserved(20)))
5188     Reg = 0;
5189   if (Reg)
5190     return Reg;
5191   report_fatal_error(Twine("Invalid register name \""
5192                               + StringRef(RegName)  + "\"."));
5193 }
5194 
5195 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5196                                                      SelectionDAG &DAG) const {
5197   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5198 
5199   EVT VT = Op.getValueType();
5200   SDLoc DL(Op);
5201 
5202   SDValue FrameAddr =
5203       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5204   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5205 
5206   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5207 }
5208 
5209 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5210                                                SelectionDAG &DAG) const {
5211   MachineFunction &MF = DAG.getMachineFunction();
5212   MachineFrameInfo &MFI = MF.getFrameInfo();
5213   MFI.setReturnAddressIsTaken(true);
5214 
5215   EVT VT = Op.getValueType();
5216   SDLoc DL(Op);
5217   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5218   if (Depth) {
5219     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5220     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5221     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5222                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5223                        MachinePointerInfo());
5224   }
5225 
5226   // Return LR, which contains the return address. Mark it an implicit live-in.
5227   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5228   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5229 }
5230 
5231 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5232 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5233 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5234                                                     SelectionDAG &DAG) const {
5235   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5236   EVT VT = Op.getValueType();
5237   unsigned VTBits = VT.getSizeInBits();
5238   SDLoc dl(Op);
5239   SDValue ShOpLo = Op.getOperand(0);
5240   SDValue ShOpHi = Op.getOperand(1);
5241   SDValue ShAmt = Op.getOperand(2);
5242   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5243 
5244   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5245 
5246   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5247                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5248   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5249 
5250   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5251   // is "undef". We wanted 0, so CSEL it directly.
5252   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5253                                ISD::SETEQ, dl, DAG);
5254   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5255   HiBitsForLo =
5256       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5257                   HiBitsForLo, CCVal, Cmp);
5258 
5259   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5260                                    DAG.getConstant(VTBits, dl, MVT::i64));
5261 
5262   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5263   SDValue LoForNormalShift =
5264       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5265 
5266   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5267                        dl, DAG);
5268   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5269   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5270   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5271                            LoForNormalShift, CCVal, Cmp);
5272 
5273   // AArch64 shifts larger than the register width are wrapped rather than
5274   // clamped, so we can't just emit "hi >> x".
5275   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5276   SDValue HiForBigShift =
5277       Opc == ISD::SRA
5278           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5279                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5280           : DAG.getConstant(0, dl, VT);
5281   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5282                            HiForNormalShift, CCVal, Cmp);
5283 
5284   SDValue Ops[2] = { Lo, Hi };
5285   return DAG.getMergeValues(Ops, dl);
5286 }
5287 
5288 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5289 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5290 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5291                                                    SelectionDAG &DAG) const {
5292   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5293   EVT VT = Op.getValueType();
5294   unsigned VTBits = VT.getSizeInBits();
5295   SDLoc dl(Op);
5296   SDValue ShOpLo = Op.getOperand(0);
5297   SDValue ShOpHi = Op.getOperand(1);
5298   SDValue ShAmt = Op.getOperand(2);
5299 
5300   assert(Op.getOpcode() == ISD::SHL_PARTS);
5301   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5302                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5303   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5304 
5305   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5306   // is "undef". We wanted 0, so CSEL it directly.
5307   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5308                                ISD::SETEQ, dl, DAG);
5309   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5310   LoBitsForHi =
5311       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5312                   LoBitsForHi, CCVal, Cmp);
5313 
5314   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5315                                    DAG.getConstant(VTBits, dl, MVT::i64));
5316   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5317   SDValue HiForNormalShift =
5318       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5319 
5320   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5321 
5322   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5323                        dl, DAG);
5324   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5325   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5326                            HiForNormalShift, CCVal, Cmp);
5327 
5328   // AArch64 shifts of larger than register sizes are wrapped rather than
5329   // clamped, so we can't just emit "lo << a" if a is too big.
5330   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5331   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5332   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5333                            LoForNormalShift, CCVal, Cmp);
5334 
5335   SDValue Ops[2] = { Lo, Hi };
5336   return DAG.getMergeValues(Ops, dl);
5337 }
5338 
5339 bool AArch64TargetLowering::isOffsetFoldingLegal(
5340     const GlobalAddressSDNode *GA) const {
5341   // Offsets are folded in the DAG combine rather than here so that we can
5342   // intelligently choose an offset based on the uses.
5343   return false;
5344 }
5345 
5346 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5347   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5348   // FIXME: We should be able to handle f128 as well with a clever lowering.
5349   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5350                           (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
5351     LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString() << " imm value: 0\n");
5352     return true;
5353   }
5354 
5355   bool IsLegal = false;
5356   SmallString<128> ImmStrVal;
5357   Imm.toString(ImmStrVal);
5358 
5359   if (VT == MVT::f64)
5360     IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
5361   else if (VT == MVT::f32)
5362     IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
5363   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5364     IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
5365 
5366   if (IsLegal) {
5367     LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString()
5368                       << " imm value: " << ImmStrVal << "\n");
5369     return true;
5370   }
5371 
5372   LLVM_DEBUG(dbgs() << "Illegal " << VT.getEVTString()
5373                     << " imm value: " << ImmStrVal << "\n");
5374   return false;
5375 }
5376 
5377 //===----------------------------------------------------------------------===//
5378 //                          AArch64 Optimization Hooks
5379 //===----------------------------------------------------------------------===//
5380 
5381 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5382                            SDValue Operand, SelectionDAG &DAG,
5383                            int &ExtraSteps) {
5384   EVT VT = Operand.getValueType();
5385   if (ST->hasNEON() &&
5386       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5387        VT == MVT::f32 || VT == MVT::v1f32 ||
5388        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5389     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5390       // For the reciprocal estimates, convergence is quadratic, so the number
5391       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5392       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5393       // the result for float (23 mantissa bits) is 2 and for double (52
5394       // mantissa bits) is 3.
5395       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5396 
5397     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5398   }
5399 
5400   return SDValue();
5401 }
5402 
5403 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5404                                                SelectionDAG &DAG, int Enabled,
5405                                                int &ExtraSteps,
5406                                                bool &UseOneConst,
5407                                                bool Reciprocal) const {
5408   if (Enabled == ReciprocalEstimate::Enabled ||
5409       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5410     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5411                                        DAG, ExtraSteps)) {
5412       SDLoc DL(Operand);
5413       EVT VT = Operand.getValueType();
5414 
5415       SDNodeFlags Flags;
5416       Flags.setAllowReassociation(true);
5417 
5418       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5419       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5420       for (int i = ExtraSteps; i > 0; --i) {
5421         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5422                                    Flags);
5423         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5424         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5425       }
5426       if (!Reciprocal) {
5427         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5428                                       VT);
5429         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5430         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5431 
5432         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5433         // Correct the result if the operand is 0.0.
5434         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5435                                VT, Eq, Operand, Estimate);
5436       }
5437 
5438       ExtraSteps = 0;
5439       return Estimate;
5440     }
5441 
5442   return SDValue();
5443 }
5444 
5445 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5446                                                 SelectionDAG &DAG, int Enabled,
5447                                                 int &ExtraSteps) const {
5448   if (Enabled == ReciprocalEstimate::Enabled)
5449     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5450                                        DAG, ExtraSteps)) {
5451       SDLoc DL(Operand);
5452       EVT VT = Operand.getValueType();
5453 
5454       SDNodeFlags Flags;
5455       Flags.setAllowReassociation(true);
5456 
5457       // Newton reciprocal iteration: E * (2 - X * E)
5458       // AArch64 reciprocal iteration instruction: (2 - M * N)
5459       for (int i = ExtraSteps; i > 0; --i) {
5460         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5461                                    Estimate, Flags);
5462         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5463       }
5464 
5465       ExtraSteps = 0;
5466       return Estimate;
5467     }
5468 
5469   return SDValue();
5470 }
5471 
5472 //===----------------------------------------------------------------------===//
5473 //                          AArch64 Inline Assembly Support
5474 //===----------------------------------------------------------------------===//
5475 
5476 // Table of Constraints
5477 // TODO: This is the current set of constraints supported by ARM for the
5478 // compiler, not all of them may make sense.
5479 //
5480 // r - A general register
5481 // w - An FP/SIMD register of some size in the range v0-v31
5482 // x - An FP/SIMD register of some size in the range v0-v15
5483 // I - Constant that can be used with an ADD instruction
5484 // J - Constant that can be used with a SUB instruction
5485 // K - Constant that can be used with a 32-bit logical instruction
5486 // L - Constant that can be used with a 64-bit logical instruction
5487 // M - Constant that can be used as a 32-bit MOV immediate
5488 // N - Constant that can be used as a 64-bit MOV immediate
5489 // Q - A memory reference with base register and no offset
5490 // S - A symbolic address
5491 // Y - Floating point constant zero
5492 // Z - Integer constant zero
5493 //
5494 //   Note that general register operands will be output using their 64-bit x
5495 // register name, whatever the size of the variable, unless the asm operand
5496 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5497 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5498 // %q modifier.
5499 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5500   // At this point, we have to lower this constraint to something else, so we
5501   // lower it to an "r" or "w". However, by doing this we will force the result
5502   // to be in register, while the X constraint is much more permissive.
5503   //
5504   // Although we are correct (we are free to emit anything, without
5505   // constraints), we might break use cases that would expect us to be more
5506   // efficient and emit something else.
5507   if (!Subtarget->hasFPARMv8())
5508     return "r";
5509 
5510   if (ConstraintVT.isFloatingPoint())
5511     return "w";
5512 
5513   if (ConstraintVT.isVector() &&
5514      (ConstraintVT.getSizeInBits() == 64 ||
5515       ConstraintVT.getSizeInBits() == 128))
5516     return "w";
5517 
5518   return "r";
5519 }
5520 
5521 /// getConstraintType - Given a constraint letter, return the type of
5522 /// constraint it is for this target.
5523 AArch64TargetLowering::ConstraintType
5524 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5525   if (Constraint.size() == 1) {
5526     switch (Constraint[0]) {
5527     default:
5528       break;
5529     case 'z':
5530       return C_Other;
5531     case 'x':
5532     case 'w':
5533       return C_RegisterClass;
5534     // An address with a single base register. Due to the way we
5535     // currently handle addresses it is the same as 'r'.
5536     case 'Q':
5537       return C_Memory;
5538     case 'S': // A symbolic address
5539       return C_Other;
5540     }
5541   }
5542   return TargetLowering::getConstraintType(Constraint);
5543 }
5544 
5545 /// Examine constraint type and operand type and determine a weight value.
5546 /// This object must already have been set up with the operand type
5547 /// and the current alternative constraint selected.
5548 TargetLowering::ConstraintWeight
5549 AArch64TargetLowering::getSingleConstraintMatchWeight(
5550     AsmOperandInfo &info, const char *constraint) const {
5551   ConstraintWeight weight = CW_Invalid;
5552   Value *CallOperandVal = info.CallOperandVal;
5553   // If we don't have a value, we can't do a match,
5554   // but allow it at the lowest weight.
5555   if (!CallOperandVal)
5556     return CW_Default;
5557   Type *type = CallOperandVal->getType();
5558   // Look at the constraint type.
5559   switch (*constraint) {
5560   default:
5561     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5562     break;
5563   case 'x':
5564   case 'w':
5565     if (type->isFloatingPointTy() || type->isVectorTy())
5566       weight = CW_Register;
5567     break;
5568   case 'z':
5569     weight = CW_Constant;
5570     break;
5571   }
5572   return weight;
5573 }
5574 
5575 std::pair<unsigned, const TargetRegisterClass *>
5576 AArch64TargetLowering::getRegForInlineAsmConstraint(
5577     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5578   if (Constraint.size() == 1) {
5579     switch (Constraint[0]) {
5580     case 'r':
5581       if (VT.getSizeInBits() == 64)
5582         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5583       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5584     case 'w':
5585       if (!Subtarget->hasFPARMv8())
5586         break;
5587       if (VT.getSizeInBits() == 16)
5588         return std::make_pair(0U, &AArch64::FPR16RegClass);
5589       if (VT.getSizeInBits() == 32)
5590         return std::make_pair(0U, &AArch64::FPR32RegClass);
5591       if (VT.getSizeInBits() == 64)
5592         return std::make_pair(0U, &AArch64::FPR64RegClass);
5593       if (VT.getSizeInBits() == 128)
5594         return std::make_pair(0U, &AArch64::FPR128RegClass);
5595       break;
5596     // The instructions that this constraint is designed for can
5597     // only take 128-bit registers so just use that regclass.
5598     case 'x':
5599       if (!Subtarget->hasFPARMv8())
5600         break;
5601       if (VT.getSizeInBits() == 128)
5602         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5603       break;
5604     }
5605   }
5606   if (StringRef("{cc}").equals_lower(Constraint))
5607     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5608 
5609   // Use the default implementation in TargetLowering to convert the register
5610   // constraint into a member of a register class.
5611   std::pair<unsigned, const TargetRegisterClass *> Res;
5612   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5613 
5614   // Not found as a standard register?
5615   if (!Res.second) {
5616     unsigned Size = Constraint.size();
5617     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5618         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5619       int RegNo;
5620       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5621       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5622         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5623         // By default we'll emit v0-v31 for this unless there's a modifier where
5624         // we'll emit the correct register as well.
5625         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5626           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5627           Res.second = &AArch64::FPR64RegClass;
5628         } else {
5629           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5630           Res.second = &AArch64::FPR128RegClass;
5631         }
5632       }
5633     }
5634   }
5635 
5636   if (Res.second && !Subtarget->hasFPARMv8() &&
5637       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5638       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5639     return std::make_pair(0U, nullptr);
5640 
5641   return Res;
5642 }
5643 
5644 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5645 /// vector.  If it is invalid, don't add anything to Ops.
5646 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5647     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5648     SelectionDAG &DAG) const {
5649   SDValue Result;
5650 
5651   // Currently only support length 1 constraints.
5652   if (Constraint.length() != 1)
5653     return;
5654 
5655   char ConstraintLetter = Constraint[0];
5656   switch (ConstraintLetter) {
5657   default:
5658     break;
5659 
5660   // This set of constraints deal with valid constants for various instructions.
5661   // Validate and return a target constant for them if we can.
5662   case 'z': {
5663     // 'z' maps to xzr or wzr so it needs an input of 0.
5664     if (!isNullConstant(Op))
5665       return;
5666 
5667     if (Op.getValueType() == MVT::i64)
5668       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5669     else
5670       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5671     break;
5672   }
5673   case 'S': {
5674     // An absolute symbolic address or label reference.
5675     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5676       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5677                                           GA->getValueType(0));
5678     } else if (const BlockAddressSDNode *BA =
5679                    dyn_cast<BlockAddressSDNode>(Op)) {
5680       Result =
5681           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5682     } else if (const ExternalSymbolSDNode *ES =
5683                    dyn_cast<ExternalSymbolSDNode>(Op)) {
5684       Result =
5685           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5686     } else
5687       return;
5688     break;
5689   }
5690 
5691   case 'I':
5692   case 'J':
5693   case 'K':
5694   case 'L':
5695   case 'M':
5696   case 'N':
5697     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5698     if (!C)
5699       return;
5700 
5701     // Grab the value and do some validation.
5702     uint64_t CVal = C->getZExtValue();
5703     switch (ConstraintLetter) {
5704     // The I constraint applies only to simple ADD or SUB immediate operands:
5705     // i.e. 0 to 4095 with optional shift by 12
5706     // The J constraint applies only to ADD or SUB immediates that would be
5707     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5708     // instruction [or vice versa], in other words -1 to -4095 with optional
5709     // left shift by 12.
5710     case 'I':
5711       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5712         break;
5713       return;
5714     case 'J': {
5715       uint64_t NVal = -C->getSExtValue();
5716       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5717         CVal = C->getSExtValue();
5718         break;
5719       }
5720       return;
5721     }
5722     // The K and L constraints apply *only* to logical immediates, including
5723     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5724     // been removed and MOV should be used). So these constraints have to
5725     // distinguish between bit patterns that are valid 32-bit or 64-bit
5726     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5727     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5728     // versa.
5729     case 'K':
5730       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5731         break;
5732       return;
5733     case 'L':
5734       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5735         break;
5736       return;
5737     // The M and N constraints are a superset of K and L respectively, for use
5738     // with the MOV (immediate) alias. As well as the logical immediates they
5739     // also match 32 or 64-bit immediates that can be loaded either using a
5740     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5741     // (M) or 64-bit 0x1234000000000000 (N) etc.
5742     // As a note some of this code is liberally stolen from the asm parser.
5743     case 'M': {
5744       if (!isUInt<32>(CVal))
5745         return;
5746       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5747         break;
5748       if ((CVal & 0xFFFF) == CVal)
5749         break;
5750       if ((CVal & 0xFFFF0000ULL) == CVal)
5751         break;
5752       uint64_t NCVal = ~(uint32_t)CVal;
5753       if ((NCVal & 0xFFFFULL) == NCVal)
5754         break;
5755       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5756         break;
5757       return;
5758     }
5759     case 'N': {
5760       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5761         break;
5762       if ((CVal & 0xFFFFULL) == CVal)
5763         break;
5764       if ((CVal & 0xFFFF0000ULL) == CVal)
5765         break;
5766       if ((CVal & 0xFFFF00000000ULL) == CVal)
5767         break;
5768       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5769         break;
5770       uint64_t NCVal = ~CVal;
5771       if ((NCVal & 0xFFFFULL) == NCVal)
5772         break;
5773       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5774         break;
5775       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5776         break;
5777       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5778         break;
5779       return;
5780     }
5781     default:
5782       return;
5783     }
5784 
5785     // All assembler immediates are 64-bit integers.
5786     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5787     break;
5788   }
5789 
5790   if (Result.getNode()) {
5791     Ops.push_back(Result);
5792     return;
5793   }
5794 
5795   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5796 }
5797 
5798 //===----------------------------------------------------------------------===//
5799 //                     AArch64 Advanced SIMD Support
5800 //===----------------------------------------------------------------------===//
5801 
5802 /// WidenVector - Given a value in the V64 register class, produce the
5803 /// equivalent value in the V128 register class.
5804 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5805   EVT VT = V64Reg.getValueType();
5806   unsigned NarrowSize = VT.getVectorNumElements();
5807   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5808   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5809   SDLoc DL(V64Reg);
5810 
5811   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5812                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5813 }
5814 
5815 /// getExtFactor - Determine the adjustment factor for the position when
5816 /// generating an "extract from vector registers" instruction.
5817 static unsigned getExtFactor(SDValue &V) {
5818   EVT EltType = V.getValueType().getVectorElementType();
5819   return EltType.getSizeInBits() / 8;
5820 }
5821 
5822 /// NarrowVector - Given a value in the V128 register class, produce the
5823 /// equivalent value in the V64 register class.
5824 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5825   EVT VT = V128Reg.getValueType();
5826   unsigned WideSize = VT.getVectorNumElements();
5827   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5828   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5829   SDLoc DL(V128Reg);
5830 
5831   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5832 }
5833 
5834 // Gather data to see if the operation can be modelled as a
5835 // shuffle in combination with VEXTs.
5836 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5837                                                   SelectionDAG &DAG) const {
5838   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5839   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
5840   SDLoc dl(Op);
5841   EVT VT = Op.getValueType();
5842   unsigned NumElts = VT.getVectorNumElements();
5843 
5844   struct ShuffleSourceInfo {
5845     SDValue Vec;
5846     unsigned MinElt;
5847     unsigned MaxElt;
5848 
5849     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5850     // be compatible with the shuffle we intend to construct. As a result
5851     // ShuffleVec will be some sliding window into the original Vec.
5852     SDValue ShuffleVec;
5853 
5854     // Code should guarantee that element i in Vec starts at element "WindowBase
5855     // + i * WindowScale in ShuffleVec".
5856     int WindowBase;
5857     int WindowScale;
5858 
5859     ShuffleSourceInfo(SDValue Vec)
5860       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5861           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5862 
5863     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5864   };
5865 
5866   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5867   // node.
5868   SmallVector<ShuffleSourceInfo, 2> Sources;
5869   for (unsigned i = 0; i < NumElts; ++i) {
5870     SDValue V = Op.getOperand(i);
5871     if (V.isUndef())
5872       continue;
5873     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5874              !isa<ConstantSDNode>(V.getOperand(1))) {
5875       LLVM_DEBUG(
5876           dbgs() << "Reshuffle failed: "
5877                     "a shuffle can only come from building a vector from "
5878                     "various elements of other vectors, provided their "
5879                     "indices are constant\n");
5880       return SDValue();
5881     }
5882 
5883     // Add this element source to the list if it's not already there.
5884     SDValue SourceVec = V.getOperand(0);
5885     auto Source = find(Sources, SourceVec);
5886     if (Source == Sources.end())
5887       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5888 
5889     // Update the minimum and maximum lane number seen.
5890     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5891     Source->MinElt = std::min(Source->MinElt, EltNo);
5892     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5893   }
5894 
5895   if (Sources.size() > 2) {
5896     LLVM_DEBUG(
5897         dbgs() << "Reshuffle failed: currently only do something sane when at "
5898                   "most two source vectors are involved\n");
5899     return SDValue();
5900   }
5901 
5902   // Find out the smallest element size among result and two sources, and use
5903   // it as element size to build the shuffle_vector.
5904   EVT SmallestEltTy = VT.getVectorElementType();
5905   for (auto &Source : Sources) {
5906     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5907     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5908       SmallestEltTy = SrcEltTy;
5909     }
5910   }
5911   unsigned ResMultiplier =
5912       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5913   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5914   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5915 
5916   // If the source vector is too wide or too narrow, we may nevertheless be able
5917   // to construct a compatible shuffle either by concatenating it with UNDEF or
5918   // extracting a suitable range of elements.
5919   for (auto &Src : Sources) {
5920     EVT SrcVT = Src.ShuffleVec.getValueType();
5921 
5922     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5923       continue;
5924 
5925     // This stage of the search produces a source with the same element type as
5926     // the original, but with a total width matching the BUILD_VECTOR output.
5927     EVT EltVT = SrcVT.getVectorElementType();
5928     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5929     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5930 
5931     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5932       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5933       // We can pad out the smaller vector for free, so if it's part of a
5934       // shuffle...
5935       Src.ShuffleVec =
5936           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5937                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5938       continue;
5939     }
5940 
5941     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5942 
5943     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5944       LLVM_DEBUG(
5945           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
5946       return SDValue();
5947     }
5948 
5949     if (Src.MinElt >= NumSrcElts) {
5950       // The extraction can just take the second half
5951       Src.ShuffleVec =
5952           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5953                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5954       Src.WindowBase = -NumSrcElts;
5955     } else if (Src.MaxElt < NumSrcElts) {
5956       // The extraction can just take the first half
5957       Src.ShuffleVec =
5958           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5959                       DAG.getConstant(0, dl, MVT::i64));
5960     } else {
5961       // An actual VEXT is needed
5962       SDValue VEXTSrc1 =
5963           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5964                       DAG.getConstant(0, dl, MVT::i64));
5965       SDValue VEXTSrc2 =
5966           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5967                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5968       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5969 
5970       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5971                                    VEXTSrc2,
5972                                    DAG.getConstant(Imm, dl, MVT::i32));
5973       Src.WindowBase = -Src.MinElt;
5974     }
5975   }
5976 
5977   // Another possible incompatibility occurs from the vector element types. We
5978   // can fix this by bitcasting the source vectors to the same type we intend
5979   // for the shuffle.
5980   for (auto &Src : Sources) {
5981     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5982     if (SrcEltTy == SmallestEltTy)
5983       continue;
5984     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5985     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5986     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5987     Src.WindowBase *= Src.WindowScale;
5988   }
5989 
5990   // Final sanity check before we try to actually produce a shuffle.
5991   LLVM_DEBUG(for (auto Src
5992                   : Sources)
5993                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
5994 
5995   // The stars all align, our next step is to produce the mask for the shuffle.
5996   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5997   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5998   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5999     SDValue Entry = Op.getOperand(i);
6000     if (Entry.isUndef())
6001       continue;
6002 
6003     auto Src = find(Sources, Entry.getOperand(0));
6004     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6005 
6006     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6007     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6008     // segment.
6009     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6010     int BitsDefined =
6011         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6012     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6013 
6014     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6015     // starting at the appropriate offset.
6016     int *LaneMask = &Mask[i * ResMultiplier];
6017 
6018     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6019     ExtractBase += NumElts * (Src - Sources.begin());
6020     for (int j = 0; j < LanesDefined; ++j)
6021       LaneMask[j] = ExtractBase + j;
6022   }
6023 
6024   // Final check before we try to produce nonsense...
6025   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6026     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6027     return SDValue();
6028   }
6029 
6030   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6031   for (unsigned i = 0; i < Sources.size(); ++i)
6032     ShuffleOps[i] = Sources[i].ShuffleVec;
6033 
6034   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6035                                          ShuffleOps[1], Mask);
6036   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6037 
6038   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6039              dbgs() << "Reshuffle, creating node: "; V.dump(););
6040 
6041   return V;
6042 }
6043 
6044 // check if an EXT instruction can handle the shuffle mask when the
6045 // vector sources of the shuffle are the same.
6046 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6047   unsigned NumElts = VT.getVectorNumElements();
6048 
6049   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6050   if (M[0] < 0)
6051     return false;
6052 
6053   Imm = M[0];
6054 
6055   // If this is a VEXT shuffle, the immediate value is the index of the first
6056   // element.  The other shuffle indices must be the successive elements after
6057   // the first one.
6058   unsigned ExpectedElt = Imm;
6059   for (unsigned i = 1; i < NumElts; ++i) {
6060     // Increment the expected index.  If it wraps around, just follow it
6061     // back to index zero and keep going.
6062     ++ExpectedElt;
6063     if (ExpectedElt == NumElts)
6064       ExpectedElt = 0;
6065 
6066     if (M[i] < 0)
6067       continue; // ignore UNDEF indices
6068     if (ExpectedElt != static_cast<unsigned>(M[i]))
6069       return false;
6070   }
6071 
6072   return true;
6073 }
6074 
6075 // check if an EXT instruction can handle the shuffle mask when the
6076 // vector sources of the shuffle are different.
6077 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6078                       unsigned &Imm) {
6079   // Look for the first non-undef element.
6080   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6081 
6082   // Benefit form APInt to handle overflow when calculating expected element.
6083   unsigned NumElts = VT.getVectorNumElements();
6084   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6085   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6086   // The following shuffle indices must be the successive elements after the
6087   // first real element.
6088   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6089       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6090   if (FirstWrongElt != M.end())
6091     return false;
6092 
6093   // The index of an EXT is the first element if it is not UNDEF.
6094   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6095   // value of the first element.  E.g.
6096   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6097   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6098   // ExpectedElt is the last mask index plus 1.
6099   Imm = ExpectedElt.getZExtValue();
6100 
6101   // There are two difference cases requiring to reverse input vectors.
6102   // For example, for vector <4 x i32> we have the following cases,
6103   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6104   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6105   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6106   // to reverse two input vectors.
6107   if (Imm < NumElts)
6108     ReverseEXT = true;
6109   else
6110     Imm -= NumElts;
6111 
6112   return true;
6113 }
6114 
6115 /// isREVMask - Check if a vector shuffle corresponds to a REV
6116 /// instruction with the specified blocksize.  (The order of the elements
6117 /// within each block of the vector is reversed.)
6118 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6119   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6120          "Only possible block sizes for REV are: 16, 32, 64");
6121 
6122   unsigned EltSz = VT.getScalarSizeInBits();
6123   if (EltSz == 64)
6124     return false;
6125 
6126   unsigned NumElts = VT.getVectorNumElements();
6127   unsigned BlockElts = M[0] + 1;
6128   // If the first shuffle index is UNDEF, be optimistic.
6129   if (M[0] < 0)
6130     BlockElts = BlockSize / EltSz;
6131 
6132   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6133     return false;
6134 
6135   for (unsigned i = 0; i < NumElts; ++i) {
6136     if (M[i] < 0)
6137       continue; // ignore UNDEF indices
6138     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6139       return false;
6140   }
6141 
6142   return true;
6143 }
6144 
6145 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6146   unsigned NumElts = VT.getVectorNumElements();
6147   WhichResult = (M[0] == 0 ? 0 : 1);
6148   unsigned Idx = WhichResult * NumElts / 2;
6149   for (unsigned i = 0; i != NumElts; i += 2) {
6150     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6151         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6152       return false;
6153     Idx += 1;
6154   }
6155 
6156   return true;
6157 }
6158 
6159 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6160   unsigned NumElts = VT.getVectorNumElements();
6161   WhichResult = (M[0] == 0 ? 0 : 1);
6162   for (unsigned i = 0; i != NumElts; ++i) {
6163     if (M[i] < 0)
6164       continue; // ignore UNDEF indices
6165     if ((unsigned)M[i] != 2 * i + WhichResult)
6166       return false;
6167   }
6168 
6169   return true;
6170 }
6171 
6172 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6173   unsigned NumElts = VT.getVectorNumElements();
6174   WhichResult = (M[0] == 0 ? 0 : 1);
6175   for (unsigned i = 0; i < NumElts; i += 2) {
6176     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6177         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6178       return false;
6179   }
6180   return true;
6181 }
6182 
6183 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6184 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6185 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6186 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6187   unsigned NumElts = VT.getVectorNumElements();
6188   WhichResult = (M[0] == 0 ? 0 : 1);
6189   unsigned Idx = WhichResult * NumElts / 2;
6190   for (unsigned i = 0; i != NumElts; i += 2) {
6191     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6192         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6193       return false;
6194     Idx += 1;
6195   }
6196 
6197   return true;
6198 }
6199 
6200 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6201 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6202 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6203 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6204   unsigned Half = VT.getVectorNumElements() / 2;
6205   WhichResult = (M[0] == 0 ? 0 : 1);
6206   for (unsigned j = 0; j != 2; ++j) {
6207     unsigned Idx = WhichResult;
6208     for (unsigned i = 0; i != Half; ++i) {
6209       int MIdx = M[i + j * Half];
6210       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6211         return false;
6212       Idx += 2;
6213     }
6214   }
6215 
6216   return true;
6217 }
6218 
6219 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6220 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6221 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6222 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6223   unsigned NumElts = VT.getVectorNumElements();
6224   WhichResult = (M[0] == 0 ? 0 : 1);
6225   for (unsigned i = 0; i < NumElts; i += 2) {
6226     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6227         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6228       return false;
6229   }
6230   return true;
6231 }
6232 
6233 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6234                       bool &DstIsLeft, int &Anomaly) {
6235   if (M.size() != static_cast<size_t>(NumInputElements))
6236     return false;
6237 
6238   int NumLHSMatch = 0, NumRHSMatch = 0;
6239   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6240 
6241   for (int i = 0; i < NumInputElements; ++i) {
6242     if (M[i] == -1) {
6243       ++NumLHSMatch;
6244       ++NumRHSMatch;
6245       continue;
6246     }
6247 
6248     if (M[i] == i)
6249       ++NumLHSMatch;
6250     else
6251       LastLHSMismatch = i;
6252 
6253     if (M[i] == i + NumInputElements)
6254       ++NumRHSMatch;
6255     else
6256       LastRHSMismatch = i;
6257   }
6258 
6259   if (NumLHSMatch == NumInputElements - 1) {
6260     DstIsLeft = true;
6261     Anomaly = LastLHSMismatch;
6262     return true;
6263   } else if (NumRHSMatch == NumInputElements - 1) {
6264     DstIsLeft = false;
6265     Anomaly = LastRHSMismatch;
6266     return true;
6267   }
6268 
6269   return false;
6270 }
6271 
6272 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6273   if (VT.getSizeInBits() != 128)
6274     return false;
6275 
6276   unsigned NumElts = VT.getVectorNumElements();
6277 
6278   for (int I = 0, E = NumElts / 2; I != E; I++) {
6279     if (Mask[I] != I)
6280       return false;
6281   }
6282 
6283   int Offset = NumElts / 2;
6284   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6285     if (Mask[I] != I + SplitLHS * Offset)
6286       return false;
6287   }
6288 
6289   return true;
6290 }
6291 
6292 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6293   SDLoc DL(Op);
6294   EVT VT = Op.getValueType();
6295   SDValue V0 = Op.getOperand(0);
6296   SDValue V1 = Op.getOperand(1);
6297   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6298 
6299   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6300       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6301     return SDValue();
6302 
6303   bool SplitV0 = V0.getValueSizeInBits() == 128;
6304 
6305   if (!isConcatMask(Mask, VT, SplitV0))
6306     return SDValue();
6307 
6308   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6309                                 VT.getVectorNumElements() / 2);
6310   if (SplitV0) {
6311     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6312                      DAG.getConstant(0, DL, MVT::i64));
6313   }
6314   if (V1.getValueSizeInBits() == 128) {
6315     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6316                      DAG.getConstant(0, DL, MVT::i64));
6317   }
6318   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6319 }
6320 
6321 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6322 /// the specified operations to build the shuffle.
6323 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6324                                       SDValue RHS, SelectionDAG &DAG,
6325                                       const SDLoc &dl) {
6326   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6327   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6328   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6329 
6330   enum {
6331     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6332     OP_VREV,
6333     OP_VDUP0,
6334     OP_VDUP1,
6335     OP_VDUP2,
6336     OP_VDUP3,
6337     OP_VEXT1,
6338     OP_VEXT2,
6339     OP_VEXT3,
6340     OP_VUZPL, // VUZP, left result
6341     OP_VUZPR, // VUZP, right result
6342     OP_VZIPL, // VZIP, left result
6343     OP_VZIPR, // VZIP, right result
6344     OP_VTRNL, // VTRN, left result
6345     OP_VTRNR  // VTRN, right result
6346   };
6347 
6348   if (OpNum == OP_COPY) {
6349     if (LHSID == (1 * 9 + 2) * 9 + 3)
6350       return LHS;
6351     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6352     return RHS;
6353   }
6354 
6355   SDValue OpLHS, OpRHS;
6356   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6357   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6358   EVT VT = OpLHS.getValueType();
6359 
6360   switch (OpNum) {
6361   default:
6362     llvm_unreachable("Unknown shuffle opcode!");
6363   case OP_VREV:
6364     // VREV divides the vector in half and swaps within the half.
6365     if (VT.getVectorElementType() == MVT::i32 ||
6366         VT.getVectorElementType() == MVT::f32)
6367       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6368     // vrev <4 x i16> -> REV32
6369     if (VT.getVectorElementType() == MVT::i16 ||
6370         VT.getVectorElementType() == MVT::f16)
6371       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6372     // vrev <4 x i8> -> REV16
6373     assert(VT.getVectorElementType() == MVT::i8);
6374     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6375   case OP_VDUP0:
6376   case OP_VDUP1:
6377   case OP_VDUP2:
6378   case OP_VDUP3: {
6379     EVT EltTy = VT.getVectorElementType();
6380     unsigned Opcode;
6381     if (EltTy == MVT::i8)
6382       Opcode = AArch64ISD::DUPLANE8;
6383     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6384       Opcode = AArch64ISD::DUPLANE16;
6385     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6386       Opcode = AArch64ISD::DUPLANE32;
6387     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6388       Opcode = AArch64ISD::DUPLANE64;
6389     else
6390       llvm_unreachable("Invalid vector element type?");
6391 
6392     if (VT.getSizeInBits() == 64)
6393       OpLHS = WidenVector(OpLHS, DAG);
6394     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6395     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6396   }
6397   case OP_VEXT1:
6398   case OP_VEXT2:
6399   case OP_VEXT3: {
6400     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6401     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6402                        DAG.getConstant(Imm, dl, MVT::i32));
6403   }
6404   case OP_VUZPL:
6405     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6406                        OpRHS);
6407   case OP_VUZPR:
6408     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6409                        OpRHS);
6410   case OP_VZIPL:
6411     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6412                        OpRHS);
6413   case OP_VZIPR:
6414     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6415                        OpRHS);
6416   case OP_VTRNL:
6417     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6418                        OpRHS);
6419   case OP_VTRNR:
6420     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6421                        OpRHS);
6422   }
6423 }
6424 
6425 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6426                            SelectionDAG &DAG) {
6427   // Check to see if we can use the TBL instruction.
6428   SDValue V1 = Op.getOperand(0);
6429   SDValue V2 = Op.getOperand(1);
6430   SDLoc DL(Op);
6431 
6432   EVT EltVT = Op.getValueType().getVectorElementType();
6433   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6434 
6435   SmallVector<SDValue, 8> TBLMask;
6436   for (int Val : ShuffleMask) {
6437     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6438       unsigned Offset = Byte + Val * BytesPerElt;
6439       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6440     }
6441   }
6442 
6443   MVT IndexVT = MVT::v8i8;
6444   unsigned IndexLen = 8;
6445   if (Op.getValueSizeInBits() == 128) {
6446     IndexVT = MVT::v16i8;
6447     IndexLen = 16;
6448   }
6449 
6450   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6451   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6452 
6453   SDValue Shuffle;
6454   if (V2.getNode()->isUndef()) {
6455     if (IndexLen == 8)
6456       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6457     Shuffle = DAG.getNode(
6458         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6459         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6460         DAG.getBuildVector(IndexVT, DL,
6461                            makeArrayRef(TBLMask.data(), IndexLen)));
6462   } else {
6463     if (IndexLen == 8) {
6464       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6465       Shuffle = DAG.getNode(
6466           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6467           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6468           DAG.getBuildVector(IndexVT, DL,
6469                              makeArrayRef(TBLMask.data(), IndexLen)));
6470     } else {
6471       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6472       // cannot currently represent the register constraints on the input
6473       // table registers.
6474       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6475       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6476       //                   IndexLen));
6477       Shuffle = DAG.getNode(
6478           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6479           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6480           V2Cst, DAG.getBuildVector(IndexVT, DL,
6481                                     makeArrayRef(TBLMask.data(), IndexLen)));
6482     }
6483   }
6484   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6485 }
6486 
6487 static unsigned getDUPLANEOp(EVT EltType) {
6488   if (EltType == MVT::i8)
6489     return AArch64ISD::DUPLANE8;
6490   if (EltType == MVT::i16 || EltType == MVT::f16)
6491     return AArch64ISD::DUPLANE16;
6492   if (EltType == MVT::i32 || EltType == MVT::f32)
6493     return AArch64ISD::DUPLANE32;
6494   if (EltType == MVT::i64 || EltType == MVT::f64)
6495     return AArch64ISD::DUPLANE64;
6496 
6497   llvm_unreachable("Invalid vector element type?");
6498 }
6499 
6500 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6501                                                    SelectionDAG &DAG) const {
6502   SDLoc dl(Op);
6503   EVT VT = Op.getValueType();
6504 
6505   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6506 
6507   // Convert shuffles that are directly supported on NEON to target-specific
6508   // DAG nodes, instead of keeping them as shuffles and matching them again
6509   // during code selection.  This is more efficient and avoids the possibility
6510   // of inconsistencies between legalization and selection.
6511   ArrayRef<int> ShuffleMask = SVN->getMask();
6512 
6513   SDValue V1 = Op.getOperand(0);
6514   SDValue V2 = Op.getOperand(1);
6515 
6516   if (SVN->isSplat()) {
6517     int Lane = SVN->getSplatIndex();
6518     // If this is undef splat, generate it via "just" vdup, if possible.
6519     if (Lane == -1)
6520       Lane = 0;
6521 
6522     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6523       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6524                          V1.getOperand(0));
6525     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6526     // constant. If so, we can just reference the lane's definition directly.
6527     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6528         !isa<ConstantSDNode>(V1.getOperand(Lane)))
6529       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6530 
6531     // Otherwise, duplicate from the lane of the input vector.
6532     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6533 
6534     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6535     // to make a vector of the same size as this SHUFFLE. We can ignore the
6536     // extract entirely, and canonicalise the concat using WidenVector.
6537     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6538       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6539       V1 = V1.getOperand(0);
6540     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6541       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6542       Lane -= Idx * VT.getVectorNumElements() / 2;
6543       V1 = WidenVector(V1.getOperand(Idx), DAG);
6544     } else if (VT.getSizeInBits() == 64)
6545       V1 = WidenVector(V1, DAG);
6546 
6547     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6548   }
6549 
6550   if (isREVMask(ShuffleMask, VT, 64))
6551     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6552   if (isREVMask(ShuffleMask, VT, 32))
6553     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6554   if (isREVMask(ShuffleMask, VT, 16))
6555     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6556 
6557   bool ReverseEXT = false;
6558   unsigned Imm;
6559   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6560     if (ReverseEXT)
6561       std::swap(V1, V2);
6562     Imm *= getExtFactor(V1);
6563     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6564                        DAG.getConstant(Imm, dl, MVT::i32));
6565   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6566     Imm *= getExtFactor(V1);
6567     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6568                        DAG.getConstant(Imm, dl, MVT::i32));
6569   }
6570 
6571   unsigned WhichResult;
6572   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6573     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6574     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6575   }
6576   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6577     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6578     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6579   }
6580   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6581     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6582     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6583   }
6584 
6585   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6586     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6587     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6588   }
6589   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6590     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6591     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6592   }
6593   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6594     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6595     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6596   }
6597 
6598   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6599     return Concat;
6600 
6601   bool DstIsLeft;
6602   int Anomaly;
6603   int NumInputElements = V1.getValueType().getVectorNumElements();
6604   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6605     SDValue DstVec = DstIsLeft ? V1 : V2;
6606     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6607 
6608     SDValue SrcVec = V1;
6609     int SrcLane = ShuffleMask[Anomaly];
6610     if (SrcLane >= NumInputElements) {
6611       SrcVec = V2;
6612       SrcLane -= VT.getVectorNumElements();
6613     }
6614     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6615 
6616     EVT ScalarVT = VT.getVectorElementType();
6617 
6618     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6619       ScalarVT = MVT::i32;
6620 
6621     return DAG.getNode(
6622         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6623         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6624         DstLaneV);
6625   }
6626 
6627   // If the shuffle is not directly supported and it has 4 elements, use
6628   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6629   unsigned NumElts = VT.getVectorNumElements();
6630   if (NumElts == 4) {
6631     unsigned PFIndexes[4];
6632     for (unsigned i = 0; i != 4; ++i) {
6633       if (ShuffleMask[i] < 0)
6634         PFIndexes[i] = 8;
6635       else
6636         PFIndexes[i] = ShuffleMask[i];
6637     }
6638 
6639     // Compute the index in the perfect shuffle table.
6640     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6641                             PFIndexes[2] * 9 + PFIndexes[3];
6642     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6643     unsigned Cost = (PFEntry >> 30);
6644 
6645     if (Cost <= 4)
6646       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6647   }
6648 
6649   return GenerateTBL(Op, ShuffleMask, DAG);
6650 }
6651 
6652 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6653                                APInt &UndefBits) {
6654   EVT VT = BVN->getValueType(0);
6655   APInt SplatBits, SplatUndef;
6656   unsigned SplatBitSize;
6657   bool HasAnyUndefs;
6658   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6659     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6660 
6661     for (unsigned i = 0; i < NumSplats; ++i) {
6662       CnstBits <<= SplatBitSize;
6663       UndefBits <<= SplatBitSize;
6664       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6665       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6666     }
6667 
6668     return true;
6669   }
6670 
6671   return false;
6672 }
6673 
6674 // Try 64-bit splatted SIMD immediate.
6675 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6676                                  const APInt &Bits) {
6677   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6678     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6679     EVT VT = Op.getValueType();
6680     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6681 
6682     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6683       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6684 
6685       SDLoc dl(Op);
6686       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6687                                 DAG.getConstant(Value, dl, MVT::i32));
6688       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6689     }
6690   }
6691 
6692   return SDValue();
6693 }
6694 
6695 // Try 32-bit splatted SIMD immediate.
6696 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6697                                   const APInt &Bits,
6698                                   const SDValue *LHS = nullptr) {
6699   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6700     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6701     EVT VT = Op.getValueType();
6702     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6703     bool isAdvSIMDModImm = false;
6704     uint64_t Shift;
6705 
6706     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6707       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6708       Shift = 0;
6709     }
6710     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6711       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6712       Shift = 8;
6713     }
6714     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6715       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6716       Shift = 16;
6717     }
6718     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6719       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6720       Shift = 24;
6721     }
6722 
6723     if (isAdvSIMDModImm) {
6724       SDLoc dl(Op);
6725       SDValue Mov;
6726 
6727       if (LHS)
6728         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6729                           DAG.getConstant(Value, dl, MVT::i32),
6730                           DAG.getConstant(Shift, dl, MVT::i32));
6731       else
6732         Mov = DAG.getNode(NewOp, dl, MovTy,
6733                           DAG.getConstant(Value, dl, MVT::i32),
6734                           DAG.getConstant(Shift, dl, MVT::i32));
6735 
6736       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6737     }
6738   }
6739 
6740   return SDValue();
6741 }
6742 
6743 // Try 16-bit splatted SIMD immediate.
6744 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6745                                   const APInt &Bits,
6746                                   const SDValue *LHS = nullptr) {
6747   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6748     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6749     EVT VT = Op.getValueType();
6750     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6751     bool isAdvSIMDModImm = false;
6752     uint64_t Shift;
6753 
6754     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6755       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6756       Shift = 0;
6757     }
6758     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6759       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6760       Shift = 8;
6761     }
6762 
6763     if (isAdvSIMDModImm) {
6764       SDLoc dl(Op);
6765       SDValue Mov;
6766 
6767       if (LHS)
6768         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6769                           DAG.getConstant(Value, dl, MVT::i32),
6770                           DAG.getConstant(Shift, dl, MVT::i32));
6771       else
6772         Mov = DAG.getNode(NewOp, dl, MovTy,
6773                           DAG.getConstant(Value, dl, MVT::i32),
6774                           DAG.getConstant(Shift, dl, MVT::i32));
6775 
6776       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6777     }
6778   }
6779 
6780   return SDValue();
6781 }
6782 
6783 // Try 32-bit splatted SIMD immediate with shifted ones.
6784 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6785                                     SelectionDAG &DAG, const APInt &Bits) {
6786   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6787     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6788     EVT VT = Op.getValueType();
6789     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6790     bool isAdvSIMDModImm = false;
6791     uint64_t Shift;
6792 
6793     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6794       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6795       Shift = 264;
6796     }
6797     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6798       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6799       Shift = 272;
6800     }
6801 
6802     if (isAdvSIMDModImm) {
6803       SDLoc dl(Op);
6804       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6805                                 DAG.getConstant(Value, dl, MVT::i32),
6806                                 DAG.getConstant(Shift, dl, MVT::i32));
6807       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6808     }
6809   }
6810 
6811   return SDValue();
6812 }
6813 
6814 // Try 8-bit splatted SIMD immediate.
6815 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6816                                  const APInt &Bits) {
6817   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6818     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6819     EVT VT = Op.getValueType();
6820     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6821 
6822     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6823       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6824 
6825       SDLoc dl(Op);
6826       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6827                                 DAG.getConstant(Value, dl, MVT::i32));
6828       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6829     }
6830   }
6831 
6832   return SDValue();
6833 }
6834 
6835 // Try FP splatted SIMD immediate.
6836 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6837                                   const APInt &Bits) {
6838   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6839     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6840     EVT VT = Op.getValueType();
6841     bool isWide = (VT.getSizeInBits() == 128);
6842     MVT MovTy;
6843     bool isAdvSIMDModImm = false;
6844 
6845     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6846       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6847       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6848     }
6849     else if (isWide &&
6850              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6851       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6852       MovTy = MVT::v2f64;
6853     }
6854 
6855     if (isAdvSIMDModImm) {
6856       SDLoc dl(Op);
6857       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6858                                 DAG.getConstant(Value, dl, MVT::i32));
6859       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6860     }
6861   }
6862 
6863   return SDValue();
6864 }
6865 
6866 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6867                                               SelectionDAG &DAG) const {
6868   SDValue LHS = Op.getOperand(0);
6869   EVT VT = Op.getValueType();
6870 
6871   BuildVectorSDNode *BVN =
6872       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6873   if (!BVN) {
6874     // AND commutes, so try swapping the operands.
6875     LHS = Op.getOperand(1);
6876     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6877   }
6878   if (!BVN)
6879     return Op;
6880 
6881   APInt DefBits(VT.getSizeInBits(), 0);
6882   APInt UndefBits(VT.getSizeInBits(), 0);
6883   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6884     SDValue NewOp;
6885 
6886     // We only have BIC vector immediate instruction, which is and-not.
6887     DefBits = ~DefBits;
6888     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6889                                     DefBits, &LHS)) ||
6890         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6891                                     DefBits, &LHS)))
6892       return NewOp;
6893 
6894     UndefBits = ~UndefBits;
6895     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6896                                     UndefBits, &LHS)) ||
6897         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6898                                     UndefBits, &LHS)))
6899       return NewOp;
6900   }
6901 
6902   // We can always fall back to a non-immediate AND.
6903   return Op;
6904 }
6905 
6906 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6907 // consists of only the same constant int value, returned in reference arg
6908 // ConstVal
6909 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6910                                      uint64_t &ConstVal) {
6911   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6912   if (!Bvec)
6913     return false;
6914   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6915   if (!FirstElt)
6916     return false;
6917   EVT VT = Bvec->getValueType(0);
6918   unsigned NumElts = VT.getVectorNumElements();
6919   for (unsigned i = 1; i < NumElts; ++i)
6920     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6921       return false;
6922   ConstVal = FirstElt->getZExtValue();
6923   return true;
6924 }
6925 
6926 static unsigned getIntrinsicID(const SDNode *N) {
6927   unsigned Opcode = N->getOpcode();
6928   switch (Opcode) {
6929   default:
6930     return Intrinsic::not_intrinsic;
6931   case ISD::INTRINSIC_WO_CHAIN: {
6932     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6933     if (IID < Intrinsic::num_intrinsics)
6934       return IID;
6935     return Intrinsic::not_intrinsic;
6936   }
6937   }
6938 }
6939 
6940 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6941 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6942 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6943 // Also, logical shift right -> sri, with the same structure.
6944 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6945   EVT VT = N->getValueType(0);
6946 
6947   if (!VT.isVector())
6948     return SDValue();
6949 
6950   SDLoc DL(N);
6951 
6952   // Is the first op an AND?
6953   const SDValue And = N->getOperand(0);
6954   if (And.getOpcode() != ISD::AND)
6955     return SDValue();
6956 
6957   // Is the second op an shl or lshr?
6958   SDValue Shift = N->getOperand(1);
6959   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6960   // or AArch64ISD::VLSHR vector, #shift
6961   unsigned ShiftOpc = Shift.getOpcode();
6962   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6963     return SDValue();
6964   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6965 
6966   // Is the shift amount constant?
6967   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6968   if (!C2node)
6969     return SDValue();
6970 
6971   // Is the and mask vector all constant?
6972   uint64_t C1;
6973   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6974     return SDValue();
6975 
6976   // Is C1 == ~C2, taking into account how much one can shift elements of a
6977   // particular size?
6978   uint64_t C2 = C2node->getZExtValue();
6979   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6980   if (C2 > ElemSizeInBits)
6981     return SDValue();
6982   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6983   if ((C1 & ElemMask) != (~C2 & ElemMask))
6984     return SDValue();
6985 
6986   SDValue X = And.getOperand(0);
6987   SDValue Y = Shift.getOperand(0);
6988 
6989   unsigned Intrin =
6990       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6991   SDValue ResultSLI =
6992       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6993                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6994                   Shift.getOperand(1));
6995 
6996   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6997   LLVM_DEBUG(N->dump(&DAG));
6998   LLVM_DEBUG(dbgs() << "into: \n");
6999   LLVM_DEBUG(ResultSLI->dump(&DAG));
7000 
7001   ++NumShiftInserts;
7002   return ResultSLI;
7003 }
7004 
7005 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7006                                              SelectionDAG &DAG) const {
7007   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7008   if (EnableAArch64SlrGeneration) {
7009     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7010       return Res;
7011   }
7012 
7013   EVT VT = Op.getValueType();
7014 
7015   SDValue LHS = Op.getOperand(0);
7016   BuildVectorSDNode *BVN =
7017       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7018   if (!BVN) {
7019     // OR commutes, so try swapping the operands.
7020     LHS = Op.getOperand(1);
7021     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7022   }
7023   if (!BVN)
7024     return Op;
7025 
7026   APInt DefBits(VT.getSizeInBits(), 0);
7027   APInt UndefBits(VT.getSizeInBits(), 0);
7028   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7029     SDValue NewOp;
7030 
7031     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7032                                     DefBits, &LHS)) ||
7033         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7034                                     DefBits, &LHS)))
7035       return NewOp;
7036 
7037     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7038                                     UndefBits, &LHS)) ||
7039         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7040                                     UndefBits, &LHS)))
7041       return NewOp;
7042   }
7043 
7044   // We can always fall back to a non-immediate OR.
7045   return Op;
7046 }
7047 
7048 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7049 // be truncated to fit element width.
7050 static SDValue NormalizeBuildVector(SDValue Op,
7051                                     SelectionDAG &DAG) {
7052   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7053   SDLoc dl(Op);
7054   EVT VT = Op.getValueType();
7055   EVT EltTy= VT.getVectorElementType();
7056 
7057   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7058     return Op;
7059 
7060   SmallVector<SDValue, 16> Ops;
7061   for (SDValue Lane : Op->ops()) {
7062     // For integer vectors, type legalization would have promoted the
7063     // operands already. Otherwise, if Op is a floating-point splat
7064     // (with operands cast to integers), then the only possibilities
7065     // are constants and UNDEFs.
7066     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7067       APInt LowBits(EltTy.getSizeInBits(),
7068                     CstLane->getZExtValue());
7069       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7070     } else if (Lane.getNode()->isUndef()) {
7071       Lane = DAG.getUNDEF(MVT::i32);
7072     } else {
7073       assert(Lane.getValueType() == MVT::i32 &&
7074              "Unexpected BUILD_VECTOR operand type");
7075     }
7076     Ops.push_back(Lane);
7077   }
7078   return DAG.getBuildVector(VT, dl, Ops);
7079 }
7080 
7081 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7082   EVT VT = Op.getValueType();
7083 
7084   APInt DefBits(VT.getSizeInBits(), 0);
7085   APInt UndefBits(VT.getSizeInBits(), 0);
7086   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7087   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7088     SDValue NewOp;
7089     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7090         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7091         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7092         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7093         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7094         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7095       return NewOp;
7096 
7097     DefBits = ~DefBits;
7098     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7099         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7100         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7101       return NewOp;
7102 
7103     DefBits = UndefBits;
7104     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7105         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7106         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7107         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7108         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7109         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7110       return NewOp;
7111 
7112     DefBits = ~UndefBits;
7113     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7114         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7115         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7116       return NewOp;
7117   }
7118 
7119   return SDValue();
7120 }
7121 
7122 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7123                                                  SelectionDAG &DAG) const {
7124   EVT VT = Op.getValueType();
7125 
7126   // Try to build a simple constant vector.
7127   Op = NormalizeBuildVector(Op, DAG);
7128   if (VT.isInteger()) {
7129     // Certain vector constants, used to express things like logical NOT and
7130     // arithmetic NEG, are passed through unmodified.  This allows special
7131     // patterns for these operations to match, which will lower these constants
7132     // to whatever is proven necessary.
7133     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7134     if (BVN->isConstant())
7135       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7136         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7137         APInt Val(BitSize,
7138                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7139         if (Val.isNullValue() || Val.isAllOnesValue())
7140           return Op;
7141       }
7142   }
7143 
7144   if (SDValue V = ConstantBuildVector(Op, DAG))
7145     return V;
7146 
7147   // Scan through the operands to find some interesting properties we can
7148   // exploit:
7149   //   1) If only one value is used, we can use a DUP, or
7150   //   2) if only the low element is not undef, we can just insert that, or
7151   //   3) if only one constant value is used (w/ some non-constant lanes),
7152   //      we can splat the constant value into the whole vector then fill
7153   //      in the non-constant lanes.
7154   //   4) FIXME: If different constant values are used, but we can intelligently
7155   //             select the values we'll be overwriting for the non-constant
7156   //             lanes such that we can directly materialize the vector
7157   //             some other way (MOVI, e.g.), we can be sneaky.
7158   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7159   SDLoc dl(Op);
7160   unsigned NumElts = VT.getVectorNumElements();
7161   bool isOnlyLowElement = true;
7162   bool usesOnlyOneValue = true;
7163   bool usesOnlyOneConstantValue = true;
7164   bool isConstant = true;
7165   bool AllLanesExtractElt = true;
7166   unsigned NumConstantLanes = 0;
7167   SDValue Value;
7168   SDValue ConstantValue;
7169   for (unsigned i = 0; i < NumElts; ++i) {
7170     SDValue V = Op.getOperand(i);
7171     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7172       AllLanesExtractElt = false;
7173     if (V.isUndef())
7174       continue;
7175     if (i > 0)
7176       isOnlyLowElement = false;
7177     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7178       isConstant = false;
7179 
7180     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7181       ++NumConstantLanes;
7182       if (!ConstantValue.getNode())
7183         ConstantValue = V;
7184       else if (ConstantValue != V)
7185         usesOnlyOneConstantValue = false;
7186     }
7187 
7188     if (!Value.getNode())
7189       Value = V;
7190     else if (V != Value)
7191       usesOnlyOneValue = false;
7192   }
7193 
7194   if (!Value.getNode()) {
7195     LLVM_DEBUG(
7196         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7197     return DAG.getUNDEF(VT);
7198   }
7199 
7200   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7201   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7202   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7203   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7204     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7205                          "SCALAR_TO_VECTOR node\n");
7206     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7207   }
7208 
7209   if (AllLanesExtractElt) {
7210     SDNode *Vector = nullptr;
7211     bool Even = false;
7212     bool Odd = false;
7213     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7214     // the Odd pattern <1,3,5,...>.
7215     for (unsigned i = 0; i < NumElts; ++i) {
7216       SDValue V = Op.getOperand(i);
7217       const SDNode *N = V.getNode();
7218       if (!isa<ConstantSDNode>(N->getOperand(1)))
7219         break;
7220       SDValue N0 = N->getOperand(0);
7221 
7222       // All elements are extracted from the same vector.
7223       if (!Vector) {
7224         Vector = N0.getNode();
7225         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7226         // BUILD_VECTOR.
7227         if (VT.getVectorElementType() !=
7228             N0.getValueType().getVectorElementType())
7229           break;
7230       } else if (Vector != N0.getNode()) {
7231         Odd = false;
7232         Even = false;
7233         break;
7234       }
7235 
7236       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7237       // indices <1,3,5,...>.
7238       uint64_t Val = N->getConstantOperandVal(1);
7239       if (Val == 2 * i) {
7240         Even = true;
7241         continue;
7242       }
7243       if (Val - 1 == 2 * i) {
7244         Odd = true;
7245         continue;
7246       }
7247 
7248       // Something does not match: abort.
7249       Odd = false;
7250       Even = false;
7251       break;
7252     }
7253     if (Even || Odd) {
7254       SDValue LHS =
7255           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7256                       DAG.getConstant(0, dl, MVT::i64));
7257       SDValue RHS =
7258           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7259                       DAG.getConstant(NumElts, dl, MVT::i64));
7260 
7261       if (Even && !Odd)
7262         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7263                            RHS);
7264       if (Odd && !Even)
7265         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7266                            RHS);
7267     }
7268   }
7269 
7270   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7271   // i32 and try again.
7272   if (usesOnlyOneValue) {
7273     if (!isConstant) {
7274       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7275           Value.getValueType() != VT) {
7276         LLVM_DEBUG(
7277             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7278         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7279       }
7280 
7281       // This is actually a DUPLANExx operation, which keeps everything vectory.
7282 
7283       SDValue Lane = Value.getOperand(1);
7284       Value = Value.getOperand(0);
7285       if (Value.getValueSizeInBits() == 64) {
7286         LLVM_DEBUG(
7287             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7288                       "widening it\n");
7289         Value = WidenVector(Value, DAG);
7290       }
7291 
7292       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7293       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7294     }
7295 
7296     if (VT.getVectorElementType().isFloatingPoint()) {
7297       SmallVector<SDValue, 8> Ops;
7298       EVT EltTy = VT.getVectorElementType();
7299       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7300               "Unsupported floating-point vector type");
7301       LLVM_DEBUG(
7302           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7303                     "BITCASTS, and try again\n");
7304       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7305       for (unsigned i = 0; i < NumElts; ++i)
7306         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7307       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7308       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7309       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7310                  Val.dump(););
7311       Val = LowerBUILD_VECTOR(Val, DAG);
7312       if (Val.getNode())
7313         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7314     }
7315   }
7316 
7317   // If there was only one constant value used and for more than one lane,
7318   // start by splatting that value, then replace the non-constant lanes. This
7319   // is better than the default, which will perform a separate initialization
7320   // for each lane.
7321   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7322     // Firstly, try to materialize the splat constant.
7323     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7324             Val = ConstantBuildVector(Vec, DAG);
7325     if (!Val) {
7326       // Otherwise, materialize the constant and splat it.
7327       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7328       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7329     }
7330 
7331     // Now insert the non-constant lanes.
7332     for (unsigned i = 0; i < NumElts; ++i) {
7333       SDValue V = Op.getOperand(i);
7334       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7335       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7336         // Note that type legalization likely mucked about with the VT of the
7337         // source operand, so we may have to convert it here before inserting.
7338         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7339     }
7340     return Val;
7341   }
7342 
7343   // This will generate a load from the constant pool.
7344   if (isConstant) {
7345     LLVM_DEBUG(
7346         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7347                   "expansion\n");
7348     return SDValue();
7349   }
7350 
7351   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7352   if (NumElts >= 4) {
7353     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7354       return shuffle;
7355   }
7356 
7357   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7358   // know the default expansion would otherwise fall back on something even
7359   // worse. For a vector with one or two non-undef values, that's
7360   // scalar_to_vector for the elements followed by a shuffle (provided the
7361   // shuffle is valid for the target) and materialization element by element
7362   // on the stack followed by a load for everything else.
7363   if (!isConstant && !usesOnlyOneValue) {
7364     LLVM_DEBUG(
7365         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7366                   "of INSERT_VECTOR_ELT\n");
7367 
7368     SDValue Vec = DAG.getUNDEF(VT);
7369     SDValue Op0 = Op.getOperand(0);
7370     unsigned i = 0;
7371 
7372     // Use SCALAR_TO_VECTOR for lane zero to
7373     // a) Avoid a RMW dependency on the full vector register, and
7374     // b) Allow the register coalescer to fold away the copy if the
7375     //    value is already in an S or D register, and we're forced to emit an
7376     //    INSERT_SUBREG that we can't fold anywhere.
7377     //
7378     // We also allow types like i8 and i16 which are illegal scalar but legal
7379     // vector element types. After type-legalization the inserted value is
7380     // extended (i32) and it is safe to cast them to the vector type by ignoring
7381     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7382     if (!Op0.isUndef()) {
7383       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7384       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7385       ++i;
7386     }
7387     LLVM_DEBUG(if (i < NumElts) dbgs()
7388                    << "Creating nodes for the other vector elements:\n";);
7389     for (; i < NumElts; ++i) {
7390       SDValue V = Op.getOperand(i);
7391       if (V.isUndef())
7392         continue;
7393       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7394       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7395     }
7396     return Vec;
7397   }
7398 
7399   LLVM_DEBUG(
7400       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7401                 "better alternative\n");
7402   return SDValue();
7403 }
7404 
7405 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7406                                                       SelectionDAG &DAG) const {
7407   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7408 
7409   // Check for non-constant or out of range lane.
7410   EVT VT = Op.getOperand(0).getValueType();
7411   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7412   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7413     return SDValue();
7414 
7415 
7416   // Insertion/extraction are legal for V128 types.
7417   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7418       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7419       VT == MVT::v8f16)
7420     return Op;
7421 
7422   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7423       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7424     return SDValue();
7425 
7426   // For V64 types, we perform insertion by expanding the value
7427   // to a V128 type and perform the insertion on that.
7428   SDLoc DL(Op);
7429   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7430   EVT WideTy = WideVec.getValueType();
7431 
7432   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7433                              Op.getOperand(1), Op.getOperand(2));
7434   // Re-narrow the resultant vector.
7435   return NarrowVector(Node, DAG);
7436 }
7437 
7438 SDValue
7439 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7440                                                SelectionDAG &DAG) const {
7441   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7442 
7443   // Check for non-constant or out of range lane.
7444   EVT VT = Op.getOperand(0).getValueType();
7445   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7446   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7447     return SDValue();
7448 
7449 
7450   // Insertion/extraction are legal for V128 types.
7451   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7452       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7453       VT == MVT::v8f16)
7454     return Op;
7455 
7456   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7457       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7458     return SDValue();
7459 
7460   // For V64 types, we perform extraction by expanding the value
7461   // to a V128 type and perform the extraction on that.
7462   SDLoc DL(Op);
7463   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7464   EVT WideTy = WideVec.getValueType();
7465 
7466   EVT ExtrTy = WideTy.getVectorElementType();
7467   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7468     ExtrTy = MVT::i32;
7469 
7470   // For extractions, we just return the result directly.
7471   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7472                      Op.getOperand(1));
7473 }
7474 
7475 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7476                                                       SelectionDAG &DAG) const {
7477   EVT VT = Op.getOperand(0).getValueType();
7478   SDLoc dl(Op);
7479   // Just in case...
7480   if (!VT.isVector())
7481     return SDValue();
7482 
7483   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7484   if (!Cst)
7485     return SDValue();
7486   unsigned Val = Cst->getZExtValue();
7487 
7488   unsigned Size = Op.getValueSizeInBits();
7489 
7490   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7491   if (Val == 0)
7492     return Op;
7493 
7494   // If this is extracting the upper 64-bits of a 128-bit vector, we match
7495   // that directly.
7496   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7497     return Op;
7498 
7499   return SDValue();
7500 }
7501 
7502 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7503   if (VT.getVectorNumElements() == 4 &&
7504       (VT.is128BitVector() || VT.is64BitVector())) {
7505     unsigned PFIndexes[4];
7506     for (unsigned i = 0; i != 4; ++i) {
7507       if (M[i] < 0)
7508         PFIndexes[i] = 8;
7509       else
7510         PFIndexes[i] = M[i];
7511     }
7512 
7513     // Compute the index in the perfect shuffle table.
7514     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7515                             PFIndexes[2] * 9 + PFIndexes[3];
7516     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7517     unsigned Cost = (PFEntry >> 30);
7518 
7519     if (Cost <= 4)
7520       return true;
7521   }
7522 
7523   bool DummyBool;
7524   int DummyInt;
7525   unsigned DummyUnsigned;
7526 
7527   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7528           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7529           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7530           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7531           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7532           isZIPMask(M, VT, DummyUnsigned) ||
7533           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7534           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7535           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7536           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7537           isConcatMask(M, VT, VT.getSizeInBits() == 128));
7538 }
7539 
7540 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7541 /// operand of a vector shift operation, where all the elements of the
7542 /// build_vector must have the same constant integer value.
7543 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7544   // Ignore bit_converts.
7545   while (Op.getOpcode() == ISD::BITCAST)
7546     Op = Op.getOperand(0);
7547   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7548   APInt SplatBits, SplatUndef;
7549   unsigned SplatBitSize;
7550   bool HasAnyUndefs;
7551   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7552                                     HasAnyUndefs, ElementBits) ||
7553       SplatBitSize > ElementBits)
7554     return false;
7555   Cnt = SplatBits.getSExtValue();
7556   return true;
7557 }
7558 
7559 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7560 /// operand of a vector shift left operation.  That value must be in the range:
7561 ///   0 <= Value < ElementBits for a left shift; or
7562 ///   0 <= Value <= ElementBits for a long left shift.
7563 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7564   assert(VT.isVector() && "vector shift count is not a vector type");
7565   int64_t ElementBits = VT.getScalarSizeInBits();
7566   if (!getVShiftImm(Op, ElementBits, Cnt))
7567     return false;
7568   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7569 }
7570 
7571 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7572 /// operand of a vector shift right operation. The value must be in the range:
7573 ///   1 <= Value <= ElementBits for a right shift; or
7574 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7575   assert(VT.isVector() && "vector shift count is not a vector type");
7576   int64_t ElementBits = VT.getScalarSizeInBits();
7577   if (!getVShiftImm(Op, ElementBits, Cnt))
7578     return false;
7579   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7580 }
7581 
7582 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7583                                                       SelectionDAG &DAG) const {
7584   EVT VT = Op.getValueType();
7585   SDLoc DL(Op);
7586   int64_t Cnt;
7587 
7588   if (!Op.getOperand(1).getValueType().isVector())
7589     return Op;
7590   unsigned EltSize = VT.getScalarSizeInBits();
7591 
7592   switch (Op.getOpcode()) {
7593   default:
7594     llvm_unreachable("unexpected shift opcode");
7595 
7596   case ISD::SHL:
7597     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7598       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7599                          DAG.getConstant(Cnt, DL, MVT::i32));
7600     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7601                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7602                                        MVT::i32),
7603                        Op.getOperand(0), Op.getOperand(1));
7604   case ISD::SRA:
7605   case ISD::SRL:
7606     // Right shift immediate
7607     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7608       unsigned Opc =
7609           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7610       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7611                          DAG.getConstant(Cnt, DL, MVT::i32));
7612     }
7613 
7614     // Right shift register.  Note, there is not a shift right register
7615     // instruction, but the shift left register instruction takes a signed
7616     // value, where negative numbers specify a right shift.
7617     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7618                                                 : Intrinsic::aarch64_neon_ushl;
7619     // negate the shift amount
7620     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7621     SDValue NegShiftLeft =
7622         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7623                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7624                     NegShift);
7625     return NegShiftLeft;
7626   }
7627 
7628   return SDValue();
7629 }
7630 
7631 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7632                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7633                                     const SDLoc &dl, SelectionDAG &DAG) {
7634   EVT SrcVT = LHS.getValueType();
7635   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7636          "function only supposed to emit natural comparisons");
7637 
7638   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7639   APInt CnstBits(VT.getSizeInBits(), 0);
7640   APInt UndefBits(VT.getSizeInBits(), 0);
7641   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7642   bool IsZero = IsCnst && (CnstBits == 0);
7643 
7644   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7645     switch (CC) {
7646     default:
7647       return SDValue();
7648     case AArch64CC::NE: {
7649       SDValue Fcmeq;
7650       if (IsZero)
7651         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7652       else
7653         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7654       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7655     }
7656     case AArch64CC::EQ:
7657       if (IsZero)
7658         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7659       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7660     case AArch64CC::GE:
7661       if (IsZero)
7662         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7663       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7664     case AArch64CC::GT:
7665       if (IsZero)
7666         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7667       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7668     case AArch64CC::LS:
7669       if (IsZero)
7670         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7671       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7672     case AArch64CC::LT:
7673       if (!NoNans)
7674         return SDValue();
7675       // If we ignore NaNs then we can use to the MI implementation.
7676       LLVM_FALLTHROUGH;
7677     case AArch64CC::MI:
7678       if (IsZero)
7679         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7680       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7681     }
7682   }
7683 
7684   switch (CC) {
7685   default:
7686     return SDValue();
7687   case AArch64CC::NE: {
7688     SDValue Cmeq;
7689     if (IsZero)
7690       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7691     else
7692       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7693     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7694   }
7695   case AArch64CC::EQ:
7696     if (IsZero)
7697       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7698     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7699   case AArch64CC::GE:
7700     if (IsZero)
7701       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7702     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7703   case AArch64CC::GT:
7704     if (IsZero)
7705       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7706     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7707   case AArch64CC::LE:
7708     if (IsZero)
7709       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7710     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7711   case AArch64CC::LS:
7712     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7713   case AArch64CC::LO:
7714     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7715   case AArch64CC::LT:
7716     if (IsZero)
7717       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7718     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7719   case AArch64CC::HI:
7720     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7721   case AArch64CC::HS:
7722     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7723   }
7724 }
7725 
7726 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7727                                            SelectionDAG &DAG) const {
7728   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7729   SDValue LHS = Op.getOperand(0);
7730   SDValue RHS = Op.getOperand(1);
7731   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7732   SDLoc dl(Op);
7733 
7734   if (LHS.getValueType().getVectorElementType().isInteger()) {
7735     assert(LHS.getValueType() == RHS.getValueType());
7736     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7737     SDValue Cmp =
7738         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7739     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7740   }
7741 
7742   const bool FullFP16 =
7743     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7744 
7745   // Make v4f16 (only) fcmp operations utilise vector instructions
7746   // v8f16 support will be a litle more complicated
7747   if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7748     if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7749       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7750       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7751       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7752       DAG.ReplaceAllUsesWith(Op, NewSetcc);
7753       CmpVT = MVT::v4i32;
7754     } else
7755       return SDValue();
7756   }
7757 
7758   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7759          LHS.getValueType().getVectorElementType() == MVT::f64);
7760 
7761   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7762   // clean.  Some of them require two branches to implement.
7763   AArch64CC::CondCode CC1, CC2;
7764   bool ShouldInvert;
7765   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7766 
7767   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7768   SDValue Cmp =
7769       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7770   if (!Cmp.getNode())
7771     return SDValue();
7772 
7773   if (CC2 != AArch64CC::AL) {
7774     SDValue Cmp2 =
7775         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7776     if (!Cmp2.getNode())
7777       return SDValue();
7778 
7779     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7780   }
7781 
7782   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7783 
7784   if (ShouldInvert)
7785     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7786 
7787   return Cmp;
7788 }
7789 
7790 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7791                                   SelectionDAG &DAG) {
7792   SDValue VecOp = ScalarOp.getOperand(0);
7793   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7794   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7795                      DAG.getConstant(0, DL, MVT::i64));
7796 }
7797 
7798 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7799                                               SelectionDAG &DAG) const {
7800   SDLoc dl(Op);
7801   switch (Op.getOpcode()) {
7802   case ISD::VECREDUCE_ADD:
7803     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7804   case ISD::VECREDUCE_SMAX:
7805     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7806   case ISD::VECREDUCE_SMIN:
7807     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7808   case ISD::VECREDUCE_UMAX:
7809     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7810   case ISD::VECREDUCE_UMIN:
7811     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7812   case ISD::VECREDUCE_FMAX: {
7813     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7814     return DAG.getNode(
7815         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7816         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7817         Op.getOperand(0));
7818   }
7819   case ISD::VECREDUCE_FMIN: {
7820     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7821     return DAG.getNode(
7822         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7823         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7824         Op.getOperand(0));
7825   }
7826   default:
7827     llvm_unreachable("Unhandled reduction");
7828   }
7829 }
7830 
7831 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7832                                                     SelectionDAG &DAG) const {
7833   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7834   if (!Subtarget.hasLSE())
7835     return SDValue();
7836 
7837   // LSE has an atomic load-add instruction, but not a load-sub.
7838   SDLoc dl(Op);
7839   MVT VT = Op.getSimpleValueType();
7840   SDValue RHS = Op.getOperand(2);
7841   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7842   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7843   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7844                        Op.getOperand(0), Op.getOperand(1), RHS,
7845                        AN->getMemOperand());
7846 }
7847 
7848 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7849                                                     SelectionDAG &DAG) const {
7850   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7851   if (!Subtarget.hasLSE())
7852     return SDValue();
7853 
7854   // LSE has an atomic load-clear instruction, but not a load-and.
7855   SDLoc dl(Op);
7856   MVT VT = Op.getSimpleValueType();
7857   SDValue RHS = Op.getOperand(2);
7858   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7859   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7860   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7861                        Op.getOperand(0), Op.getOperand(1), RHS,
7862                        AN->getMemOperand());
7863 }
7864 
7865 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7866     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7867   SDLoc dl(Op);
7868   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7869   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7870 
7871   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7872   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7873   if (Subtarget->hasCustomCallingConv())
7874     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
7875 
7876   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7877                      DAG.getConstant(4, dl, MVT::i64));
7878   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7879   Chain =
7880       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7881                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7882                   DAG.getRegisterMask(Mask), Chain.getValue(1));
7883   // To match the actual intent better, we should read the output from X15 here
7884   // again (instead of potentially spilling it to the stack), but rereading Size
7885   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7886   // here.
7887 
7888   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7889                      DAG.getConstant(4, dl, MVT::i64));
7890   return Chain;
7891 }
7892 
7893 SDValue
7894 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7895                                                SelectionDAG &DAG) const {
7896   assert(Subtarget->isTargetWindows() &&
7897          "Only Windows alloca probing supported");
7898   SDLoc dl(Op);
7899   // Get the inputs.
7900   SDNode *Node = Op.getNode();
7901   SDValue Chain = Op.getOperand(0);
7902   SDValue Size = Op.getOperand(1);
7903   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7904   EVT VT = Node->getValueType(0);
7905 
7906   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7907           "no-stack-arg-probe")) {
7908     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7909     Chain = SP.getValue(1);
7910     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7911     if (Align)
7912       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7913                        DAG.getConstant(-(uint64_t)Align, dl, VT));
7914     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7915     SDValue Ops[2] = {SP, Chain};
7916     return DAG.getMergeValues(Ops, dl);
7917   }
7918 
7919   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7920 
7921   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7922 
7923   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7924   Chain = SP.getValue(1);
7925   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7926   if (Align)
7927     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7928                      DAG.getConstant(-(uint64_t)Align, dl, VT));
7929   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7930 
7931   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7932                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7933 
7934   SDValue Ops[2] = {SP, Chain};
7935   return DAG.getMergeValues(Ops, dl);
7936 }
7937 
7938 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7939 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7940 /// specified in the intrinsic calls.
7941 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7942                                                const CallInst &I,
7943                                                MachineFunction &MF,
7944                                                unsigned Intrinsic) const {
7945   auto &DL = I.getModule()->getDataLayout();
7946   switch (Intrinsic) {
7947   case Intrinsic::aarch64_neon_ld2:
7948   case Intrinsic::aarch64_neon_ld3:
7949   case Intrinsic::aarch64_neon_ld4:
7950   case Intrinsic::aarch64_neon_ld1x2:
7951   case Intrinsic::aarch64_neon_ld1x3:
7952   case Intrinsic::aarch64_neon_ld1x4:
7953   case Intrinsic::aarch64_neon_ld2lane:
7954   case Intrinsic::aarch64_neon_ld3lane:
7955   case Intrinsic::aarch64_neon_ld4lane:
7956   case Intrinsic::aarch64_neon_ld2r:
7957   case Intrinsic::aarch64_neon_ld3r:
7958   case Intrinsic::aarch64_neon_ld4r: {
7959     Info.opc = ISD::INTRINSIC_W_CHAIN;
7960     // Conservatively set memVT to the entire set of vectors loaded.
7961     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7962     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7963     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7964     Info.offset = 0;
7965     Info.align = 0;
7966     // volatile loads with NEON intrinsics not supported
7967     Info.flags = MachineMemOperand::MOLoad;
7968     return true;
7969   }
7970   case Intrinsic::aarch64_neon_st2:
7971   case Intrinsic::aarch64_neon_st3:
7972   case Intrinsic::aarch64_neon_st4:
7973   case Intrinsic::aarch64_neon_st1x2:
7974   case Intrinsic::aarch64_neon_st1x3:
7975   case Intrinsic::aarch64_neon_st1x4:
7976   case Intrinsic::aarch64_neon_st2lane:
7977   case Intrinsic::aarch64_neon_st3lane:
7978   case Intrinsic::aarch64_neon_st4lane: {
7979     Info.opc = ISD::INTRINSIC_VOID;
7980     // Conservatively set memVT to the entire set of vectors stored.
7981     unsigned NumElts = 0;
7982     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7983       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7984       if (!ArgTy->isVectorTy())
7985         break;
7986       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7987     }
7988     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7989     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7990     Info.offset = 0;
7991     Info.align = 0;
7992     // volatile stores with NEON intrinsics not supported
7993     Info.flags = MachineMemOperand::MOStore;
7994     return true;
7995   }
7996   case Intrinsic::aarch64_ldaxr:
7997   case Intrinsic::aarch64_ldxr: {
7998     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7999     Info.opc = ISD::INTRINSIC_W_CHAIN;
8000     Info.memVT = MVT::getVT(PtrTy->getElementType());
8001     Info.ptrVal = I.getArgOperand(0);
8002     Info.offset = 0;
8003     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
8004     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8005     return true;
8006   }
8007   case Intrinsic::aarch64_stlxr:
8008   case Intrinsic::aarch64_stxr: {
8009     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8010     Info.opc = ISD::INTRINSIC_W_CHAIN;
8011     Info.memVT = MVT::getVT(PtrTy->getElementType());
8012     Info.ptrVal = I.getArgOperand(1);
8013     Info.offset = 0;
8014     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
8015     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8016     return true;
8017   }
8018   case Intrinsic::aarch64_ldaxp:
8019   case Intrinsic::aarch64_ldxp:
8020     Info.opc = ISD::INTRINSIC_W_CHAIN;
8021     Info.memVT = MVT::i128;
8022     Info.ptrVal = I.getArgOperand(0);
8023     Info.offset = 0;
8024     Info.align = 16;
8025     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8026     return true;
8027   case Intrinsic::aarch64_stlxp:
8028   case Intrinsic::aarch64_stxp:
8029     Info.opc = ISD::INTRINSIC_W_CHAIN;
8030     Info.memVT = MVT::i128;
8031     Info.ptrVal = I.getArgOperand(2);
8032     Info.offset = 0;
8033     Info.align = 16;
8034     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8035     return true;
8036   default:
8037     break;
8038   }
8039 
8040   return false;
8041 }
8042 
8043 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8044                                                   ISD::LoadExtType ExtTy,
8045                                                   EVT NewVT) const {
8046   // TODO: This may be worth removing. Check regression tests for diffs.
8047   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8048     return false;
8049 
8050   // If we're reducing the load width in order to avoid having to use an extra
8051   // instruction to do extension then it's probably a good idea.
8052   if (ExtTy != ISD::NON_EXTLOAD)
8053     return true;
8054   // Don't reduce load width if it would prevent us from combining a shift into
8055   // the offset.
8056   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8057   assert(Mem);
8058   const SDValue &Base = Mem->getBasePtr();
8059   if (Base.getOpcode() == ISD::ADD &&
8060       Base.getOperand(1).getOpcode() == ISD::SHL &&
8061       Base.getOperand(1).hasOneUse() &&
8062       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8063     // The shift can be combined if it matches the size of the value being
8064     // loaded (and so reducing the width would make it not match).
8065     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8066     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8067     if (ShiftAmount == Log2_32(LoadBytes))
8068       return false;
8069   }
8070   // We have no reason to disallow reducing the load width, so allow it.
8071   return true;
8072 }
8073 
8074 // Truncations from 64-bit GPR to 32-bit GPR is free.
8075 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8076   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8077     return false;
8078   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8079   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8080   return NumBits1 > NumBits2;
8081 }
8082 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8083   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8084     return false;
8085   unsigned NumBits1 = VT1.getSizeInBits();
8086   unsigned NumBits2 = VT2.getSizeInBits();
8087   return NumBits1 > NumBits2;
8088 }
8089 
8090 /// Check if it is profitable to hoist instruction in then/else to if.
8091 /// Not profitable if I and it's user can form a FMA instruction
8092 /// because we prefer FMSUB/FMADD.
8093 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8094   if (I->getOpcode() != Instruction::FMul)
8095     return true;
8096 
8097   if (!I->hasOneUse())
8098     return true;
8099 
8100   Instruction *User = I->user_back();
8101 
8102   if (User &&
8103       !(User->getOpcode() == Instruction::FSub ||
8104         User->getOpcode() == Instruction::FAdd))
8105     return true;
8106 
8107   const TargetOptions &Options = getTargetMachine().Options;
8108   const DataLayout &DL = I->getModule()->getDataLayout();
8109   EVT VT = getValueType(DL, User->getOperand(0)->getType());
8110 
8111   return !(isFMAFasterThanFMulAndFAdd(VT) &&
8112            isOperationLegalOrCustom(ISD::FMA, VT) &&
8113            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8114             Options.UnsafeFPMath));
8115 }
8116 
8117 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8118 // 64-bit GPR.
8119 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8120   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8121     return false;
8122   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8123   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8124   return NumBits1 == 32 && NumBits2 == 64;
8125 }
8126 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8127   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8128     return false;
8129   unsigned NumBits1 = VT1.getSizeInBits();
8130   unsigned NumBits2 = VT2.getSizeInBits();
8131   return NumBits1 == 32 && NumBits2 == 64;
8132 }
8133 
8134 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8135   EVT VT1 = Val.getValueType();
8136   if (isZExtFree(VT1, VT2)) {
8137     return true;
8138   }
8139 
8140   if (Val.getOpcode() != ISD::LOAD)
8141     return false;
8142 
8143   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8144   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8145           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8146           VT1.getSizeInBits() <= 32);
8147 }
8148 
8149 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8150   if (isa<FPExtInst>(Ext))
8151     return false;
8152 
8153   // Vector types are not free.
8154   if (Ext->getType()->isVectorTy())
8155     return false;
8156 
8157   for (const Use &U : Ext->uses()) {
8158     // The extension is free if we can fold it with a left shift in an
8159     // addressing mode or an arithmetic operation: add, sub, and cmp.
8160 
8161     // Is there a shift?
8162     const Instruction *Instr = cast<Instruction>(U.getUser());
8163 
8164     // Is this a constant shift?
8165     switch (Instr->getOpcode()) {
8166     case Instruction::Shl:
8167       if (!isa<ConstantInt>(Instr->getOperand(1)))
8168         return false;
8169       break;
8170     case Instruction::GetElementPtr: {
8171       gep_type_iterator GTI = gep_type_begin(Instr);
8172       auto &DL = Ext->getModule()->getDataLayout();
8173       std::advance(GTI, U.getOperandNo()-1);
8174       Type *IdxTy = GTI.getIndexedType();
8175       // This extension will end up with a shift because of the scaling factor.
8176       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8177       // Get the shift amount based on the scaling factor:
8178       // log2(sizeof(IdxTy)) - log2(8).
8179       uint64_t ShiftAmt =
8180           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8181       // Is the constant foldable in the shift of the addressing mode?
8182       // I.e., shift amount is between 1 and 4 inclusive.
8183       if (ShiftAmt == 0 || ShiftAmt > 4)
8184         return false;
8185       break;
8186     }
8187     case Instruction::Trunc:
8188       // Check if this is a noop.
8189       // trunc(sext ty1 to ty2) to ty1.
8190       if (Instr->getType() == Ext->getOperand(0)->getType())
8191         continue;
8192       LLVM_FALLTHROUGH;
8193     default:
8194       return false;
8195     }
8196 
8197     // At this point we can use the bfm family, so this extension is free
8198     // for that use.
8199   }
8200   return true;
8201 }
8202 
8203 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8204                                           unsigned &RequiredAligment) const {
8205   if (!LoadedType.isSimple() ||
8206       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8207     return false;
8208   // Cyclone supports unaligned accesses.
8209   RequiredAligment = 0;
8210   unsigned NumBits = LoadedType.getSizeInBits();
8211   return NumBits == 32 || NumBits == 64;
8212 }
8213 
8214 /// A helper function for determining the number of interleaved accesses we
8215 /// will generate when lowering accesses of the given type.
8216 unsigned
8217 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8218                                                  const DataLayout &DL) const {
8219   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8220 }
8221 
8222 MachineMemOperand::Flags
8223 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8224   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8225       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8226     return MOStridedAccess;
8227   return MachineMemOperand::MONone;
8228 }
8229 
8230 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8231     VectorType *VecTy, const DataLayout &DL) const {
8232 
8233   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8234   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8235 
8236   // Ensure the number of vector elements is greater than 1.
8237   if (VecTy->getNumElements() < 2)
8238     return false;
8239 
8240   // Ensure the element type is legal.
8241   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8242     return false;
8243 
8244   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8245   // 128 will be split into multiple interleaved accesses.
8246   return VecSize == 64 || VecSize % 128 == 0;
8247 }
8248 
8249 /// Lower an interleaved load into a ldN intrinsic.
8250 ///
8251 /// E.g. Lower an interleaved load (Factor = 2):
8252 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8253 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
8254 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
8255 ///
8256 ///      Into:
8257 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8258 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8259 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8260 bool AArch64TargetLowering::lowerInterleavedLoad(
8261     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8262     ArrayRef<unsigned> Indices, unsigned Factor) const {
8263   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8264          "Invalid interleave factor");
8265   assert(!Shuffles.empty() && "Empty shufflevector input");
8266   assert(Shuffles.size() == Indices.size() &&
8267          "Unmatched number of shufflevectors and indices");
8268 
8269   const DataLayout &DL = LI->getModule()->getDataLayout();
8270 
8271   VectorType *VecTy = Shuffles[0]->getType();
8272 
8273   // Skip if we do not have NEON and skip illegal vector types. We can
8274   // "legalize" wide vector types into multiple interleaved accesses as long as
8275   // the vector types are divisible by 128.
8276   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8277     return false;
8278 
8279   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8280 
8281   // A pointer vector can not be the return type of the ldN intrinsics. Need to
8282   // load integer vectors first and then convert to pointer vectors.
8283   Type *EltTy = VecTy->getVectorElementType();
8284   if (EltTy->isPointerTy())
8285     VecTy =
8286         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8287 
8288   IRBuilder<> Builder(LI);
8289 
8290   // The base address of the load.
8291   Value *BaseAddr = LI->getPointerOperand();
8292 
8293   if (NumLoads > 1) {
8294     // If we're going to generate more than one load, reset the sub-vector type
8295     // to something legal.
8296     VecTy = VectorType::get(VecTy->getVectorElementType(),
8297                             VecTy->getVectorNumElements() / NumLoads);
8298 
8299     // We will compute the pointer operand of each load from the original base
8300     // address using GEPs. Cast the base address to a pointer to the scalar
8301     // element type.
8302     BaseAddr = Builder.CreateBitCast(
8303         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8304                       LI->getPointerAddressSpace()));
8305   }
8306 
8307   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8308   Type *Tys[2] = {VecTy, PtrTy};
8309   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8310                                             Intrinsic::aarch64_neon_ld3,
8311                                             Intrinsic::aarch64_neon_ld4};
8312   Function *LdNFunc =
8313       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8314 
8315   // Holds sub-vectors extracted from the load intrinsic return values. The
8316   // sub-vectors are associated with the shufflevector instructions they will
8317   // replace.
8318   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8319 
8320   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8321 
8322     // If we're generating more than one load, compute the base address of
8323     // subsequent loads as an offset from the previous.
8324     if (LoadCount > 0)
8325       BaseAddr = Builder.CreateConstGEP1_32(
8326           BaseAddr, VecTy->getVectorNumElements() * Factor);
8327 
8328     CallInst *LdN = Builder.CreateCall(
8329         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8330 
8331     // Extract and store the sub-vectors returned by the load intrinsic.
8332     for (unsigned i = 0; i < Shuffles.size(); i++) {
8333       ShuffleVectorInst *SVI = Shuffles[i];
8334       unsigned Index = Indices[i];
8335 
8336       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8337 
8338       // Convert the integer vector to pointer vector if the element is pointer.
8339       if (EltTy->isPointerTy())
8340         SubVec = Builder.CreateIntToPtr(
8341             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8342                                     VecTy->getVectorNumElements()));
8343       SubVecs[SVI].push_back(SubVec);
8344     }
8345   }
8346 
8347   // Replace uses of the shufflevector instructions with the sub-vectors
8348   // returned by the load intrinsic. If a shufflevector instruction is
8349   // associated with more than one sub-vector, those sub-vectors will be
8350   // concatenated into a single wide vector.
8351   for (ShuffleVectorInst *SVI : Shuffles) {
8352     auto &SubVec = SubVecs[SVI];
8353     auto *WideVec =
8354         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8355     SVI->replaceAllUsesWith(WideVec);
8356   }
8357 
8358   return true;
8359 }
8360 
8361 /// Lower an interleaved store into a stN intrinsic.
8362 ///
8363 /// E.g. Lower an interleaved store (Factor = 3):
8364 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8365 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8366 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8367 ///
8368 ///      Into:
8369 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8370 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8371 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8372 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8373 ///
8374 /// Note that the new shufflevectors will be removed and we'll only generate one
8375 /// st3 instruction in CodeGen.
8376 ///
8377 /// Example for a more general valid mask (Factor 3). Lower:
8378 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8379 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8380 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8381 ///
8382 ///      Into:
8383 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8384 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8385 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8386 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8387 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8388                                                   ShuffleVectorInst *SVI,
8389                                                   unsigned Factor) const {
8390   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8391          "Invalid interleave factor");
8392 
8393   VectorType *VecTy = SVI->getType();
8394   assert(VecTy->getVectorNumElements() % Factor == 0 &&
8395          "Invalid interleaved store");
8396 
8397   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8398   Type *EltTy = VecTy->getVectorElementType();
8399   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8400 
8401   const DataLayout &DL = SI->getModule()->getDataLayout();
8402 
8403   // Skip if we do not have NEON and skip illegal vector types. We can
8404   // "legalize" wide vector types into multiple interleaved accesses as long as
8405   // the vector types are divisible by 128.
8406   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8407     return false;
8408 
8409   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8410 
8411   Value *Op0 = SVI->getOperand(0);
8412   Value *Op1 = SVI->getOperand(1);
8413   IRBuilder<> Builder(SI);
8414 
8415   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8416   // vectors to integer vectors.
8417   if (EltTy->isPointerTy()) {
8418     Type *IntTy = DL.getIntPtrType(EltTy);
8419     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8420 
8421     // Convert to the corresponding integer vector.
8422     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8423     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8424     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8425 
8426     SubVecTy = VectorType::get(IntTy, LaneLen);
8427   }
8428 
8429   // The base address of the store.
8430   Value *BaseAddr = SI->getPointerOperand();
8431 
8432   if (NumStores > 1) {
8433     // If we're going to generate more than one store, reset the lane length
8434     // and sub-vector type to something legal.
8435     LaneLen /= NumStores;
8436     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8437 
8438     // We will compute the pointer operand of each store from the original base
8439     // address using GEPs. Cast the base address to a pointer to the scalar
8440     // element type.
8441     BaseAddr = Builder.CreateBitCast(
8442         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8443                       SI->getPointerAddressSpace()));
8444   }
8445 
8446   auto Mask = SVI->getShuffleMask();
8447 
8448   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8449   Type *Tys[2] = {SubVecTy, PtrTy};
8450   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8451                                              Intrinsic::aarch64_neon_st3,
8452                                              Intrinsic::aarch64_neon_st4};
8453   Function *StNFunc =
8454       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8455 
8456   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8457 
8458     SmallVector<Value *, 5> Ops;
8459 
8460     // Split the shufflevector operands into sub vectors for the new stN call.
8461     for (unsigned i = 0; i < Factor; i++) {
8462       unsigned IdxI = StoreCount * LaneLen * Factor + i;
8463       if (Mask[IdxI] >= 0) {
8464         Ops.push_back(Builder.CreateShuffleVector(
8465             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8466       } else {
8467         unsigned StartMask = 0;
8468         for (unsigned j = 1; j < LaneLen; j++) {
8469           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8470           if (Mask[IdxJ * Factor + IdxI] >= 0) {
8471             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8472             break;
8473           }
8474         }
8475         // Note: Filling undef gaps with random elements is ok, since
8476         // those elements were being written anyway (with undefs).
8477         // In the case of all undefs we're defaulting to using elems from 0
8478         // Note: StartMask cannot be negative, it's checked in
8479         // isReInterleaveMask
8480         Ops.push_back(Builder.CreateShuffleVector(
8481             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8482       }
8483     }
8484 
8485     // If we generating more than one store, we compute the base address of
8486     // subsequent stores as an offset from the previous.
8487     if (StoreCount > 0)
8488       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8489 
8490     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8491     Builder.CreateCall(StNFunc, Ops);
8492   }
8493   return true;
8494 }
8495 
8496 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8497                        unsigned AlignCheck) {
8498   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8499           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8500 }
8501 
8502 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8503                                                unsigned SrcAlign, bool IsMemset,
8504                                                bool ZeroMemset,
8505                                                bool MemcpyStrSrc,
8506                                                MachineFunction &MF) const {
8507   const Function &F = MF.getFunction();
8508   bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8509   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8510   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8511   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8512   // taken one instruction to materialize the v2i64 zero and one store (with
8513   // restrictive addressing mode). Just do i64 stores.
8514   bool IsSmallMemset = IsMemset && Size < 32;
8515   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8516     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8517       return true;
8518     bool Fast;
8519     return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8520   };
8521 
8522   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8523       AlignmentIsAcceptable(MVT::v2i64, 16))
8524     return MVT::v2i64;
8525   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8526     return MVT::f128;
8527   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8528     return MVT::i64;
8529   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8530     return MVT::i32;
8531   return MVT::Other;
8532 }
8533 
8534 // 12-bit optionally shifted immediates are legal for adds.
8535 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8536   if (Immed == std::numeric_limits<int64_t>::min()) {
8537     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8538                       << ": avoid UB for INT64_MIN\n");
8539     return false;
8540   }
8541   // Same encoding for add/sub, just flip the sign.
8542   Immed = std::abs(Immed);
8543   bool IsLegal = ((Immed >> 12) == 0 ||
8544                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8545   LLVM_DEBUG(dbgs() << "Is " << Immed
8546                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8547   return IsLegal;
8548 }
8549 
8550 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8551 // immediates is the same as for an add or a sub.
8552 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8553   return isLegalAddImmediate(Immed);
8554 }
8555 
8556 /// isLegalAddressingMode - Return true if the addressing mode represented
8557 /// by AM is legal for this target, for a load/store of the specified type.
8558 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8559                                                   const AddrMode &AM, Type *Ty,
8560                                                   unsigned AS, Instruction *I) const {
8561   // AArch64 has five basic addressing modes:
8562   //  reg
8563   //  reg + 9-bit signed offset
8564   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
8565   //  reg1 + reg2
8566   //  reg + SIZE_IN_BYTES * reg
8567 
8568   // No global is ever allowed as a base.
8569   if (AM.BaseGV)
8570     return false;
8571 
8572   // No reg+reg+imm addressing.
8573   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8574     return false;
8575 
8576   // check reg + imm case:
8577   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8578   uint64_t NumBytes = 0;
8579   if (Ty->isSized()) {
8580     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8581     NumBytes = NumBits / 8;
8582     if (!isPowerOf2_64(NumBits))
8583       NumBytes = 0;
8584   }
8585 
8586   if (!AM.Scale) {
8587     int64_t Offset = AM.BaseOffs;
8588 
8589     // 9-bit signed offset
8590     if (isInt<9>(Offset))
8591       return true;
8592 
8593     // 12-bit unsigned offset
8594     unsigned shift = Log2_64(NumBytes);
8595     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8596         // Must be a multiple of NumBytes (NumBytes is a power of 2)
8597         (Offset >> shift) << shift == Offset)
8598       return true;
8599     return false;
8600   }
8601 
8602   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8603 
8604   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8605 }
8606 
8607 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8608   // Consider splitting large offset of struct or array.
8609   return true;
8610 }
8611 
8612 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8613                                                 const AddrMode &AM, Type *Ty,
8614                                                 unsigned AS) const {
8615   // Scaling factors are not free at all.
8616   // Operands                     | Rt Latency
8617   // -------------------------------------------
8618   // Rt, [Xn, Xm]                 | 4
8619   // -------------------------------------------
8620   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
8621   // Rt, [Xn, Wm, <extend> #imm]  |
8622   if (isLegalAddressingMode(DL, AM, Ty, AS))
8623     // Scale represents reg2 * scale, thus account for 1 if
8624     // it is not equal to 0 or 1.
8625     return AM.Scale != 0 && AM.Scale != 1;
8626   return -1;
8627 }
8628 
8629 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8630   VT = VT.getScalarType();
8631 
8632   if (!VT.isSimple())
8633     return false;
8634 
8635   switch (VT.getSimpleVT().SimpleTy) {
8636   case MVT::f32:
8637   case MVT::f64:
8638     return true;
8639   default:
8640     break;
8641   }
8642 
8643   return false;
8644 }
8645 
8646 const MCPhysReg *
8647 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8648   // LR is a callee-save register, but we must treat it as clobbered by any call
8649   // site. Hence we include LR in the scratch registers, which are in turn added
8650   // as implicit-defs for stackmaps and patchpoints.
8651   static const MCPhysReg ScratchRegs[] = {
8652     AArch64::X16, AArch64::X17, AArch64::LR, 0
8653   };
8654   return ScratchRegs;
8655 }
8656 
8657 bool
8658 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8659                                                      CombineLevel Level) const {
8660   N = N->getOperand(0).getNode();
8661   EVT VT = N->getValueType(0);
8662     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8663     // it with shift to let it be lowered to UBFX.
8664   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8665       isa<ConstantSDNode>(N->getOperand(1))) {
8666     uint64_t TruncMask = N->getConstantOperandVal(1);
8667     if (isMask_64(TruncMask) &&
8668       N->getOperand(0).getOpcode() == ISD::SRL &&
8669       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8670       return false;
8671   }
8672   return true;
8673 }
8674 
8675 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8676                                                               Type *Ty) const {
8677   assert(Ty->isIntegerTy());
8678 
8679   unsigned BitSize = Ty->getPrimitiveSizeInBits();
8680   if (BitSize == 0)
8681     return false;
8682 
8683   int64_t Val = Imm.getSExtValue();
8684   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8685     return true;
8686 
8687   if ((int64_t)Val < 0)
8688     Val = ~Val;
8689   if (BitSize == 32)
8690     Val &= (1LL << 32) - 1;
8691 
8692   unsigned LZ = countLeadingZeros((uint64_t)Val);
8693   unsigned Shift = (63 - LZ) / 16;
8694   // MOVZ is free so return true for one or fewer MOVK.
8695   return Shift < 3;
8696 }
8697 
8698 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8699                                                     unsigned Index) const {
8700   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8701     return false;
8702 
8703   return (Index == 0 || Index == ResVT.getVectorNumElements());
8704 }
8705 
8706 /// Turn vector tests of the signbit in the form of:
8707 ///   xor (sra X, elt_size(X)-1), -1
8708 /// into:
8709 ///   cmge X, X, #0
8710 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8711                                          const AArch64Subtarget *Subtarget) {
8712   EVT VT = N->getValueType(0);
8713   if (!Subtarget->hasNEON() || !VT.isVector())
8714     return SDValue();
8715 
8716   // There must be a shift right algebraic before the xor, and the xor must be a
8717   // 'not' operation.
8718   SDValue Shift = N->getOperand(0);
8719   SDValue Ones = N->getOperand(1);
8720   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8721       !ISD::isBuildVectorAllOnes(Ones.getNode()))
8722     return SDValue();
8723 
8724   // The shift should be smearing the sign bit across each vector element.
8725   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8726   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8727   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8728     return SDValue();
8729 
8730   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8731 }
8732 
8733 // Generate SUBS and CSEL for integer abs.
8734 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8735   EVT VT = N->getValueType(0);
8736 
8737   SDValue N0 = N->getOperand(0);
8738   SDValue N1 = N->getOperand(1);
8739   SDLoc DL(N);
8740 
8741   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8742   // and change it to SUB and CSEL.
8743   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8744       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8745       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8746     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8747       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
8748         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
8749                                   N0.getOperand(0));
8750         // Generate SUBS & CSEL.
8751         SDValue Cmp =
8752             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
8753                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
8754         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8755                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8756                            SDValue(Cmp.getNode(), 1));
8757       }
8758   return SDValue();
8759 }
8760 
8761 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8762                                  TargetLowering::DAGCombinerInfo &DCI,
8763                                  const AArch64Subtarget *Subtarget) {
8764   if (DCI.isBeforeLegalizeOps())
8765     return SDValue();
8766 
8767   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8768     return Cmp;
8769 
8770   return performIntegerAbsCombine(N, DAG);
8771 }
8772 
8773 SDValue
8774 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8775                                      SelectionDAG &DAG,
8776                                      SmallVectorImpl<SDNode *> &Created) const {
8777   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
8778   if (isIntDivCheap(N->getValueType(0), Attr))
8779     return SDValue(N,0); // Lower SDIV as SDIV
8780 
8781   // fold (sdiv X, pow2)
8782   EVT VT = N->getValueType(0);
8783   if ((VT != MVT::i32 && VT != MVT::i64) ||
8784       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8785     return SDValue();
8786 
8787   SDLoc DL(N);
8788   SDValue N0 = N->getOperand(0);
8789   unsigned Lg2 = Divisor.countTrailingZeros();
8790   SDValue Zero = DAG.getConstant(0, DL, VT);
8791   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8792 
8793   // Add (N0 < 0) ? Pow2 - 1 : 0;
8794   SDValue CCVal;
8795   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8796   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8797   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8798 
8799   Created.push_back(Cmp.getNode());
8800   Created.push_back(Add.getNode());
8801   Created.push_back(CSel.getNode());
8802 
8803   // Divide by pow2.
8804   SDValue SRA =
8805       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8806 
8807   // If we're dividing by a positive value, we're done.  Otherwise, we must
8808   // negate the result.
8809   if (Divisor.isNonNegative())
8810     return SRA;
8811 
8812   Created.push_back(SRA.getNode());
8813   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8814 }
8815 
8816 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8817                                  TargetLowering::DAGCombinerInfo &DCI,
8818                                  const AArch64Subtarget *Subtarget) {
8819   if (DCI.isBeforeLegalizeOps())
8820     return SDValue();
8821 
8822   // The below optimizations require a constant RHS.
8823   if (!isa<ConstantSDNode>(N->getOperand(1)))
8824     return SDValue();
8825 
8826   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8827   const APInt &ConstValue = C->getAPIntValue();
8828 
8829   // Multiplication of a power of two plus/minus one can be done more
8830   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8831   // future CPUs have a cheaper MADD instruction, this may need to be
8832   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8833   // 64-bit is 5 cycles, so this is always a win.
8834   // More aggressively, some multiplications N0 * C can be lowered to
8835   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8836   // e.g. 6=3*2=(2+1)*2.
8837   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8838   // which equals to (1+2)*16-(1+2).
8839   SDValue N0 = N->getOperand(0);
8840   // TrailingZeroes is used to test if the mul can be lowered to
8841   // shift+add+shift.
8842   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8843   if (TrailingZeroes) {
8844     // Conservatively do not lower to shift+add+shift if the mul might be
8845     // folded into smul or umul.
8846     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8847                             isZeroExtended(N0.getNode(), DAG)))
8848       return SDValue();
8849     // Conservatively do not lower to shift+add+shift if the mul might be
8850     // folded into madd or msub.
8851     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8852                            N->use_begin()->getOpcode() == ISD::SUB))
8853       return SDValue();
8854   }
8855   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8856   // and shift+add+shift.
8857   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8858 
8859   unsigned ShiftAmt, AddSubOpc;
8860   // Is the shifted value the LHS operand of the add/sub?
8861   bool ShiftValUseIsN0 = true;
8862   // Do we need to negate the result?
8863   bool NegateResult = false;
8864 
8865   if (ConstValue.isNonNegative()) {
8866     // (mul x, 2^N + 1) => (add (shl x, N), x)
8867     // (mul x, 2^N - 1) => (sub (shl x, N), x)
8868     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8869     APInt SCVMinus1 = ShiftedConstValue - 1;
8870     APInt CVPlus1 = ConstValue + 1;
8871     if (SCVMinus1.isPowerOf2()) {
8872       ShiftAmt = SCVMinus1.logBase2();
8873       AddSubOpc = ISD::ADD;
8874     } else if (CVPlus1.isPowerOf2()) {
8875       ShiftAmt = CVPlus1.logBase2();
8876       AddSubOpc = ISD::SUB;
8877     } else
8878       return SDValue();
8879   } else {
8880     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8881     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8882     APInt CVNegPlus1 = -ConstValue + 1;
8883     APInt CVNegMinus1 = -ConstValue - 1;
8884     if (CVNegPlus1.isPowerOf2()) {
8885       ShiftAmt = CVNegPlus1.logBase2();
8886       AddSubOpc = ISD::SUB;
8887       ShiftValUseIsN0 = false;
8888     } else if (CVNegMinus1.isPowerOf2()) {
8889       ShiftAmt = CVNegMinus1.logBase2();
8890       AddSubOpc = ISD::ADD;
8891       NegateResult = true;
8892     } else
8893       return SDValue();
8894   }
8895 
8896   SDLoc DL(N);
8897   EVT VT = N->getValueType(0);
8898   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8899                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
8900 
8901   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8902   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8903   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8904   assert(!(NegateResult && TrailingZeroes) &&
8905          "NegateResult and TrailingZeroes cannot both be true for now.");
8906   // Negate the result.
8907   if (NegateResult)
8908     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8909   // Shift the result.
8910   if (TrailingZeroes)
8911     return DAG.getNode(ISD::SHL, DL, VT, Res,
8912                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8913   return Res;
8914 }
8915 
8916 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8917                                                          SelectionDAG &DAG) {
8918   // Take advantage of vector comparisons producing 0 or -1 in each lane to
8919   // optimize away operation when it's from a constant.
8920   //
8921   // The general transformation is:
8922   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8923   //       AND(VECTOR_CMP(x,y), constant2)
8924   //    constant2 = UNARYOP(constant)
8925 
8926   // Early exit if this isn't a vector operation, the operand of the
8927   // unary operation isn't a bitwise AND, or if the sizes of the operations
8928   // aren't the same.
8929   EVT VT = N->getValueType(0);
8930   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8931       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8932       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8933     return SDValue();
8934 
8935   // Now check that the other operand of the AND is a constant. We could
8936   // make the transformation for non-constant splats as well, but it's unclear
8937   // that would be a benefit as it would not eliminate any operations, just
8938   // perform one more step in scalar code before moving to the vector unit.
8939   if (BuildVectorSDNode *BV =
8940           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8941     // Bail out if the vector isn't a constant.
8942     if (!BV->isConstant())
8943       return SDValue();
8944 
8945     // Everything checks out. Build up the new and improved node.
8946     SDLoc DL(N);
8947     EVT IntVT = BV->getValueType(0);
8948     // Create a new constant of the appropriate type for the transformed
8949     // DAG.
8950     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8951     // The AND node needs bitcasts to/from an integer vector type around it.
8952     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8953     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8954                                  N->getOperand(0)->getOperand(0), MaskConst);
8955     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8956     return Res;
8957   }
8958 
8959   return SDValue();
8960 }
8961 
8962 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8963                                      const AArch64Subtarget *Subtarget) {
8964   // First try to optimize away the conversion when it's conditionally from
8965   // a constant. Vectors only.
8966   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8967     return Res;
8968 
8969   EVT VT = N->getValueType(0);
8970   if (VT != MVT::f32 && VT != MVT::f64)
8971     return SDValue();
8972 
8973   // Only optimize when the source and destination types have the same width.
8974   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8975     return SDValue();
8976 
8977   // If the result of an integer load is only used by an integer-to-float
8978   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8979   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8980   SDValue N0 = N->getOperand(0);
8981   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8982       // Do not change the width of a volatile load.
8983       !cast<LoadSDNode>(N0)->isVolatile()) {
8984     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8985     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8986                                LN0->getPointerInfo(), LN0->getAlignment(),
8987                                LN0->getMemOperand()->getFlags());
8988 
8989     // Make sure successors of the original load stay after it by updating them
8990     // to use the new Chain.
8991     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8992 
8993     unsigned Opcode =
8994         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8995     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8996   }
8997 
8998   return SDValue();
8999 }
9000 
9001 /// Fold a floating-point multiply by power of two into floating-point to
9002 /// fixed-point conversion.
9003 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9004                                      TargetLowering::DAGCombinerInfo &DCI,
9005                                      const AArch64Subtarget *Subtarget) {
9006   if (!Subtarget->hasNEON())
9007     return SDValue();
9008 
9009   SDValue Op = N->getOperand(0);
9010   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9011       Op.getOpcode() != ISD::FMUL)
9012     return SDValue();
9013 
9014   SDValue ConstVec = Op->getOperand(1);
9015   if (!isa<BuildVectorSDNode>(ConstVec))
9016     return SDValue();
9017 
9018   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9019   uint32_t FloatBits = FloatTy.getSizeInBits();
9020   if (FloatBits != 32 && FloatBits != 64)
9021     return SDValue();
9022 
9023   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9024   uint32_t IntBits = IntTy.getSizeInBits();
9025   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9026     return SDValue();
9027 
9028   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9029   if (IntBits > FloatBits)
9030     return SDValue();
9031 
9032   BitVector UndefElements;
9033   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9034   int32_t Bits = IntBits == 64 ? 64 : 32;
9035   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9036   if (C == -1 || C == 0 || C > Bits)
9037     return SDValue();
9038 
9039   MVT ResTy;
9040   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9041   switch (NumLanes) {
9042   default:
9043     return SDValue();
9044   case 2:
9045     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9046     break;
9047   case 4:
9048     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9049     break;
9050   }
9051 
9052   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9053     return SDValue();
9054 
9055   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9056          "Illegal vector type after legalization");
9057 
9058   SDLoc DL(N);
9059   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9060   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9061                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9062   SDValue FixConv =
9063       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9064                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9065                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9066   // We can handle smaller integers by generating an extra trunc.
9067   if (IntBits < FloatBits)
9068     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9069 
9070   return FixConv;
9071 }
9072 
9073 /// Fold a floating-point divide by power of two into fixed-point to
9074 /// floating-point conversion.
9075 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9076                                   TargetLowering::DAGCombinerInfo &DCI,
9077                                   const AArch64Subtarget *Subtarget) {
9078   if (!Subtarget->hasNEON())
9079     return SDValue();
9080 
9081   SDValue Op = N->getOperand(0);
9082   unsigned Opc = Op->getOpcode();
9083   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9084       !Op.getOperand(0).getValueType().isSimple() ||
9085       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9086     return SDValue();
9087 
9088   SDValue ConstVec = N->getOperand(1);
9089   if (!isa<BuildVectorSDNode>(ConstVec))
9090     return SDValue();
9091 
9092   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9093   int32_t IntBits = IntTy.getSizeInBits();
9094   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9095     return SDValue();
9096 
9097   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9098   int32_t FloatBits = FloatTy.getSizeInBits();
9099   if (FloatBits != 32 && FloatBits != 64)
9100     return SDValue();
9101 
9102   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9103   if (IntBits > FloatBits)
9104     return SDValue();
9105 
9106   BitVector UndefElements;
9107   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9108   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9109   if (C == -1 || C == 0 || C > FloatBits)
9110     return SDValue();
9111 
9112   MVT ResTy;
9113   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9114   switch (NumLanes) {
9115   default:
9116     return SDValue();
9117   case 2:
9118     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9119     break;
9120   case 4:
9121     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9122     break;
9123   }
9124 
9125   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9126     return SDValue();
9127 
9128   SDLoc DL(N);
9129   SDValue ConvInput = Op.getOperand(0);
9130   bool IsSigned = Opc == ISD::SINT_TO_FP;
9131   if (IntBits < FloatBits)
9132     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9133                             ResTy, ConvInput);
9134 
9135   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9136                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
9137   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9138                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9139                      DAG.getConstant(C, DL, MVT::i32));
9140 }
9141 
9142 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9143 /// searches for and classifies those shifts.
9144 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9145                          bool &FromHi) {
9146   if (N.getOpcode() == ISD::SHL)
9147     FromHi = false;
9148   else if (N.getOpcode() == ISD::SRL)
9149     FromHi = true;
9150   else
9151     return false;
9152 
9153   if (!isa<ConstantSDNode>(N.getOperand(1)))
9154     return false;
9155 
9156   ShiftAmount = N->getConstantOperandVal(1);
9157   Src = N->getOperand(0);
9158   return true;
9159 }
9160 
9161 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9162 /// registers viewed as a high/low pair. This function looks for the pattern:
9163 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9164 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9165 /// aren't independent.
9166 static SDValue tryCombineToEXTR(SDNode *N,
9167                                 TargetLowering::DAGCombinerInfo &DCI) {
9168   SelectionDAG &DAG = DCI.DAG;
9169   SDLoc DL(N);
9170   EVT VT = N->getValueType(0);
9171 
9172   assert(N->getOpcode() == ISD::OR && "Unexpected root");
9173 
9174   if (VT != MVT::i32 && VT != MVT::i64)
9175     return SDValue();
9176 
9177   SDValue LHS;
9178   uint32_t ShiftLHS = 0;
9179   bool LHSFromHi = false;
9180   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9181     return SDValue();
9182 
9183   SDValue RHS;
9184   uint32_t ShiftRHS = 0;
9185   bool RHSFromHi = false;
9186   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9187     return SDValue();
9188 
9189   // If they're both trying to come from the high part of the register, they're
9190   // not really an EXTR.
9191   if (LHSFromHi == RHSFromHi)
9192     return SDValue();
9193 
9194   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9195     return SDValue();
9196 
9197   if (LHSFromHi) {
9198     std::swap(LHS, RHS);
9199     std::swap(ShiftLHS, ShiftRHS);
9200   }
9201 
9202   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9203                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
9204 }
9205 
9206 static SDValue tryCombineToBSL(SDNode *N,
9207                                 TargetLowering::DAGCombinerInfo &DCI) {
9208   EVT VT = N->getValueType(0);
9209   SelectionDAG &DAG = DCI.DAG;
9210   SDLoc DL(N);
9211 
9212   if (!VT.isVector())
9213     return SDValue();
9214 
9215   SDValue N0 = N->getOperand(0);
9216   if (N0.getOpcode() != ISD::AND)
9217     return SDValue();
9218 
9219   SDValue N1 = N->getOperand(1);
9220   if (N1.getOpcode() != ISD::AND)
9221     return SDValue();
9222 
9223   // We only have to look for constant vectors here since the general, variable
9224   // case can be handled in TableGen.
9225   unsigned Bits = VT.getScalarSizeInBits();
9226   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9227   for (int i = 1; i >= 0; --i)
9228     for (int j = 1; j >= 0; --j) {
9229       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9230       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9231       if (!BVN0 || !BVN1)
9232         continue;
9233 
9234       bool FoundMatch = true;
9235       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9236         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9237         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9238         if (!CN0 || !CN1 ||
9239             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9240           FoundMatch = false;
9241           break;
9242         }
9243       }
9244 
9245       if (FoundMatch)
9246         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9247                            N0->getOperand(1 - i), N1->getOperand(1 - j));
9248     }
9249 
9250   return SDValue();
9251 }
9252 
9253 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9254                                 const AArch64Subtarget *Subtarget) {
9255   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9256   SelectionDAG &DAG = DCI.DAG;
9257   EVT VT = N->getValueType(0);
9258 
9259   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9260     return SDValue();
9261 
9262   if (SDValue Res = tryCombineToEXTR(N, DCI))
9263     return Res;
9264 
9265   if (SDValue Res = tryCombineToBSL(N, DCI))
9266     return Res;
9267 
9268   return SDValue();
9269 }
9270 
9271 static SDValue performSRLCombine(SDNode *N,
9272                                  TargetLowering::DAGCombinerInfo &DCI) {
9273   SelectionDAG &DAG = DCI.DAG;
9274   EVT VT = N->getValueType(0);
9275   if (VT != MVT::i32 && VT != MVT::i64)
9276     return SDValue();
9277 
9278   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9279   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9280   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9281   SDValue N0 = N->getOperand(0);
9282   if (N0.getOpcode() == ISD::BSWAP) {
9283     SDLoc DL(N);
9284     SDValue N1 = N->getOperand(1);
9285     SDValue N00 = N0.getOperand(0);
9286     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9287       uint64_t ShiftAmt = C->getZExtValue();
9288       if (VT == MVT::i32 && ShiftAmt == 16 &&
9289           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9290         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9291       if (VT == MVT::i64 && ShiftAmt == 32 &&
9292           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9293         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9294     }
9295   }
9296   return SDValue();
9297 }
9298 
9299 static SDValue performBitcastCombine(SDNode *N,
9300                                      TargetLowering::DAGCombinerInfo &DCI,
9301                                      SelectionDAG &DAG) {
9302   // Wait 'til after everything is legalized to try this. That way we have
9303   // legal vector types and such.
9304   if (DCI.isBeforeLegalizeOps())
9305     return SDValue();
9306 
9307   // Remove extraneous bitcasts around an extract_subvector.
9308   // For example,
9309   //    (v4i16 (bitconvert
9310   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9311   //  becomes
9312   //    (extract_subvector ((v8i16 ...), (i64 4)))
9313 
9314   // Only interested in 64-bit vectors as the ultimate result.
9315   EVT VT = N->getValueType(0);
9316   if (!VT.isVector())
9317     return SDValue();
9318   if (VT.getSimpleVT().getSizeInBits() != 64)
9319     return SDValue();
9320   // Is the operand an extract_subvector starting at the beginning or halfway
9321   // point of the vector? A low half may also come through as an
9322   // EXTRACT_SUBREG, so look for that, too.
9323   SDValue Op0 = N->getOperand(0);
9324   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9325       !(Op0->isMachineOpcode() &&
9326         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9327     return SDValue();
9328   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9329   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9330     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9331       return SDValue();
9332   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9333     if (idx != AArch64::dsub)
9334       return SDValue();
9335     // The dsub reference is equivalent to a lane zero subvector reference.
9336     idx = 0;
9337   }
9338   // Look through the bitcast of the input to the extract.
9339   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9340     return SDValue();
9341   SDValue Source = Op0->getOperand(0)->getOperand(0);
9342   // If the source type has twice the number of elements as our destination
9343   // type, we know this is an extract of the high or low half of the vector.
9344   EVT SVT = Source->getValueType(0);
9345   if (!SVT.isVector() ||
9346       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9347     return SDValue();
9348 
9349   LLVM_DEBUG(
9350       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9351 
9352   // Create the simplified form to just extract the low or high half of the
9353   // vector directly rather than bothering with the bitcasts.
9354   SDLoc dl(N);
9355   unsigned NumElements = VT.getVectorNumElements();
9356   if (idx) {
9357     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9358     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9359   } else {
9360     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9361     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9362                                       Source, SubReg),
9363                    0);
9364   }
9365 }
9366 
9367 static SDValue performConcatVectorsCombine(SDNode *N,
9368                                            TargetLowering::DAGCombinerInfo &DCI,
9369                                            SelectionDAG &DAG) {
9370   SDLoc dl(N);
9371   EVT VT = N->getValueType(0);
9372   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9373 
9374   // Optimize concat_vectors of truncated vectors, where the intermediate
9375   // type is illegal, to avoid said illegality,  e.g.,
9376   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9377   //                          (v2i16 (truncate (v2i64)))))
9378   // ->
9379   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9380   //                                    (v4i32 (bitcast (v2i64))),
9381   //                                    <0, 2, 4, 6>)))
9382   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9383   // on both input and result type, so we might generate worse code.
9384   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9385   if (N->getNumOperands() == 2 &&
9386       N0->getOpcode() == ISD::TRUNCATE &&
9387       N1->getOpcode() == ISD::TRUNCATE) {
9388     SDValue N00 = N0->getOperand(0);
9389     SDValue N10 = N1->getOperand(0);
9390     EVT N00VT = N00.getValueType();
9391 
9392     if (N00VT == N10.getValueType() &&
9393         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9394         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9395       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9396       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9397       for (size_t i = 0; i < Mask.size(); ++i)
9398         Mask[i] = i * 2;
9399       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9400                          DAG.getVectorShuffle(
9401                              MidVT, dl,
9402                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9403                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9404     }
9405   }
9406 
9407   // Wait 'til after everything is legalized to try this. That way we have
9408   // legal vector types and such.
9409   if (DCI.isBeforeLegalizeOps())
9410     return SDValue();
9411 
9412   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9413   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9414   // canonicalise to that.
9415   if (N0 == N1 && VT.getVectorNumElements() == 2) {
9416     assert(VT.getScalarSizeInBits() == 64);
9417     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9418                        DAG.getConstant(0, dl, MVT::i64));
9419   }
9420 
9421   // Canonicalise concat_vectors so that the right-hand vector has as few
9422   // bit-casts as possible before its real operation. The primary matching
9423   // destination for these operations will be the narrowing "2" instructions,
9424   // which depend on the operation being performed on this right-hand vector.
9425   // For example,
9426   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
9427   // becomes
9428   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9429 
9430   if (N1->getOpcode() != ISD::BITCAST)
9431     return SDValue();
9432   SDValue RHS = N1->getOperand(0);
9433   MVT RHSTy = RHS.getValueType().getSimpleVT();
9434   // If the RHS is not a vector, this is not the pattern we're looking for.
9435   if (!RHSTy.isVector())
9436     return SDValue();
9437 
9438   LLVM_DEBUG(
9439       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9440 
9441   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9442                                   RHSTy.getVectorNumElements() * 2);
9443   return DAG.getNode(ISD::BITCAST, dl, VT,
9444                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9445                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9446                                  RHS));
9447 }
9448 
9449 static SDValue tryCombineFixedPointConvert(SDNode *N,
9450                                            TargetLowering::DAGCombinerInfo &DCI,
9451                                            SelectionDAG &DAG) {
9452   // Wait until after everything is legalized to try this. That way we have
9453   // legal vector types and such.
9454   if (DCI.isBeforeLegalizeOps())
9455     return SDValue();
9456   // Transform a scalar conversion of a value from a lane extract into a
9457   // lane extract of a vector conversion. E.g., from foo1 to foo2:
9458   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9459   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9460   //
9461   // The second form interacts better with instruction selection and the
9462   // register allocator to avoid cross-class register copies that aren't
9463   // coalescable due to a lane reference.
9464 
9465   // Check the operand and see if it originates from a lane extract.
9466   SDValue Op1 = N->getOperand(1);
9467   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9468     // Yep, no additional predication needed. Perform the transform.
9469     SDValue IID = N->getOperand(0);
9470     SDValue Shift = N->getOperand(2);
9471     SDValue Vec = Op1.getOperand(0);
9472     SDValue Lane = Op1.getOperand(1);
9473     EVT ResTy = N->getValueType(0);
9474     EVT VecResTy;
9475     SDLoc DL(N);
9476 
9477     // The vector width should be 128 bits by the time we get here, even
9478     // if it started as 64 bits (the extract_vector handling will have
9479     // done so).
9480     assert(Vec.getValueSizeInBits() == 128 &&
9481            "unexpected vector size on extract_vector_elt!");
9482     if (Vec.getValueType() == MVT::v4i32)
9483       VecResTy = MVT::v4f32;
9484     else if (Vec.getValueType() == MVT::v2i64)
9485       VecResTy = MVT::v2f64;
9486     else
9487       llvm_unreachable("unexpected vector type!");
9488 
9489     SDValue Convert =
9490         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9491     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9492   }
9493   return SDValue();
9494 }
9495 
9496 // AArch64 high-vector "long" operations are formed by performing the non-high
9497 // version on an extract_subvector of each operand which gets the high half:
9498 //
9499 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9500 //
9501 // However, there are cases which don't have an extract_high explicitly, but
9502 // have another operation that can be made compatible with one for free. For
9503 // example:
9504 //
9505 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
9506 //
9507 // This routine does the actual conversion of such DUPs, once outer routines
9508 // have determined that everything else is in order.
9509 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9510 // similarly here.
9511 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9512   switch (N.getOpcode()) {
9513   case AArch64ISD::DUP:
9514   case AArch64ISD::DUPLANE8:
9515   case AArch64ISD::DUPLANE16:
9516   case AArch64ISD::DUPLANE32:
9517   case AArch64ISD::DUPLANE64:
9518   case AArch64ISD::MOVI:
9519   case AArch64ISD::MOVIshift:
9520   case AArch64ISD::MOVIedit:
9521   case AArch64ISD::MOVImsl:
9522   case AArch64ISD::MVNIshift:
9523   case AArch64ISD::MVNImsl:
9524     break;
9525   default:
9526     // FMOV could be supported, but isn't very useful, as it would only occur
9527     // if you passed a bitcast' floating point immediate to an eligible long
9528     // integer op (addl, smull, ...).
9529     return SDValue();
9530   }
9531 
9532   MVT NarrowTy = N.getSimpleValueType();
9533   if (!NarrowTy.is64BitVector())
9534     return SDValue();
9535 
9536   MVT ElementTy = NarrowTy.getVectorElementType();
9537   unsigned NumElems = NarrowTy.getVectorNumElements();
9538   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9539 
9540   SDLoc dl(N);
9541   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9542                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9543                      DAG.getConstant(NumElems, dl, MVT::i64));
9544 }
9545 
9546 static bool isEssentiallyExtractSubvector(SDValue N) {
9547   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9548     return true;
9549 
9550   return N.getOpcode() == ISD::BITCAST &&
9551          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9552 }
9553 
9554 /// Helper structure to keep track of ISD::SET_CC operands.
9555 struct GenericSetCCInfo {
9556   const SDValue *Opnd0;
9557   const SDValue *Opnd1;
9558   ISD::CondCode CC;
9559 };
9560 
9561 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9562 struct AArch64SetCCInfo {
9563   const SDValue *Cmp;
9564   AArch64CC::CondCode CC;
9565 };
9566 
9567 /// Helper structure to keep track of SetCC information.
9568 union SetCCInfo {
9569   GenericSetCCInfo Generic;
9570   AArch64SetCCInfo AArch64;
9571 };
9572 
9573 /// Helper structure to be able to read SetCC information.  If set to
9574 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9575 /// GenericSetCCInfo.
9576 struct SetCCInfoAndKind {
9577   SetCCInfo Info;
9578   bool IsAArch64;
9579 };
9580 
9581 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9582 /// an
9583 /// AArch64 lowered one.
9584 /// \p SetCCInfo is filled accordingly.
9585 /// \post SetCCInfo is meanginfull only when this function returns true.
9586 /// \return True when Op is a kind of SET_CC operation.
9587 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9588   // If this is a setcc, this is straight forward.
9589   if (Op.getOpcode() == ISD::SETCC) {
9590     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9591     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9592     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9593     SetCCInfo.IsAArch64 = false;
9594     return true;
9595   }
9596   // Otherwise, check if this is a matching csel instruction.
9597   // In other words:
9598   // - csel 1, 0, cc
9599   // - csel 0, 1, !cc
9600   if (Op.getOpcode() != AArch64ISD::CSEL)
9601     return false;
9602   // Set the information about the operands.
9603   // TODO: we want the operands of the Cmp not the csel
9604   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9605   SetCCInfo.IsAArch64 = true;
9606   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9607       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9608 
9609   // Check that the operands matches the constraints:
9610   // (1) Both operands must be constants.
9611   // (2) One must be 1 and the other must be 0.
9612   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9613   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9614 
9615   // Check (1).
9616   if (!TValue || !FValue)
9617     return false;
9618 
9619   // Check (2).
9620   if (!TValue->isOne()) {
9621     // Update the comparison when we are interested in !cc.
9622     std::swap(TValue, FValue);
9623     SetCCInfo.Info.AArch64.CC =
9624         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9625   }
9626   return TValue->isOne() && FValue->isNullValue();
9627 }
9628 
9629 // Returns true if Op is setcc or zext of setcc.
9630 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9631   if (isSetCC(Op, Info))
9632     return true;
9633   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9634     isSetCC(Op->getOperand(0), Info));
9635 }
9636 
9637 // The folding we want to perform is:
9638 // (add x, [zext] (setcc cc ...) )
9639 //   -->
9640 // (csel x, (add x, 1), !cc ...)
9641 //
9642 // The latter will get matched to a CSINC instruction.
9643 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9644   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9645   SDValue LHS = Op->getOperand(0);
9646   SDValue RHS = Op->getOperand(1);
9647   SetCCInfoAndKind InfoAndKind;
9648 
9649   // If neither operand is a SET_CC, give up.
9650   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9651     std::swap(LHS, RHS);
9652     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9653       return SDValue();
9654   }
9655 
9656   // FIXME: This could be generatized to work for FP comparisons.
9657   EVT CmpVT = InfoAndKind.IsAArch64
9658                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9659                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
9660   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9661     return SDValue();
9662 
9663   SDValue CCVal;
9664   SDValue Cmp;
9665   SDLoc dl(Op);
9666   if (InfoAndKind.IsAArch64) {
9667     CCVal = DAG.getConstant(
9668         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9669         MVT::i32);
9670     Cmp = *InfoAndKind.Info.AArch64.Cmp;
9671   } else
9672     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9673                       *InfoAndKind.Info.Generic.Opnd1,
9674                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9675                       CCVal, DAG, dl);
9676 
9677   EVT VT = Op->getValueType(0);
9678   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
9679   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9680 }
9681 
9682 // The basic add/sub long vector instructions have variants with "2" on the end
9683 // which act on the high-half of their inputs. They are normally matched by
9684 // patterns like:
9685 //
9686 // (add (zeroext (extract_high LHS)),
9687 //      (zeroext (extract_high RHS)))
9688 // -> uaddl2 vD, vN, vM
9689 //
9690 // However, if one of the extracts is something like a duplicate, this
9691 // instruction can still be used profitably. This function puts the DAG into a
9692 // more appropriate form for those patterns to trigger.
9693 static SDValue performAddSubLongCombine(SDNode *N,
9694                                         TargetLowering::DAGCombinerInfo &DCI,
9695                                         SelectionDAG &DAG) {
9696   if (DCI.isBeforeLegalizeOps())
9697     return SDValue();
9698 
9699   MVT VT = N->getSimpleValueType(0);
9700   if (!VT.is128BitVector()) {
9701     if (N->getOpcode() == ISD::ADD)
9702       return performSetccAddFolding(N, DAG);
9703     return SDValue();
9704   }
9705 
9706   // Make sure both branches are extended in the same way.
9707   SDValue LHS = N->getOperand(0);
9708   SDValue RHS = N->getOperand(1);
9709   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9710        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9711       LHS.getOpcode() != RHS.getOpcode())
9712     return SDValue();
9713 
9714   unsigned ExtType = LHS.getOpcode();
9715 
9716   // It's not worth doing if at least one of the inputs isn't already an
9717   // extract, but we don't know which it'll be so we have to try both.
9718   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9719     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9720     if (!RHS.getNode())
9721       return SDValue();
9722 
9723     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9724   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9725     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9726     if (!LHS.getNode())
9727       return SDValue();
9728 
9729     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9730   }
9731 
9732   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9733 }
9734 
9735 // Massage DAGs which we can use the high-half "long" operations on into
9736 // something isel will recognize better. E.g.
9737 //
9738 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9739 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
9740 //                     (extract_high (v2i64 (dup128 scalar)))))
9741 //
9742 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
9743                                        TargetLowering::DAGCombinerInfo &DCI,
9744                                        SelectionDAG &DAG) {
9745   if (DCI.isBeforeLegalizeOps())
9746     return SDValue();
9747 
9748   SDValue LHS = N->getOperand(1);
9749   SDValue RHS = N->getOperand(2);
9750   assert(LHS.getValueType().is64BitVector() &&
9751          RHS.getValueType().is64BitVector() &&
9752          "unexpected shape for long operation");
9753 
9754   // Either node could be a DUP, but it's not worth doing both of them (you'd
9755   // just as well use the non-high version) so look for a corresponding extract
9756   // operation on the other "wing".
9757   if (isEssentiallyExtractSubvector(LHS)) {
9758     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9759     if (!RHS.getNode())
9760       return SDValue();
9761   } else if (isEssentiallyExtractSubvector(RHS)) {
9762     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9763     if (!LHS.getNode())
9764       return SDValue();
9765   }
9766 
9767   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9768                      N->getOperand(0), LHS, RHS);
9769 }
9770 
9771 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9772   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9773   unsigned ElemBits = ElemTy.getSizeInBits();
9774 
9775   int64_t ShiftAmount;
9776   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9777     APInt SplatValue, SplatUndef;
9778     unsigned SplatBitSize;
9779     bool HasAnyUndefs;
9780     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9781                               HasAnyUndefs, ElemBits) ||
9782         SplatBitSize != ElemBits)
9783       return SDValue();
9784 
9785     ShiftAmount = SplatValue.getSExtValue();
9786   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9787     ShiftAmount = CVN->getSExtValue();
9788   } else
9789     return SDValue();
9790 
9791   unsigned Opcode;
9792   bool IsRightShift;
9793   switch (IID) {
9794   default:
9795     llvm_unreachable("Unknown shift intrinsic");
9796   case Intrinsic::aarch64_neon_sqshl:
9797     Opcode = AArch64ISD::SQSHL_I;
9798     IsRightShift = false;
9799     break;
9800   case Intrinsic::aarch64_neon_uqshl:
9801     Opcode = AArch64ISD::UQSHL_I;
9802     IsRightShift = false;
9803     break;
9804   case Intrinsic::aarch64_neon_srshl:
9805     Opcode = AArch64ISD::SRSHR_I;
9806     IsRightShift = true;
9807     break;
9808   case Intrinsic::aarch64_neon_urshl:
9809     Opcode = AArch64ISD::URSHR_I;
9810     IsRightShift = true;
9811     break;
9812   case Intrinsic::aarch64_neon_sqshlu:
9813     Opcode = AArch64ISD::SQSHLU_I;
9814     IsRightShift = false;
9815     break;
9816   }
9817 
9818   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9819     SDLoc dl(N);
9820     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9821                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9822   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9823     SDLoc dl(N);
9824     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9825                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
9826   }
9827 
9828   return SDValue();
9829 }
9830 
9831 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9832 // the intrinsics must be legal and take an i32, this means there's almost
9833 // certainly going to be a zext in the DAG which we can eliminate.
9834 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9835   SDValue AndN = N->getOperand(2);
9836   if (AndN.getOpcode() != ISD::AND)
9837     return SDValue();
9838 
9839   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9840   if (!CMask || CMask->getZExtValue() != Mask)
9841     return SDValue();
9842 
9843   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9844                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9845 }
9846 
9847 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9848                                            SelectionDAG &DAG) {
9849   SDLoc dl(N);
9850   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9851                      DAG.getNode(Opc, dl,
9852                                  N->getOperand(1).getSimpleValueType(),
9853                                  N->getOperand(1)),
9854                      DAG.getConstant(0, dl, MVT::i64));
9855 }
9856 
9857 static SDValue performIntrinsicCombine(SDNode *N,
9858                                        TargetLowering::DAGCombinerInfo &DCI,
9859                                        const AArch64Subtarget *Subtarget) {
9860   SelectionDAG &DAG = DCI.DAG;
9861   unsigned IID = getIntrinsicID(N);
9862   switch (IID) {
9863   default:
9864     break;
9865   case Intrinsic::aarch64_neon_vcvtfxs2fp:
9866   case Intrinsic::aarch64_neon_vcvtfxu2fp:
9867     return tryCombineFixedPointConvert(N, DCI, DAG);
9868   case Intrinsic::aarch64_neon_saddv:
9869     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9870   case Intrinsic::aarch64_neon_uaddv:
9871     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9872   case Intrinsic::aarch64_neon_sminv:
9873     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9874   case Intrinsic::aarch64_neon_uminv:
9875     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9876   case Intrinsic::aarch64_neon_smaxv:
9877     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9878   case Intrinsic::aarch64_neon_umaxv:
9879     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9880   case Intrinsic::aarch64_neon_fmax:
9881     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
9882                        N->getOperand(1), N->getOperand(2));
9883   case Intrinsic::aarch64_neon_fmin:
9884     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
9885                        N->getOperand(1), N->getOperand(2));
9886   case Intrinsic::aarch64_neon_fmaxnm:
9887     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9888                        N->getOperand(1), N->getOperand(2));
9889   case Intrinsic::aarch64_neon_fminnm:
9890     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9891                        N->getOperand(1), N->getOperand(2));
9892   case Intrinsic::aarch64_neon_smull:
9893   case Intrinsic::aarch64_neon_umull:
9894   case Intrinsic::aarch64_neon_pmull:
9895   case Intrinsic::aarch64_neon_sqdmull:
9896     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9897   case Intrinsic::aarch64_neon_sqshl:
9898   case Intrinsic::aarch64_neon_uqshl:
9899   case Intrinsic::aarch64_neon_sqshlu:
9900   case Intrinsic::aarch64_neon_srshl:
9901   case Intrinsic::aarch64_neon_urshl:
9902     return tryCombineShiftImm(IID, N, DAG);
9903   case Intrinsic::aarch64_crc32b:
9904   case Intrinsic::aarch64_crc32cb:
9905     return tryCombineCRC32(0xff, N, DAG);
9906   case Intrinsic::aarch64_crc32h:
9907   case Intrinsic::aarch64_crc32ch:
9908     return tryCombineCRC32(0xffff, N, DAG);
9909   }
9910   return SDValue();
9911 }
9912 
9913 static SDValue performExtendCombine(SDNode *N,
9914                                     TargetLowering::DAGCombinerInfo &DCI,
9915                                     SelectionDAG &DAG) {
9916   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9917   // we can convert that DUP into another extract_high (of a bigger DUP), which
9918   // helps the backend to decide that an sabdl2 would be useful, saving a real
9919   // extract_high operation.
9920   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9921       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9922     SDNode *ABDNode = N->getOperand(0).getNode();
9923     unsigned IID = getIntrinsicID(ABDNode);
9924     if (IID == Intrinsic::aarch64_neon_sabd ||
9925         IID == Intrinsic::aarch64_neon_uabd) {
9926       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9927       if (!NewABD.getNode())
9928         return SDValue();
9929 
9930       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9931                          NewABD);
9932     }
9933   }
9934 
9935   // This is effectively a custom type legalization for AArch64.
9936   //
9937   // Type legalization will split an extend of a small, legal, type to a larger
9938   // illegal type by first splitting the destination type, often creating
9939   // illegal source types, which then get legalized in isel-confusing ways,
9940   // leading to really terrible codegen. E.g.,
9941   //   %result = v8i32 sext v8i8 %value
9942   // becomes
9943   //   %losrc = extract_subreg %value, ...
9944   //   %hisrc = extract_subreg %value, ...
9945   //   %lo = v4i32 sext v4i8 %losrc
9946   //   %hi = v4i32 sext v4i8 %hisrc
9947   // Things go rapidly downhill from there.
9948   //
9949   // For AArch64, the [sz]ext vector instructions can only go up one element
9950   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9951   // take two instructions.
9952   //
9953   // This implies that the most efficient way to do the extend from v8i8
9954   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9955   // the normal splitting to happen for the v8i16->v8i32.
9956 
9957   // This is pre-legalization to catch some cases where the default
9958   // type legalization will create ill-tempered code.
9959   if (!DCI.isBeforeLegalizeOps())
9960     return SDValue();
9961 
9962   // We're only interested in cleaning things up for non-legal vector types
9963   // here. If both the source and destination are legal, things will just
9964   // work naturally without any fiddling.
9965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9966   EVT ResVT = N->getValueType(0);
9967   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9968     return SDValue();
9969   // If the vector type isn't a simple VT, it's beyond the scope of what
9970   // we're  worried about here. Let legalization do its thing and hope for
9971   // the best.
9972   SDValue Src = N->getOperand(0);
9973   EVT SrcVT = Src->getValueType(0);
9974   if (!ResVT.isSimple() || !SrcVT.isSimple())
9975     return SDValue();
9976 
9977   // If the source VT is a 64-bit vector, we can play games and get the
9978   // better results we want.
9979   if (SrcVT.getSizeInBits() != 64)
9980     return SDValue();
9981 
9982   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9983   unsigned ElementCount = SrcVT.getVectorNumElements();
9984   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9985   SDLoc DL(N);
9986   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9987 
9988   // Now split the rest of the operation into two halves, each with a 64
9989   // bit source.
9990   EVT LoVT, HiVT;
9991   SDValue Lo, Hi;
9992   unsigned NumElements = ResVT.getVectorNumElements();
9993   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9994   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9995                                  ResVT.getVectorElementType(), NumElements / 2);
9996 
9997   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9998                                LoVT.getVectorNumElements());
9999   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10000                    DAG.getConstant(0, DL, MVT::i64));
10001   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10002                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10003   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10004   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10005 
10006   // Now combine the parts back together so we still have a single result
10007   // like the combiner expects.
10008   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10009 }
10010 
10011 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10012                                SDValue SplatVal, unsigned NumVecElts) {
10013   unsigned OrigAlignment = St.getAlignment();
10014   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10015 
10016   // Create scalar stores. This is at least as good as the code sequence for a
10017   // split unaligned store which is a dup.s, ext.b, and two stores.
10018   // Most of the time the three stores should be replaced by store pair
10019   // instructions (stp).
10020   SDLoc DL(&St);
10021   SDValue BasePtr = St.getBasePtr();
10022   uint64_t BaseOffset = 0;
10023 
10024   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10025   SDValue NewST1 =
10026       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10027                    OrigAlignment, St.getMemOperand()->getFlags());
10028 
10029   // As this in ISel, we will not merge this add which may degrade results.
10030   if (BasePtr->getOpcode() == ISD::ADD &&
10031       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10032     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10033     BasePtr = BasePtr->getOperand(0);
10034   }
10035 
10036   unsigned Offset = EltOffset;
10037   while (--NumVecElts) {
10038     unsigned Alignment = MinAlign(OrigAlignment, Offset);
10039     SDValue OffsetPtr =
10040         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10041                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10042     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10043                           PtrInfo.getWithOffset(Offset), Alignment,
10044                           St.getMemOperand()->getFlags());
10045     Offset += EltOffset;
10046   }
10047   return NewST1;
10048 }
10049 
10050 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
10051 /// load store optimizer pass will merge them to store pair stores.  This should
10052 /// be better than a movi to create the vector zero followed by a vector store
10053 /// if the zero constant is not re-used, since one instructions and one register
10054 /// live range will be removed.
10055 ///
10056 /// For example, the final generated code should be:
10057 ///
10058 ///   stp xzr, xzr, [x0]
10059 ///
10060 /// instead of:
10061 ///
10062 ///   movi v0.2d, #0
10063 ///   str q0, [x0]
10064 ///
10065 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10066   SDValue StVal = St.getValue();
10067   EVT VT = StVal.getValueType();
10068 
10069   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10070   // 2, 3 or 4 i32 elements.
10071   int NumVecElts = VT.getVectorNumElements();
10072   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10073          VT.getVectorElementType().getSizeInBits() == 64) ||
10074         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10075          VT.getVectorElementType().getSizeInBits() == 32)))
10076     return SDValue();
10077 
10078   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10079     return SDValue();
10080 
10081   // If the zero constant has more than one use then the vector store could be
10082   // better since the constant mov will be amortized and stp q instructions
10083   // should be able to be formed.
10084   if (!StVal.hasOneUse())
10085     return SDValue();
10086 
10087   // If the immediate offset of the address operand is too large for the stp
10088   // instruction, then bail out.
10089   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10090     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10091     if (Offset < -512 || Offset > 504)
10092       return SDValue();
10093   }
10094 
10095   for (int I = 0; I < NumVecElts; ++I) {
10096     SDValue EltVal = StVal.getOperand(I);
10097     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10098       return SDValue();
10099   }
10100 
10101   // Use a CopyFromReg WZR/XZR here to prevent
10102   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10103   SDLoc DL(&St);
10104   unsigned ZeroReg;
10105   EVT ZeroVT;
10106   if (VT.getVectorElementType().getSizeInBits() == 32) {
10107     ZeroReg = AArch64::WZR;
10108     ZeroVT = MVT::i32;
10109   } else {
10110     ZeroReg = AArch64::XZR;
10111     ZeroVT = MVT::i64;
10112   }
10113   SDValue SplatVal =
10114       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10115   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10116 }
10117 
10118 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10119 /// value. The load store optimizer pass will merge them to store pair stores.
10120 /// This has better performance than a splat of the scalar followed by a split
10121 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10122 /// followed by an ext.b and two stores.
10123 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10124   SDValue StVal = St.getValue();
10125   EVT VT = StVal.getValueType();
10126 
10127   // Don't replace floating point stores, they possibly won't be transformed to
10128   // stp because of the store pair suppress pass.
10129   if (VT.isFloatingPoint())
10130     return SDValue();
10131 
10132   // We can express a splat as store pair(s) for 2 or 4 elements.
10133   unsigned NumVecElts = VT.getVectorNumElements();
10134   if (NumVecElts != 4 && NumVecElts != 2)
10135     return SDValue();
10136 
10137   // Check that this is a splat.
10138   // Make sure that each of the relevant vector element locations are inserted
10139   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10140   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10141   SDValue SplatVal;
10142   for (unsigned I = 0; I < NumVecElts; ++I) {
10143     // Check for insert vector elements.
10144     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10145       return SDValue();
10146 
10147     // Check that same value is inserted at each vector element.
10148     if (I == 0)
10149       SplatVal = StVal.getOperand(1);
10150     else if (StVal.getOperand(1) != SplatVal)
10151       return SDValue();
10152 
10153     // Check insert element index.
10154     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10155     if (!CIndex)
10156       return SDValue();
10157     uint64_t IndexVal = CIndex->getZExtValue();
10158     if (IndexVal >= NumVecElts)
10159       return SDValue();
10160     IndexNotInserted.reset(IndexVal);
10161 
10162     StVal = StVal.getOperand(0);
10163   }
10164   // Check that all vector element locations were inserted to.
10165   if (IndexNotInserted.any())
10166       return SDValue();
10167 
10168   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10169 }
10170 
10171 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10172                            SelectionDAG &DAG,
10173                            const AArch64Subtarget *Subtarget) {
10174 
10175   StoreSDNode *S = cast<StoreSDNode>(N);
10176   if (S->isVolatile() || S->isIndexed())
10177     return SDValue();
10178 
10179   SDValue StVal = S->getValue();
10180   EVT VT = StVal.getValueType();
10181   if (!VT.isVector())
10182     return SDValue();
10183 
10184   // If we get a splat of zeros, convert this vector store to a store of
10185   // scalars. They will be merged into store pairs of xzr thereby removing one
10186   // instruction and one register.
10187   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10188     return ReplacedZeroSplat;
10189 
10190   // FIXME: The logic for deciding if an unaligned store should be split should
10191   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10192   // a call to that function here.
10193 
10194   if (!Subtarget->isMisaligned128StoreSlow())
10195     return SDValue();
10196 
10197   // Don't split at -Oz.
10198   if (DAG.getMachineFunction().getFunction().optForMinSize())
10199     return SDValue();
10200 
10201   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10202   // those up regresses performance on micro-benchmarks and olden/bh.
10203   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10204     return SDValue();
10205 
10206   // Split unaligned 16B stores. They are terrible for performance.
10207   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10208   // extensions can use this to mark that it does not want splitting to happen
10209   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10210   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10211   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10212       S->getAlignment() <= 2)
10213     return SDValue();
10214 
10215   // If we get a splat of a scalar convert this vector store to a store of
10216   // scalars. They will be merged into store pairs thereby removing two
10217   // instructions.
10218   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10219     return ReplacedSplat;
10220 
10221   SDLoc DL(S);
10222   unsigned NumElts = VT.getVectorNumElements() / 2;
10223   // Split VT into two.
10224   EVT HalfVT =
10225       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10226   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10227                                    DAG.getConstant(0, DL, MVT::i64));
10228   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10229                                    DAG.getConstant(NumElts, DL, MVT::i64));
10230   SDValue BasePtr = S->getBasePtr();
10231   SDValue NewST1 =
10232       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10233                    S->getAlignment(), S->getMemOperand()->getFlags());
10234   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10235                                   DAG.getConstant(8, DL, MVT::i64));
10236   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10237                       S->getPointerInfo(), S->getAlignment(),
10238                       S->getMemOperand()->getFlags());
10239 }
10240 
10241 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10242 /// post-increment LD1R.
10243 static SDValue performPostLD1Combine(SDNode *N,
10244                                      TargetLowering::DAGCombinerInfo &DCI,
10245                                      bool IsLaneOp) {
10246   if (DCI.isBeforeLegalizeOps())
10247     return SDValue();
10248 
10249   SelectionDAG &DAG = DCI.DAG;
10250   EVT VT = N->getValueType(0);
10251 
10252   unsigned LoadIdx = IsLaneOp ? 1 : 0;
10253   SDNode *LD = N->getOperand(LoadIdx).getNode();
10254   // If it is not LOAD, can not do such combine.
10255   if (LD->getOpcode() != ISD::LOAD)
10256     return SDValue();
10257 
10258   // The vector lane must be a constant in the LD1LANE opcode.
10259   SDValue Lane;
10260   if (IsLaneOp) {
10261     Lane = N->getOperand(2);
10262     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10263     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10264       return SDValue();
10265   }
10266 
10267   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10268   EVT MemVT = LoadSDN->getMemoryVT();
10269   // Check if memory operand is the same type as the vector element.
10270   if (MemVT != VT.getVectorElementType())
10271     return SDValue();
10272 
10273   // Check if there are other uses. If so, do not combine as it will introduce
10274   // an extra load.
10275   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10276        ++UI) {
10277     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10278       continue;
10279     if (*UI != N)
10280       return SDValue();
10281   }
10282 
10283   SDValue Addr = LD->getOperand(1);
10284   SDValue Vector = N->getOperand(0);
10285   // Search for a use of the address operand that is an increment.
10286   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10287        Addr.getNode()->use_end(); UI != UE; ++UI) {
10288     SDNode *User = *UI;
10289     if (User->getOpcode() != ISD::ADD
10290         || UI.getUse().getResNo() != Addr.getResNo())
10291       continue;
10292 
10293     // If the increment is a constant, it must match the memory ref size.
10294     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10295     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10296       uint32_t IncVal = CInc->getZExtValue();
10297       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10298       if (IncVal != NumBytes)
10299         continue;
10300       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10301     }
10302 
10303     // To avoid cycle construction make sure that neither the load nor the add
10304     // are predecessors to each other or the Vector.
10305     SmallPtrSet<const SDNode *, 32> Visited;
10306     SmallVector<const SDNode *, 16> Worklist;
10307     Visited.insert(N);
10308     Worklist.push_back(User);
10309     Worklist.push_back(LD);
10310     Worklist.push_back(Vector.getNode());
10311     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10312         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10313       continue;
10314 
10315     SmallVector<SDValue, 8> Ops;
10316     Ops.push_back(LD->getOperand(0));  // Chain
10317     if (IsLaneOp) {
10318       Ops.push_back(Vector);           // The vector to be inserted
10319       Ops.push_back(Lane);             // The lane to be inserted in the vector
10320     }
10321     Ops.push_back(Addr);
10322     Ops.push_back(Inc);
10323 
10324     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10325     SDVTList SDTys = DAG.getVTList(Tys);
10326     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10327     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10328                                            MemVT,
10329                                            LoadSDN->getMemOperand());
10330 
10331     // Update the uses.
10332     SDValue NewResults[] = {
10333         SDValue(LD, 0),            // The result of load
10334         SDValue(UpdN.getNode(), 2) // Chain
10335     };
10336     DCI.CombineTo(LD, NewResults);
10337     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
10338     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
10339 
10340     break;
10341   }
10342   return SDValue();
10343 }
10344 
10345 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10346 /// address translation.
10347 static bool performTBISimplification(SDValue Addr,
10348                                      TargetLowering::DAGCombinerInfo &DCI,
10349                                      SelectionDAG &DAG) {
10350   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10351   KnownBits Known;
10352   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10353                                         !DCI.isBeforeLegalizeOps());
10354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10355   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10356     DCI.CommitTargetLoweringOpt(TLO);
10357     return true;
10358   }
10359   return false;
10360 }
10361 
10362 static SDValue performSTORECombine(SDNode *N,
10363                                    TargetLowering::DAGCombinerInfo &DCI,
10364                                    SelectionDAG &DAG,
10365                                    const AArch64Subtarget *Subtarget) {
10366   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10367     return Split;
10368 
10369   if (Subtarget->supportsAddressTopByteIgnored() &&
10370       performTBISimplification(N->getOperand(2), DCI, DAG))
10371     return SDValue(N, 0);
10372 
10373   return SDValue();
10374 }
10375 
10376 
10377 /// Target-specific DAG combine function for NEON load/store intrinsics
10378 /// to merge base address updates.
10379 static SDValue performNEONPostLDSTCombine(SDNode *N,
10380                                           TargetLowering::DAGCombinerInfo &DCI,
10381                                           SelectionDAG &DAG) {
10382   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10383     return SDValue();
10384 
10385   unsigned AddrOpIdx = N->getNumOperands() - 1;
10386   SDValue Addr = N->getOperand(AddrOpIdx);
10387 
10388   // Search for a use of the address operand that is an increment.
10389   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10390        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10391     SDNode *User = *UI;
10392     if (User->getOpcode() != ISD::ADD ||
10393         UI.getUse().getResNo() != Addr.getResNo())
10394       continue;
10395 
10396     // Check that the add is independent of the load/store.  Otherwise, folding
10397     // it would create a cycle.
10398     SmallPtrSet<const SDNode *, 32> Visited;
10399     SmallVector<const SDNode *, 16> Worklist;
10400     Visited.insert(Addr.getNode());
10401     Worklist.push_back(N);
10402     Worklist.push_back(User);
10403     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10404         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10405       continue;
10406 
10407     // Find the new opcode for the updating load/store.
10408     bool IsStore = false;
10409     bool IsLaneOp = false;
10410     bool IsDupOp = false;
10411     unsigned NewOpc = 0;
10412     unsigned NumVecs = 0;
10413     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10414     switch (IntNo) {
10415     default: llvm_unreachable("unexpected intrinsic for Neon base update");
10416     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
10417       NumVecs = 2; break;
10418     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
10419       NumVecs = 3; break;
10420     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
10421       NumVecs = 4; break;
10422     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
10423       NumVecs = 2; IsStore = true; break;
10424     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
10425       NumVecs = 3; IsStore = true; break;
10426     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
10427       NumVecs = 4; IsStore = true; break;
10428     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
10429       NumVecs = 2; break;
10430     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
10431       NumVecs = 3; break;
10432     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
10433       NumVecs = 4; break;
10434     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
10435       NumVecs = 2; IsStore = true; break;
10436     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
10437       NumVecs = 3; IsStore = true; break;
10438     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
10439       NumVecs = 4; IsStore = true; break;
10440     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
10441       NumVecs = 2; IsDupOp = true; break;
10442     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
10443       NumVecs = 3; IsDupOp = true; break;
10444     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
10445       NumVecs = 4; IsDupOp = true; break;
10446     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
10447       NumVecs = 2; IsLaneOp = true; break;
10448     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
10449       NumVecs = 3; IsLaneOp = true; break;
10450     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
10451       NumVecs = 4; IsLaneOp = true; break;
10452     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
10453       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10454     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
10455       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10456     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
10457       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10458     }
10459 
10460     EVT VecTy;
10461     if (IsStore)
10462       VecTy = N->getOperand(2).getValueType();
10463     else
10464       VecTy = N->getValueType(0);
10465 
10466     // If the increment is a constant, it must match the memory ref size.
10467     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10468     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10469       uint32_t IncVal = CInc->getZExtValue();
10470       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10471       if (IsLaneOp || IsDupOp)
10472         NumBytes /= VecTy.getVectorNumElements();
10473       if (IncVal != NumBytes)
10474         continue;
10475       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10476     }
10477     SmallVector<SDValue, 8> Ops;
10478     Ops.push_back(N->getOperand(0)); // Incoming chain
10479     // Load lane and store have vector list as input.
10480     if (IsLaneOp || IsStore)
10481       for (unsigned i = 2; i < AddrOpIdx; ++i)
10482         Ops.push_back(N->getOperand(i));
10483     Ops.push_back(Addr); // Base register
10484     Ops.push_back(Inc);
10485 
10486     // Return Types.
10487     EVT Tys[6];
10488     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10489     unsigned n;
10490     for (n = 0; n < NumResultVecs; ++n)
10491       Tys[n] = VecTy;
10492     Tys[n++] = MVT::i64;  // Type of write back register
10493     Tys[n] = MVT::Other;  // Type of the chain
10494     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10495 
10496     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10497     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10498                                            MemInt->getMemoryVT(),
10499                                            MemInt->getMemOperand());
10500 
10501     // Update the uses.
10502     std::vector<SDValue> NewResults;
10503     for (unsigned i = 0; i < NumResultVecs; ++i) {
10504       NewResults.push_back(SDValue(UpdN.getNode(), i));
10505     }
10506     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10507     DCI.CombineTo(N, NewResults);
10508     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10509 
10510     break;
10511   }
10512   return SDValue();
10513 }
10514 
10515 // Checks to see if the value is the prescribed width and returns information
10516 // about its extension mode.
10517 static
10518 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10519   ExtType = ISD::NON_EXTLOAD;
10520   switch(V.getNode()->getOpcode()) {
10521   default:
10522     return false;
10523   case ISD::LOAD: {
10524     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10525     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10526        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10527       ExtType = LoadNode->getExtensionType();
10528       return true;
10529     }
10530     return false;
10531   }
10532   case ISD::AssertSext: {
10533     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10534     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10535        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10536       ExtType = ISD::SEXTLOAD;
10537       return true;
10538     }
10539     return false;
10540   }
10541   case ISD::AssertZext: {
10542     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10543     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10544        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10545       ExtType = ISD::ZEXTLOAD;
10546       return true;
10547     }
10548     return false;
10549   }
10550   case ISD::Constant:
10551   case ISD::TargetConstant: {
10552     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10553            1LL << (width - 1);
10554   }
10555   }
10556 
10557   return true;
10558 }
10559 
10560 // This function does a whole lot of voodoo to determine if the tests are
10561 // equivalent without and with a mask. Essentially what happens is that given a
10562 // DAG resembling:
10563 //
10564 //  +-------------+ +-------------+ +-------------+ +-------------+
10565 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
10566 //  +-------------+ +-------------+ +-------------+ +-------------+
10567 //           |           |           |               |
10568 //           V           V           |    +----------+
10569 //          +-------------+  +----+  |    |
10570 //          |     ADD     |  |0xff|  |    |
10571 //          +-------------+  +----+  |    |
10572 //                  |           |    |    |
10573 //                  V           V    |    |
10574 //                 +-------------+   |    |
10575 //                 |     AND     |   |    |
10576 //                 +-------------+   |    |
10577 //                      |            |    |
10578 //                      +-----+      |    |
10579 //                            |      |    |
10580 //                            V      V    V
10581 //                           +-------------+
10582 //                           |     CMP     |
10583 //                           +-------------+
10584 //
10585 // The AND node may be safely removed for some combinations of inputs. In
10586 // particular we need to take into account the extension type of the Input,
10587 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10588 // width of the input (this can work for any width inputs, the above graph is
10589 // specific to 8 bits.
10590 //
10591 // The specific equations were worked out by generating output tables for each
10592 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10593 // problem was simplified by working with 4 bit inputs, which means we only
10594 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10595 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10596 // patterns present in both extensions (0,7). For every distinct set of
10597 // AddConstant and CompConstants bit patterns we can consider the masked and
10598 // unmasked versions to be equivalent if the result of this function is true for
10599 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10600 //
10601 //   sub      w8, w0, w1
10602 //   and      w10, w8, #0x0f
10603 //   cmp      w8, w2
10604 //   cset     w9, AArch64CC
10605 //   cmp      w10, w2
10606 //   cset     w11, AArch64CC
10607 //   cmp      w9, w11
10608 //   cset     w0, eq
10609 //   ret
10610 //
10611 // Since the above function shows when the outputs are equivalent it defines
10612 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10613 // would be expensive to run during compiles. The equations below were written
10614 // in a test harness that confirmed they gave equivalent outputs to the above
10615 // for all inputs function, so they can be used determine if the removal is
10616 // legal instead.
10617 //
10618 // isEquivalentMaskless() is the code for testing if the AND can be removed
10619 // factored out of the DAG recognition as the DAG can take several forms.
10620 
10621 static bool isEquivalentMaskless(unsigned CC, unsigned width,
10622                                  ISD::LoadExtType ExtType, int AddConstant,
10623                                  int CompConstant) {
10624   // By being careful about our equations and only writing the in term
10625   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10626   // make them generally applicable to all bit widths.
10627   int MaxUInt = (1 << width);
10628 
10629   // For the purposes of these comparisons sign extending the type is
10630   // equivalent to zero extending the add and displacing it by half the integer
10631   // width. Provided we are careful and make sure our equations are valid over
10632   // the whole range we can just adjust the input and avoid writing equations
10633   // for sign extended inputs.
10634   if (ExtType == ISD::SEXTLOAD)
10635     AddConstant -= (1 << (width-1));
10636 
10637   switch(CC) {
10638   case AArch64CC::LE:
10639   case AArch64CC::GT:
10640     if ((AddConstant == 0) ||
10641         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10642         (AddConstant >= 0 && CompConstant < 0) ||
10643         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10644       return true;
10645     break;
10646   case AArch64CC::LT:
10647   case AArch64CC::GE:
10648     if ((AddConstant == 0) ||
10649         (AddConstant >= 0 && CompConstant <= 0) ||
10650         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10651       return true;
10652     break;
10653   case AArch64CC::HI:
10654   case AArch64CC::LS:
10655     if ((AddConstant >= 0 && CompConstant < 0) ||
10656        (AddConstant <= 0 && CompConstant >= -1 &&
10657         CompConstant < AddConstant + MaxUInt))
10658       return true;
10659    break;
10660   case AArch64CC::PL:
10661   case AArch64CC::MI:
10662     if ((AddConstant == 0) ||
10663         (AddConstant > 0 && CompConstant <= 0) ||
10664         (AddConstant < 0 && CompConstant <= AddConstant))
10665       return true;
10666     break;
10667   case AArch64CC::LO:
10668   case AArch64CC::HS:
10669     if ((AddConstant >= 0 && CompConstant <= 0) ||
10670         (AddConstant <= 0 && CompConstant >= 0 &&
10671          CompConstant <= AddConstant + MaxUInt))
10672       return true;
10673     break;
10674   case AArch64CC::EQ:
10675   case AArch64CC::NE:
10676     if ((AddConstant > 0 && CompConstant < 0) ||
10677         (AddConstant < 0 && CompConstant >= 0 &&
10678          CompConstant < AddConstant + MaxUInt) ||
10679         (AddConstant >= 0 && CompConstant >= 0 &&
10680          CompConstant >= AddConstant) ||
10681         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
10682       return true;
10683     break;
10684   case AArch64CC::VS:
10685   case AArch64CC::VC:
10686   case AArch64CC::AL:
10687   case AArch64CC::NV:
10688     return true;
10689   case AArch64CC::Invalid:
10690     break;
10691   }
10692 
10693   return false;
10694 }
10695 
10696 static
10697 SDValue performCONDCombine(SDNode *N,
10698                            TargetLowering::DAGCombinerInfo &DCI,
10699                            SelectionDAG &DAG, unsigned CCIndex,
10700                            unsigned CmpIndex) {
10701   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10702   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10703   unsigned CondOpcode = SubsNode->getOpcode();
10704 
10705   if (CondOpcode != AArch64ISD::SUBS)
10706     return SDValue();
10707 
10708   // There is a SUBS feeding this condition. Is it fed by a mask we can
10709   // use?
10710 
10711   SDNode *AndNode = SubsNode->getOperand(0).getNode();
10712   unsigned MaskBits = 0;
10713 
10714   if (AndNode->getOpcode() != ISD::AND)
10715     return SDValue();
10716 
10717   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10718     uint32_t CNV = CN->getZExtValue();
10719     if (CNV == 255)
10720       MaskBits = 8;
10721     else if (CNV == 65535)
10722       MaskBits = 16;
10723   }
10724 
10725   if (!MaskBits)
10726     return SDValue();
10727 
10728   SDValue AddValue = AndNode->getOperand(0);
10729 
10730   if (AddValue.getOpcode() != ISD::ADD)
10731     return SDValue();
10732 
10733   // The basic dag structure is correct, grab the inputs and validate them.
10734 
10735   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10736   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10737   SDValue SubsInputValue = SubsNode->getOperand(1);
10738 
10739   // The mask is present and the provenance of all the values is a smaller type,
10740   // lets see if the mask is superfluous.
10741 
10742   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10743       !isa<ConstantSDNode>(SubsInputValue.getNode()))
10744     return SDValue();
10745 
10746   ISD::LoadExtType ExtType;
10747 
10748   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10749       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10750       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10751     return SDValue();
10752 
10753   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10754                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10755                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10756     return SDValue();
10757 
10758   // The AND is not necessary, remove it.
10759 
10760   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10761                                SubsNode->getValueType(1));
10762   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10763 
10764   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10765   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10766 
10767   return SDValue(N, 0);
10768 }
10769 
10770 // Optimize compare with zero and branch.
10771 static SDValue performBRCONDCombine(SDNode *N,
10772                                     TargetLowering::DAGCombinerInfo &DCI,
10773                                     SelectionDAG &DAG) {
10774   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10775     N = NV.getNode();
10776   SDValue Chain = N->getOperand(0);
10777   SDValue Dest = N->getOperand(1);
10778   SDValue CCVal = N->getOperand(2);
10779   SDValue Cmp = N->getOperand(3);
10780 
10781   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10782   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10783   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10784     return SDValue();
10785 
10786   unsigned CmpOpc = Cmp.getOpcode();
10787   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10788     return SDValue();
10789 
10790   // Only attempt folding if there is only one use of the flag and no use of the
10791   // value.
10792   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10793     return SDValue();
10794 
10795   SDValue LHS = Cmp.getOperand(0);
10796   SDValue RHS = Cmp.getOperand(1);
10797 
10798   assert(LHS.getValueType() == RHS.getValueType() &&
10799          "Expected the value type to be the same for both operands!");
10800   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10801     return SDValue();
10802 
10803   if (isNullConstant(LHS))
10804     std::swap(LHS, RHS);
10805 
10806   if (!isNullConstant(RHS))
10807     return SDValue();
10808 
10809   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10810       LHS.getOpcode() == ISD::SRL)
10811     return SDValue();
10812 
10813   // Fold the compare into the branch instruction.
10814   SDValue BR;
10815   if (CC == AArch64CC::EQ)
10816     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10817   else
10818     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10819 
10820   // Do not add new nodes to DAG combiner worklist.
10821   DCI.CombineTo(N, BR, false);
10822 
10823   return SDValue();
10824 }
10825 
10826 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
10827 // as well as whether the test should be inverted.  This code is required to
10828 // catch these cases (as opposed to standard dag combines) because
10829 // AArch64ISD::TBZ is matched during legalization.
10830 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10831                                  SelectionDAG &DAG) {
10832 
10833   if (!Op->hasOneUse())
10834     return Op;
10835 
10836   // We don't handle undef/constant-fold cases below, as they should have
10837   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10838   // etc.)
10839 
10840   // (tbz (trunc x), b) -> (tbz x, b)
10841   // This case is just here to enable more of the below cases to be caught.
10842   if (Op->getOpcode() == ISD::TRUNCATE &&
10843       Bit < Op->getValueType(0).getSizeInBits()) {
10844     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10845   }
10846 
10847   if (Op->getNumOperands() != 2)
10848     return Op;
10849 
10850   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10851   if (!C)
10852     return Op;
10853 
10854   switch (Op->getOpcode()) {
10855   default:
10856     return Op;
10857 
10858   // (tbz (and x, m), b) -> (tbz x, b)
10859   case ISD::AND:
10860     if ((C->getZExtValue() >> Bit) & 1)
10861       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10862     return Op;
10863 
10864   // (tbz (shl x, c), b) -> (tbz x, b-c)
10865   case ISD::SHL:
10866     if (C->getZExtValue() <= Bit &&
10867         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10868       Bit = Bit - C->getZExtValue();
10869       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10870     }
10871     return Op;
10872 
10873   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10874   case ISD::SRA:
10875     Bit = Bit + C->getZExtValue();
10876     if (Bit >= Op->getValueType(0).getSizeInBits())
10877       Bit = Op->getValueType(0).getSizeInBits() - 1;
10878     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10879 
10880   // (tbz (srl x, c), b) -> (tbz x, b+c)
10881   case ISD::SRL:
10882     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10883       Bit = Bit + C->getZExtValue();
10884       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10885     }
10886     return Op;
10887 
10888   // (tbz (xor x, -1), b) -> (tbnz x, b)
10889   case ISD::XOR:
10890     if ((C->getZExtValue() >> Bit) & 1)
10891       Invert = !Invert;
10892     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10893   }
10894 }
10895 
10896 // Optimize test single bit zero/non-zero and branch.
10897 static SDValue performTBZCombine(SDNode *N,
10898                                  TargetLowering::DAGCombinerInfo &DCI,
10899                                  SelectionDAG &DAG) {
10900   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10901   bool Invert = false;
10902   SDValue TestSrc = N->getOperand(1);
10903   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10904 
10905   if (TestSrc == NewTestSrc)
10906     return SDValue();
10907 
10908   unsigned NewOpc = N->getOpcode();
10909   if (Invert) {
10910     if (NewOpc == AArch64ISD::TBZ)
10911       NewOpc = AArch64ISD::TBNZ;
10912     else {
10913       assert(NewOpc == AArch64ISD::TBNZ);
10914       NewOpc = AArch64ISD::TBZ;
10915     }
10916   }
10917 
10918   SDLoc DL(N);
10919   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10920                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10921 }
10922 
10923 // vselect (v1i1 setcc) ->
10924 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10925 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10926 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10927 // such VSELECT.
10928 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10929   SDValue N0 = N->getOperand(0);
10930   EVT CCVT = N0.getValueType();
10931 
10932   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10933       CCVT.getVectorElementType() != MVT::i1)
10934     return SDValue();
10935 
10936   EVT ResVT = N->getValueType(0);
10937   EVT CmpVT = N0.getOperand(0).getValueType();
10938   // Only combine when the result type is of the same size as the compared
10939   // operands.
10940   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10941     return SDValue();
10942 
10943   SDValue IfTrue = N->getOperand(1);
10944   SDValue IfFalse = N->getOperand(2);
10945   SDValue SetCC =
10946       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10947                    N0.getOperand(0), N0.getOperand(1),
10948                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10949   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10950                      IfTrue, IfFalse);
10951 }
10952 
10953 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10954 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10955 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10956 /// with a vector one followed by a DUP shuffle on the result.
10957 static SDValue performSelectCombine(SDNode *N,
10958                                     TargetLowering::DAGCombinerInfo &DCI) {
10959   SelectionDAG &DAG = DCI.DAG;
10960   SDValue N0 = N->getOperand(0);
10961   EVT ResVT = N->getValueType(0);
10962 
10963   if (N0.getOpcode() != ISD::SETCC)
10964     return SDValue();
10965 
10966   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10967   // scalar SetCCResultType. We also don't expect vectors, because we assume
10968   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10969   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10970          "Scalar-SETCC feeding SELECT has unexpected result type!");
10971 
10972   // If NumMaskElts == 0, the comparison is larger than select result. The
10973   // largest real NEON comparison is 64-bits per lane, which means the result is
10974   // at most 32-bits and an illegal vector. Just bail out for now.
10975   EVT SrcVT = N0.getOperand(0).getValueType();
10976 
10977   // Don't try to do this optimization when the setcc itself has i1 operands.
10978   // There are no legal vectors of i1, so this would be pointless.
10979   if (SrcVT == MVT::i1)
10980     return SDValue();
10981 
10982   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10983   if (!ResVT.isVector() || NumMaskElts == 0)
10984     return SDValue();
10985 
10986   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10987   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10988 
10989   // Also bail out if the vector CCVT isn't the same size as ResVT.
10990   // This can happen if the SETCC operand size doesn't divide the ResVT size
10991   // (e.g., f64 vs v3f32).
10992   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10993     return SDValue();
10994 
10995   // Make sure we didn't create illegal types, if we're not supposed to.
10996   assert(DCI.isBeforeLegalize() ||
10997          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10998 
10999   // First perform a vector comparison, where lane 0 is the one we're interested
11000   // in.
11001   SDLoc DL(N0);
11002   SDValue LHS =
11003       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11004   SDValue RHS =
11005       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11006   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11007 
11008   // Now duplicate the comparison mask we want across all other lanes.
11009   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11010   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11011   Mask = DAG.getNode(ISD::BITCAST, DL,
11012                      ResVT.changeVectorElementTypeToInteger(), Mask);
11013 
11014   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11015 }
11016 
11017 /// Get rid of unnecessary NVCASTs (that don't change the type).
11018 static SDValue performNVCASTCombine(SDNode *N) {
11019   if (N->getValueType(0) == N->getOperand(0).getValueType())
11020     return N->getOperand(0);
11021 
11022   return SDValue();
11023 }
11024 
11025 // If all users of the globaladdr are of the form (globaladdr + constant), find
11026 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11027 // globaladdr as (globaladdr + constant) - constant.
11028 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11029                                            const AArch64Subtarget *Subtarget,
11030                                            const TargetMachine &TM) {
11031   auto *GN = cast<GlobalAddressSDNode>(N);
11032   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11033       AArch64II::MO_NO_FLAG)
11034     return SDValue();
11035 
11036   uint64_t MinOffset = -1ull;
11037   for (SDNode *N : GN->uses()) {
11038     if (N->getOpcode() != ISD::ADD)
11039       return SDValue();
11040     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11041     if (!C)
11042       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11043     if (!C)
11044       return SDValue();
11045     MinOffset = std::min(MinOffset, C->getZExtValue());
11046   }
11047   uint64_t Offset = MinOffset + GN->getOffset();
11048 
11049   // Require that the new offset is larger than the existing one. Otherwise, we
11050   // can end up oscillating between two possible DAGs, for example,
11051   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11052   if (Offset <= uint64_t(GN->getOffset()))
11053     return SDValue();
11054 
11055   // Check whether folding this offset is legal. It must not go out of bounds of
11056   // the referenced object to avoid violating the code model, and must be
11057   // smaller than 2^21 because this is the largest offset expressible in all
11058   // object formats.
11059   //
11060   // This check also prevents us from folding negative offsets, which will end
11061   // up being treated in the same way as large positive ones. They could also
11062   // cause code model violations, and aren't really common enough to matter.
11063   if (Offset >= (1 << 21))
11064     return SDValue();
11065 
11066   const GlobalValue *GV = GN->getGlobal();
11067   Type *T = GV->getValueType();
11068   if (!T->isSized() ||
11069       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11070     return SDValue();
11071 
11072   SDLoc DL(GN);
11073   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11074   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11075                      DAG.getConstant(MinOffset, DL, MVT::i64));
11076 }
11077 
11078 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11079                                                  DAGCombinerInfo &DCI) const {
11080   SelectionDAG &DAG = DCI.DAG;
11081   switch (N->getOpcode()) {
11082   default:
11083     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11084     break;
11085   case ISD::ADD:
11086   case ISD::SUB:
11087     return performAddSubLongCombine(N, DCI, DAG);
11088   case ISD::XOR:
11089     return performXorCombine(N, DAG, DCI, Subtarget);
11090   case ISD::MUL:
11091     return performMulCombine(N, DAG, DCI, Subtarget);
11092   case ISD::SINT_TO_FP:
11093   case ISD::UINT_TO_FP:
11094     return performIntToFpCombine(N, DAG, Subtarget);
11095   case ISD::FP_TO_SINT:
11096   case ISD::FP_TO_UINT:
11097     return performFpToIntCombine(N, DAG, DCI, Subtarget);
11098   case ISD::FDIV:
11099     return performFDivCombine(N, DAG, DCI, Subtarget);
11100   case ISD::OR:
11101     return performORCombine(N, DCI, Subtarget);
11102   case ISD::SRL:
11103     return performSRLCombine(N, DCI);
11104   case ISD::INTRINSIC_WO_CHAIN:
11105     return performIntrinsicCombine(N, DCI, Subtarget);
11106   case ISD::ANY_EXTEND:
11107   case ISD::ZERO_EXTEND:
11108   case ISD::SIGN_EXTEND:
11109     return performExtendCombine(N, DCI, DAG);
11110   case ISD::BITCAST:
11111     return performBitcastCombine(N, DCI, DAG);
11112   case ISD::CONCAT_VECTORS:
11113     return performConcatVectorsCombine(N, DCI, DAG);
11114   case ISD::SELECT:
11115     return performSelectCombine(N, DCI);
11116   case ISD::VSELECT:
11117     return performVSelectCombine(N, DCI.DAG);
11118   case ISD::LOAD:
11119     if (performTBISimplification(N->getOperand(1), DCI, DAG))
11120       return SDValue(N, 0);
11121     break;
11122   case ISD::STORE:
11123     return performSTORECombine(N, DCI, DAG, Subtarget);
11124   case AArch64ISD::BRCOND:
11125     return performBRCONDCombine(N, DCI, DAG);
11126   case AArch64ISD::TBNZ:
11127   case AArch64ISD::TBZ:
11128     return performTBZCombine(N, DCI, DAG);
11129   case AArch64ISD::CSEL:
11130     return performCONDCombine(N, DCI, DAG, 2, 3);
11131   case AArch64ISD::DUP:
11132     return performPostLD1Combine(N, DCI, false);
11133   case AArch64ISD::NVCAST:
11134     return performNVCASTCombine(N);
11135   case ISD::INSERT_VECTOR_ELT:
11136     return performPostLD1Combine(N, DCI, true);
11137   case ISD::INTRINSIC_VOID:
11138   case ISD::INTRINSIC_W_CHAIN:
11139     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11140     case Intrinsic::aarch64_neon_ld2:
11141     case Intrinsic::aarch64_neon_ld3:
11142     case Intrinsic::aarch64_neon_ld4:
11143     case Intrinsic::aarch64_neon_ld1x2:
11144     case Intrinsic::aarch64_neon_ld1x3:
11145     case Intrinsic::aarch64_neon_ld1x4:
11146     case Intrinsic::aarch64_neon_ld2lane:
11147     case Intrinsic::aarch64_neon_ld3lane:
11148     case Intrinsic::aarch64_neon_ld4lane:
11149     case Intrinsic::aarch64_neon_ld2r:
11150     case Intrinsic::aarch64_neon_ld3r:
11151     case Intrinsic::aarch64_neon_ld4r:
11152     case Intrinsic::aarch64_neon_st2:
11153     case Intrinsic::aarch64_neon_st3:
11154     case Intrinsic::aarch64_neon_st4:
11155     case Intrinsic::aarch64_neon_st1x2:
11156     case Intrinsic::aarch64_neon_st1x3:
11157     case Intrinsic::aarch64_neon_st1x4:
11158     case Intrinsic::aarch64_neon_st2lane:
11159     case Intrinsic::aarch64_neon_st3lane:
11160     case Intrinsic::aarch64_neon_st4lane:
11161       return performNEONPostLDSTCombine(N, DCI, DAG);
11162     default:
11163       break;
11164     }
11165     break;
11166   case ISD::GlobalAddress:
11167     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11168   }
11169   return SDValue();
11170 }
11171 
11172 // Check if the return value is used as only a return value, as otherwise
11173 // we can't perform a tail-call. In particular, we need to check for
11174 // target ISD nodes that are returns and any other "odd" constructs
11175 // that the generic analysis code won't necessarily catch.
11176 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11177                                                SDValue &Chain) const {
11178   if (N->getNumValues() != 1)
11179     return false;
11180   if (!N->hasNUsesOfValue(1, 0))
11181     return false;
11182 
11183   SDValue TCChain = Chain;
11184   SDNode *Copy = *N->use_begin();
11185   if (Copy->getOpcode() == ISD::CopyToReg) {
11186     // If the copy has a glue operand, we conservatively assume it isn't safe to
11187     // perform a tail call.
11188     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11189         MVT::Glue)
11190       return false;
11191     TCChain = Copy->getOperand(0);
11192   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11193     return false;
11194 
11195   bool HasRet = false;
11196   for (SDNode *Node : Copy->uses()) {
11197     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11198       return false;
11199     HasRet = true;
11200   }
11201 
11202   if (!HasRet)
11203     return false;
11204 
11205   Chain = TCChain;
11206   return true;
11207 }
11208 
11209 // Return whether the an instruction can potentially be optimized to a tail
11210 // call. This will cause the optimizers to attempt to move, or duplicate,
11211 // return instructions to help enable tail call optimizations for this
11212 // instruction.
11213 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11214   return CI->isTailCall();
11215 }
11216 
11217 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11218                                                    SDValue &Offset,
11219                                                    ISD::MemIndexedMode &AM,
11220                                                    bool &IsInc,
11221                                                    SelectionDAG &DAG) const {
11222   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11223     return false;
11224 
11225   Base = Op->getOperand(0);
11226   // All of the indexed addressing mode instructions take a signed
11227   // 9 bit immediate offset.
11228   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11229     int64_t RHSC = RHS->getSExtValue();
11230     if (Op->getOpcode() == ISD::SUB)
11231       RHSC = -(uint64_t)RHSC;
11232     if (!isInt<9>(RHSC))
11233       return false;
11234     IsInc = (Op->getOpcode() == ISD::ADD);
11235     Offset = Op->getOperand(1);
11236     return true;
11237   }
11238   return false;
11239 }
11240 
11241 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11242                                                       SDValue &Offset,
11243                                                       ISD::MemIndexedMode &AM,
11244                                                       SelectionDAG &DAG) const {
11245   EVT VT;
11246   SDValue Ptr;
11247   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11248     VT = LD->getMemoryVT();
11249     Ptr = LD->getBasePtr();
11250   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11251     VT = ST->getMemoryVT();
11252     Ptr = ST->getBasePtr();
11253   } else
11254     return false;
11255 
11256   bool IsInc;
11257   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11258     return false;
11259   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11260   return true;
11261 }
11262 
11263 bool AArch64TargetLowering::getPostIndexedAddressParts(
11264     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11265     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11266   EVT VT;
11267   SDValue Ptr;
11268   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11269     VT = LD->getMemoryVT();
11270     Ptr = LD->getBasePtr();
11271   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11272     VT = ST->getMemoryVT();
11273     Ptr = ST->getBasePtr();
11274   } else
11275     return false;
11276 
11277   bool IsInc;
11278   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11279     return false;
11280   // Post-indexing updates the base, so it's not a valid transform
11281   // if that's not the same as the load's pointer.
11282   if (Ptr != Base)
11283     return false;
11284   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11285   return true;
11286 }
11287 
11288 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11289                                   SelectionDAG &DAG) {
11290   SDLoc DL(N);
11291   SDValue Op = N->getOperand(0);
11292 
11293   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11294     return;
11295 
11296   Op = SDValue(
11297       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11298                          DAG.getUNDEF(MVT::i32), Op,
11299                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11300       0);
11301   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11302   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11303 }
11304 
11305 static void ReplaceReductionResults(SDNode *N,
11306                                     SmallVectorImpl<SDValue> &Results,
11307                                     SelectionDAG &DAG, unsigned InterOp,
11308                                     unsigned AcrossOp) {
11309   EVT LoVT, HiVT;
11310   SDValue Lo, Hi;
11311   SDLoc dl(N);
11312   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11313   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11314   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11315   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11316   Results.push_back(SplitVal);
11317 }
11318 
11319 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11320   SDLoc DL(N);
11321   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11322   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11323                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11324                                        DAG.getConstant(64, DL, MVT::i64)));
11325   return std::make_pair(Lo, Hi);
11326 }
11327 
11328 // Create an even/odd pair of X registers holding integer value V.
11329 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11330   SDLoc dl(V.getNode());
11331   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11332   SDValue VHi = DAG.getAnyExtOrTrunc(
11333       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11334       dl, MVT::i64);
11335   if (DAG.getDataLayout().isBigEndian())
11336     std::swap (VLo, VHi);
11337   SDValue RegClass =
11338       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11339   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11340   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11341   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11342   return SDValue(
11343       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11344 }
11345 
11346 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11347                                        SmallVectorImpl<SDValue> &Results,
11348                                        SelectionDAG &DAG,
11349                                        const AArch64Subtarget *Subtarget) {
11350   assert(N->getValueType(0) == MVT::i128 &&
11351          "AtomicCmpSwap on types less than 128 should be legal");
11352 
11353   if (Subtarget->hasLSE()) {
11354     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11355     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11356     SDValue Ops[] = {
11357         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11358         createGPRPairNode(DAG, N->getOperand(3)), // Store value
11359         N->getOperand(1), // Ptr
11360         N->getOperand(0), // Chain in
11361     };
11362 
11363     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11364 
11365     unsigned Opcode;
11366     switch (MemOp->getOrdering()) {
11367     case AtomicOrdering::Monotonic:
11368       Opcode = AArch64::CASPX;
11369       break;
11370     case AtomicOrdering::Acquire:
11371       Opcode = AArch64::CASPAX;
11372       break;
11373     case AtomicOrdering::Release:
11374       Opcode = AArch64::CASPLX;
11375       break;
11376     case AtomicOrdering::AcquireRelease:
11377     case AtomicOrdering::SequentiallyConsistent:
11378       Opcode = AArch64::CASPALX;
11379       break;
11380     default:
11381       llvm_unreachable("Unexpected ordering!");
11382     }
11383 
11384     MachineSDNode *CmpSwap = DAG.getMachineNode(
11385         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11386     DAG.setNodeMemRefs(CmpSwap, {MemOp});
11387 
11388     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11389     if (DAG.getDataLayout().isBigEndian())
11390       std::swap(SubReg1, SubReg2);
11391     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11392                                                  SDValue(CmpSwap, 0)));
11393     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11394                                                  SDValue(CmpSwap, 0)));
11395     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11396     return;
11397   }
11398 
11399   auto Desired = splitInt128(N->getOperand(2), DAG);
11400   auto New = splitInt128(N->getOperand(3), DAG);
11401   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11402                    New.first,        New.second,    N->getOperand(0)};
11403   SDNode *CmpSwap = DAG.getMachineNode(
11404       AArch64::CMP_SWAP_128, SDLoc(N),
11405       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11406 
11407   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11408   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11409 
11410   Results.push_back(SDValue(CmpSwap, 0));
11411   Results.push_back(SDValue(CmpSwap, 1));
11412   Results.push_back(SDValue(CmpSwap, 3));
11413 }
11414 
11415 void AArch64TargetLowering::ReplaceNodeResults(
11416     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11417   switch (N->getOpcode()) {
11418   default:
11419     llvm_unreachable("Don't know how to custom expand this");
11420   case ISD::BITCAST:
11421     ReplaceBITCASTResults(N, Results, DAG);
11422     return;
11423   case ISD::VECREDUCE_ADD:
11424   case ISD::VECREDUCE_SMAX:
11425   case ISD::VECREDUCE_SMIN:
11426   case ISD::VECREDUCE_UMAX:
11427   case ISD::VECREDUCE_UMIN:
11428     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11429     return;
11430 
11431   case AArch64ISD::SADDV:
11432     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11433     return;
11434   case AArch64ISD::UADDV:
11435     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11436     return;
11437   case AArch64ISD::SMINV:
11438     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11439     return;
11440   case AArch64ISD::UMINV:
11441     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11442     return;
11443   case AArch64ISD::SMAXV:
11444     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11445     return;
11446   case AArch64ISD::UMAXV:
11447     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11448     return;
11449   case ISD::FP_TO_UINT:
11450   case ISD::FP_TO_SINT:
11451     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11452     // Let normal code take care of it by not adding anything to Results.
11453     return;
11454   case ISD::ATOMIC_CMP_SWAP:
11455     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11456     return;
11457   }
11458 }
11459 
11460 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11461   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11462     return TargetLowering::useLoadStackGuardNode();
11463   return true;
11464 }
11465 
11466 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11467   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11468   // reciprocal if there are three or more FDIVs.
11469   return 3;
11470 }
11471 
11472 TargetLoweringBase::LegalizeTypeAction
11473 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
11474   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
11475   // v4i16, v2i32 instead of to promote.
11476   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11477       VT == MVT::v1f32)
11478     return TypeWidenVector;
11479 
11480   return TargetLoweringBase::getPreferredVectorAction(VT);
11481 }
11482 
11483 // Loads and stores less than 128-bits are already atomic; ones above that
11484 // are doomed anyway, so defer to the default libcall and blame the OS when
11485 // things go wrong.
11486 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11487   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11488   return Size == 128;
11489 }
11490 
11491 // Loads and stores less than 128-bits are already atomic; ones above that
11492 // are doomed anyway, so defer to the default libcall and blame the OS when
11493 // things go wrong.
11494 TargetLowering::AtomicExpansionKind
11495 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11496   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11497   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11498 }
11499 
11500 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11501 TargetLowering::AtomicExpansionKind
11502 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11503   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11504   if (Size > 128) return AtomicExpansionKind::None;
11505   // Nand not supported in LSE.
11506   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11507   // Leave 128 bits to LLSC.
11508   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11509 }
11510 
11511 TargetLowering::AtomicExpansionKind
11512 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11513     AtomicCmpXchgInst *AI) const {
11514   // If subtarget has LSE, leave cmpxchg intact for codegen.
11515   if (Subtarget->hasLSE())
11516     return AtomicExpansionKind::None;
11517   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11518   // implement cmpxchg without spilling. If the address being exchanged is also
11519   // on the stack and close enough to the spill slot, this can lead to a
11520   // situation where the monitor always gets cleared and the atomic operation
11521   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11522   if (getTargetMachine().getOptLevel() == 0)
11523     return AtomicExpansionKind::None;
11524   return AtomicExpansionKind::LLSC;
11525 }
11526 
11527 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11528                                              AtomicOrdering Ord) const {
11529   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11530   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11531   bool IsAcquire = isAcquireOrStronger(Ord);
11532 
11533   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11534   // intrinsic must return {i64, i64} and we have to recombine them into a
11535   // single i128 here.
11536   if (ValTy->getPrimitiveSizeInBits() == 128) {
11537     Intrinsic::ID Int =
11538         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11539     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11540 
11541     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11542     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11543 
11544     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11545     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11546     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11547     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11548     return Builder.CreateOr(
11549         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11550   }
11551 
11552   Type *Tys[] = { Addr->getType() };
11553   Intrinsic::ID Int =
11554       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11555   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11556 
11557   return Builder.CreateTruncOrBitCast(
11558       Builder.CreateCall(Ldxr, Addr),
11559       cast<PointerType>(Addr->getType())->getElementType());
11560 }
11561 
11562 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11563     IRBuilder<> &Builder) const {
11564   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11565   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11566 }
11567 
11568 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11569                                                    Value *Val, Value *Addr,
11570                                                    AtomicOrdering Ord) const {
11571   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11572   bool IsRelease = isReleaseOrStronger(Ord);
11573 
11574   // Since the intrinsics must have legal type, the i128 intrinsics take two
11575   // parameters: "i64, i64". We must marshal Val into the appropriate form
11576   // before the call.
11577   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11578     Intrinsic::ID Int =
11579         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11580     Function *Stxr = Intrinsic::getDeclaration(M, Int);
11581     Type *Int64Ty = Type::getInt64Ty(M->getContext());
11582 
11583     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11584     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11585     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11586     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
11587   }
11588 
11589   Intrinsic::ID Int =
11590       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11591   Type *Tys[] = { Addr->getType() };
11592   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11593 
11594   return Builder.CreateCall(Stxr,
11595                             {Builder.CreateZExtOrBitCast(
11596                                  Val, Stxr->getFunctionType()->getParamType(0)),
11597                              Addr});
11598 }
11599 
11600 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11601     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11602   return Ty->isArrayTy();
11603 }
11604 
11605 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11606                                                             EVT) const {
11607   return false;
11608 }
11609 
11610 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
11611   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11612   Function *ThreadPointerFunc =
11613       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
11614   return IRB.CreatePointerCast(
11615       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
11616       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11617 }
11618 
11619 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11620   // Android provides a fixed TLS slot for the stack cookie. See the definition
11621   // of TLS_SLOT_STACK_GUARD in
11622   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11623   if (Subtarget->isTargetAndroid())
11624     return UseTlsOffset(IRB, 0x28);
11625 
11626   // Fuchsia is similar.
11627   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
11628   if (Subtarget->isTargetFuchsia())
11629     return UseTlsOffset(IRB, -0x10);
11630 
11631   return TargetLowering::getIRStackGuard(IRB);
11632 }
11633 
11634 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11635   // MSVC CRT provides functionalities for stack protection.
11636   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11637     // MSVC CRT has a global variable holding security cookie.
11638     M.getOrInsertGlobal("__security_cookie",
11639                         Type::getInt8PtrTy(M.getContext()));
11640 
11641     // MSVC CRT has a function to validate security cookie.
11642     auto *SecurityCheckCookie = cast<Function>(
11643         M.getOrInsertFunction("__security_check_cookie",
11644                               Type::getVoidTy(M.getContext()),
11645                               Type::getInt8PtrTy(M.getContext())));
11646     SecurityCheckCookie->setCallingConv(CallingConv::Win64);
11647     SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
11648     return;
11649   }
11650   TargetLowering::insertSSPDeclarations(M);
11651 }
11652 
11653 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11654   // MSVC CRT has a global variable holding security cookie.
11655   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11656     return M.getGlobalVariable("__security_cookie");
11657   return TargetLowering::getSDagStackGuard(M);
11658 }
11659 
11660 Value *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
11661   // MSVC CRT has a function to validate security cookie.
11662   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11663     return M.getFunction("__security_check_cookie");
11664   return TargetLowering::getSSPStackGuardCheck(M);
11665 }
11666 
11667 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
11668   // Android provides a fixed TLS slot for the SafeStack pointer. See the
11669   // definition of TLS_SLOT_SAFESTACK in
11670   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11671   if (Subtarget->isTargetAndroid())
11672     return UseTlsOffset(IRB, 0x48);
11673 
11674   // Fuchsia is similar.
11675   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
11676   if (Subtarget->isTargetFuchsia())
11677     return UseTlsOffset(IRB, -0x8);
11678 
11679   return TargetLowering::getSafeStackPointerLocation(IRB);
11680 }
11681 
11682 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11683     const Instruction &AndI) const {
11684   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11685   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
11686   // may be beneficial to sink in other cases, but we would have to check that
11687   // the cmp would not get folded into the br to form a cbz for these to be
11688   // beneficial.
11689   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11690   if (!Mask)
11691     return false;
11692   return Mask->getValue().isPowerOf2();
11693 }
11694 
11695 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11696   // Update IsSplitCSR in AArch64unctionInfo.
11697   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11698   AFI->setIsSplitCSR(true);
11699 }
11700 
11701 void AArch64TargetLowering::insertCopiesSplitCSR(
11702     MachineBasicBlock *Entry,
11703     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11704   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11705   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11706   if (!IStart)
11707     return;
11708 
11709   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11710   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
11711   MachineBasicBlock::iterator MBBI = Entry->begin();
11712   for (const MCPhysReg *I = IStart; *I; ++I) {
11713     const TargetRegisterClass *RC = nullptr;
11714     if (AArch64::GPR64RegClass.contains(*I))
11715       RC = &AArch64::GPR64RegClass;
11716     else if (AArch64::FPR64RegClass.contains(*I))
11717       RC = &AArch64::FPR64RegClass;
11718     else
11719       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11720 
11721     unsigned NewVR = MRI->createVirtualRegister(RC);
11722     // Create copy from CSR to a virtual register.
11723     // FIXME: this currently does not emit CFI pseudo-instructions, it works
11724     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11725     // nounwind. If we want to generalize this later, we may need to emit
11726     // CFI pseudo-instructions.
11727     assert(Entry->getParent()->getFunction().hasFnAttribute(
11728                Attribute::NoUnwind) &&
11729            "Function should be nounwind in insertCopiesSplitCSR!");
11730     Entry->addLiveIn(*I);
11731     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
11732         .addReg(*I);
11733 
11734     // Insert the copy-back instructions right before the terminator.
11735     for (auto *Exit : Exits)
11736       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11737               TII->get(TargetOpcode::COPY), *I)
11738           .addReg(NewVR);
11739   }
11740 }
11741 
11742 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
11743   // Integer division on AArch64 is expensive. However, when aggressively
11744   // optimizing for code size, we prefer to use a div instruction, as it is
11745   // usually smaller than the alternative sequence.
11746   // The exception to this is vector division. Since AArch64 doesn't have vector
11747   // integer division, leaving the division as-is is a loss even in terms of
11748   // size, because it will have to be scalarized, while the alternative code
11749   // sequence can be performed in vector form.
11750   bool OptSize =
11751       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
11752   return OptSize && !VT.isVector();
11753 }
11754 
11755 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11756   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11757 }
11758 
11759 unsigned
11760 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
11761   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
11762     return getPointerTy(DL).getSizeInBits();
11763 
11764   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11765 }
11766 
11767 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11768   MF.getFrameInfo().computeMaxCallFrameSize(MF);
11769   TargetLoweringBase::finalizeLowering(MF);
11770 }
11771 
11772 // Unlike X86, we let frame lowering assign offsets to all catch objects.
11773 bool AArch64TargetLowering::needsFixedCatchObjects() const {
11774   return false;
11775 }
11776