1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64ExpandImm.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/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/IntrinsicsAArch64.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/OperandTraits.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/MC/MCRegisterInfo.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CodeGen.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Target/TargetMachine.h"
80 #include "llvm/Target/TargetOptions.h"
81 #include <algorithm>
82 #include <bitset>
83 #include <cassert>
84 #include <cctype>
85 #include <cstdint>
86 #include <cstdlib>
87 #include <iterator>
88 #include <limits>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
92 
93 using namespace llvm;
94 using namespace llvm::PatternMatch;
95 
96 #define DEBUG_TYPE "aarch64-lower"
97 
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 
102 static cl::opt<bool>
103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
104                            cl::desc("Allow AArch64 SLI/SRI formation"),
105                            cl::init(false));
106 
107 // FIXME: The necessary dtprel relocations don't seem to be supported
108 // well in the GNU bfd and gold linkers at the moment. Therefore, by
109 // default, for now, fall back to GeneralDynamic code generation.
110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
111     "aarch64-elf-ldtls-generation", cl::Hidden,
112     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113     cl::init(false));
114 
115 static cl::opt<bool>
116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
117                          cl::desc("Enable AArch64 logical imm instruction "
118                                   "optimization"),
119                          cl::init(true));
120 
121 /// Value type used for condition codes.
122 static const MVT MVT_CC = MVT::i32;
123 
124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
125                                              const AArch64Subtarget &STI)
126     : TargetLowering(TM), Subtarget(&STI) {
127   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
128   // we have to make something up. Arbitrarily, choose ZeroOrOne.
129   setBooleanContents(ZeroOrOneBooleanContent);
130   // When comparing vectors the result sets the different elements in the
131   // vector to all-one or all-zero.
132   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
133 
134   // Set up the register classes.
135   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
136   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
137 
138   if (Subtarget->hasFPARMv8()) {
139     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
140     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
141     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
142     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
143   }
144 
145   if (Subtarget->hasNEON()) {
146     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
147     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
148     // Someone set us up the NEON.
149     addDRTypeForNEON(MVT::v2f32);
150     addDRTypeForNEON(MVT::v8i8);
151     addDRTypeForNEON(MVT::v4i16);
152     addDRTypeForNEON(MVT::v2i32);
153     addDRTypeForNEON(MVT::v1i64);
154     addDRTypeForNEON(MVT::v1f64);
155     addDRTypeForNEON(MVT::v4f16);
156 
157     addQRTypeForNEON(MVT::v4f32);
158     addQRTypeForNEON(MVT::v2f64);
159     addQRTypeForNEON(MVT::v16i8);
160     addQRTypeForNEON(MVT::v8i16);
161     addQRTypeForNEON(MVT::v4i32);
162     addQRTypeForNEON(MVT::v2i64);
163     addQRTypeForNEON(MVT::v8f16);
164   }
165 
166   if (Subtarget->hasSVE()) {
167     // Add legal sve predicate types
168     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
169     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
170     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
171     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
172 
173     // Add legal sve data types
174     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
175     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
176     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
177     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
178 
179     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
180     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
181     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
182     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185 
186     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
187       setOperationAction(ISD::SADDSAT, VT, Legal);
188       setOperationAction(ISD::UADDSAT, VT, Legal);
189       setOperationAction(ISD::SSUBSAT, VT, Legal);
190       setOperationAction(ISD::USUBSAT, VT, Legal);
191       setOperationAction(ISD::SMAX, VT, Legal);
192       setOperationAction(ISD::UMAX, VT, Legal);
193       setOperationAction(ISD::SMIN, VT, Legal);
194       setOperationAction(ISD::UMIN, VT, Legal);
195     }
196 
197     for (auto VT :
198          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
199            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
200       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
201 
202     for (auto VT :
203          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
204            MVT::nxv2f64 }) {
205       setCondCodeAction(ISD::SETO, VT, Expand);
206       setCondCodeAction(ISD::SETOLT, VT, Expand);
207       setCondCodeAction(ISD::SETOLE, VT, Expand);
208       setCondCodeAction(ISD::SETULT, VT, Expand);
209       setCondCodeAction(ISD::SETULE, VT, Expand);
210       setCondCodeAction(ISD::SETUGE, VT, Expand);
211       setCondCodeAction(ISD::SETUGT, VT, Expand);
212       setCondCodeAction(ISD::SETUEQ, VT, Expand);
213       setCondCodeAction(ISD::SETUNE, VT, Expand);
214     }
215   }
216 
217   // Compute derived properties from the register classes
218   computeRegisterProperties(Subtarget->getRegisterInfo());
219 
220   // Provide all sorts of operation actions
221   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
222   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
223   setOperationAction(ISD::SETCC, MVT::i32, Custom);
224   setOperationAction(ISD::SETCC, MVT::i64, Custom);
225   setOperationAction(ISD::SETCC, MVT::f16, Custom);
226   setOperationAction(ISD::SETCC, MVT::f32, Custom);
227   setOperationAction(ISD::SETCC, MVT::f64, Custom);
228   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
229   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
230   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
231   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
232   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
233   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
234   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
235   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
236   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
237   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
238   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
239   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
240   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
241   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
242   setOperationAction(ISD::SELECT, MVT::i32, Custom);
243   setOperationAction(ISD::SELECT, MVT::i64, Custom);
244   setOperationAction(ISD::SELECT, MVT::f16, Custom);
245   setOperationAction(ISD::SELECT, MVT::f32, Custom);
246   setOperationAction(ISD::SELECT, MVT::f64, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
248   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
249   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
250   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
251   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
252   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
253   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
254 
255   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
256   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
257   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
258 
259   setOperationAction(ISD::FREM, MVT::f32, Expand);
260   setOperationAction(ISD::FREM, MVT::f64, Expand);
261   setOperationAction(ISD::FREM, MVT::f80, Expand);
262 
263   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
264 
265   // Custom lowering hooks are needed for XOR
266   // to fold it into CSINC/CSINV.
267   setOperationAction(ISD::XOR, MVT::i32, Custom);
268   setOperationAction(ISD::XOR, MVT::i64, Custom);
269 
270   // Virtually no operation on f128 is legal, but LLVM can't expand them when
271   // there's a valid register class, so we need custom operations in most cases.
272   setOperationAction(ISD::FABS, MVT::f128, Expand);
273   setOperationAction(ISD::FADD, MVT::f128, Custom);
274   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
275   setOperationAction(ISD::FCOS, MVT::f128, Expand);
276   setOperationAction(ISD::FDIV, MVT::f128, Custom);
277   setOperationAction(ISD::FMA, MVT::f128, Expand);
278   setOperationAction(ISD::FMUL, MVT::f128, Custom);
279   setOperationAction(ISD::FNEG, MVT::f128, Expand);
280   setOperationAction(ISD::FPOW, MVT::f128, Expand);
281   setOperationAction(ISD::FREM, MVT::f128, Expand);
282   setOperationAction(ISD::FRINT, MVT::f128, Expand);
283   setOperationAction(ISD::FSIN, MVT::f128, Expand);
284   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
285   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
286   setOperationAction(ISD::FSUB, MVT::f128, Custom);
287   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
288   setOperationAction(ISD::SETCC, MVT::f128, Custom);
289   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
290   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
291   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
292   setOperationAction(ISD::SELECT, MVT::f128, Custom);
293   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
294   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
295 
296   // Lowering for many of the conversions is actually specified by the non-f128
297   // type. The LowerXXX function will be trivial when f128 isn't involved.
298   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
299   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
300   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
301   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
302   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
303   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
304   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
305   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
306   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
307   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
308   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
309   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
310   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
311   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
312   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
313   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
314   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
315   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
316   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
317   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
318   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
319   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
320   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
321   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
322   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
323   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
324   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
325   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
326 
327   // Variable arguments.
328   setOperationAction(ISD::VASTART, MVT::Other, Custom);
329   setOperationAction(ISD::VAARG, MVT::Other, Custom);
330   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
331   setOperationAction(ISD::VAEND, MVT::Other, Expand);
332 
333   // Variable-sized objects.
334   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
335   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
336 
337   if (Subtarget->isTargetWindows())
338     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
339   else
340     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
341 
342   // Constant pool entries
343   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
344 
345   // BlockAddress
346   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
347 
348   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
349   setOperationAction(ISD::ADDC, MVT::i32, Custom);
350   setOperationAction(ISD::ADDE, MVT::i32, Custom);
351   setOperationAction(ISD::SUBC, MVT::i32, Custom);
352   setOperationAction(ISD::SUBE, MVT::i32, Custom);
353   setOperationAction(ISD::ADDC, MVT::i64, Custom);
354   setOperationAction(ISD::ADDE, MVT::i64, Custom);
355   setOperationAction(ISD::SUBC, MVT::i64, Custom);
356   setOperationAction(ISD::SUBE, MVT::i64, Custom);
357 
358   // AArch64 lacks both left-rotate and popcount instructions.
359   setOperationAction(ISD::ROTL, MVT::i32, Expand);
360   setOperationAction(ISD::ROTL, MVT::i64, Expand);
361   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
362     setOperationAction(ISD::ROTL, VT, Expand);
363     setOperationAction(ISD::ROTR, VT, Expand);
364   }
365 
366   // AArch64 doesn't have {U|S}MUL_LOHI.
367   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
368   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
369 
370   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
371   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
372 
373   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
374   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
375   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
376     setOperationAction(ISD::SDIVREM, VT, Expand);
377     setOperationAction(ISD::UDIVREM, VT, Expand);
378   }
379   setOperationAction(ISD::SREM, MVT::i32, Expand);
380   setOperationAction(ISD::SREM, MVT::i64, Expand);
381   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
382   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
383   setOperationAction(ISD::UREM, MVT::i32, Expand);
384   setOperationAction(ISD::UREM, MVT::i64, Expand);
385 
386   // Custom lower Add/Sub/Mul with overflow.
387   setOperationAction(ISD::SADDO, MVT::i32, Custom);
388   setOperationAction(ISD::SADDO, MVT::i64, Custom);
389   setOperationAction(ISD::UADDO, MVT::i32, Custom);
390   setOperationAction(ISD::UADDO, MVT::i64, Custom);
391   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
392   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
393   setOperationAction(ISD::USUBO, MVT::i32, Custom);
394   setOperationAction(ISD::USUBO, MVT::i64, Custom);
395   setOperationAction(ISD::SMULO, MVT::i32, Custom);
396   setOperationAction(ISD::SMULO, MVT::i64, Custom);
397   setOperationAction(ISD::UMULO, MVT::i32, Custom);
398   setOperationAction(ISD::UMULO, MVT::i64, Custom);
399 
400   setOperationAction(ISD::FSIN, MVT::f32, Expand);
401   setOperationAction(ISD::FSIN, MVT::f64, Expand);
402   setOperationAction(ISD::FCOS, MVT::f32, Expand);
403   setOperationAction(ISD::FCOS, MVT::f64, Expand);
404   setOperationAction(ISD::FPOW, MVT::f32, Expand);
405   setOperationAction(ISD::FPOW, MVT::f64, Expand);
406   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
407   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
408   if (Subtarget->hasFullFP16())
409     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
410   else
411     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
412 
413   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
414   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
415   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
416   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
417   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
418   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
419   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
420   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
421   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
422   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
423   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
424   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
425   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
426   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
427   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
428   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
429   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
430   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
431   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
432   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
433   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
434   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
435   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
436   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
437   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
438   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
439   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
440   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
441   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
442   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
443   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
444   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
445   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
446 
447   if (!Subtarget->hasFullFP16()) {
448     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
449     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
450     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
451     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
452     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
453     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
454     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
455     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
456     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
457     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
458     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
459     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
460     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
461     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
462     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
463     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
464     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
465     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
466     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
467     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
468     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
469     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
470 
471     // promote v4f16 to v4f32 when that is known to be safe.
472     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
473     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
474     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
475     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
476     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
477     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
478     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
479     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
480 
481     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
482     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
483     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
484     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
485     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
486     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
487     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
488     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
489     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
490     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
491     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
492     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
493     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
494     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
495     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
496 
497     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
498     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
499     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
500     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
501     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
502     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
503     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
504     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
505     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
506     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
507     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
508     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
509     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
510     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
511     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
512     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
513     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
514     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
515     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
516     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
517   }
518 
519   // AArch64 has implementations of a lot of rounding-like FP operations.
520   for (MVT Ty : {MVT::f32, MVT::f64}) {
521     setOperationAction(ISD::FFLOOR, Ty, Legal);
522     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
523     setOperationAction(ISD::FCEIL, Ty, Legal);
524     setOperationAction(ISD::FRINT, Ty, Legal);
525     setOperationAction(ISD::FTRUNC, Ty, Legal);
526     setOperationAction(ISD::FROUND, Ty, Legal);
527     setOperationAction(ISD::FMINNUM, Ty, Legal);
528     setOperationAction(ISD::FMAXNUM, Ty, Legal);
529     setOperationAction(ISD::FMINIMUM, Ty, Legal);
530     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
531     setOperationAction(ISD::LROUND, Ty, Legal);
532     setOperationAction(ISD::LLROUND, Ty, Legal);
533     setOperationAction(ISD::LRINT, Ty, Legal);
534     setOperationAction(ISD::LLRINT, Ty, Legal);
535   }
536 
537   if (Subtarget->hasFullFP16()) {
538     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
539     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
540     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
541     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
542     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
543     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
544     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
545     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
546     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
547     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
548   }
549 
550   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
551 
552   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
553 
554   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
555   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
556   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
557   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
558   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
559 
560   // 128-bit loads and stores can be done without expanding
561   setOperationAction(ISD::LOAD, MVT::i128, Custom);
562   setOperationAction(ISD::STORE, MVT::i128, Custom);
563 
564   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
565   // custom lowering, as there are no un-paired non-temporal stores and
566   // legalization will break up 256 bit inputs.
567   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
568   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
569   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
570   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
571   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
572   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
573   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
574 
575   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
576   // This requires the Performance Monitors extension.
577   if (Subtarget->hasPerfMon())
578     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
579 
580   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
581       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
582     // Issue __sincos_stret if available.
583     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
584     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
585   } else {
586     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
587     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
588   }
589 
590   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
591     // MSVCRT doesn't have powi; fall back to pow
592     setLibcallName(RTLIB::POWI_F32, nullptr);
593     setLibcallName(RTLIB::POWI_F64, nullptr);
594   }
595 
596   // Make floating-point constants legal for the large code model, so they don't
597   // become loads from the constant pool.
598   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
599     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
600     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
601   }
602 
603   // AArch64 does not have floating-point extending loads, i1 sign-extending
604   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
605   for (MVT VT : MVT::fp_valuetypes()) {
606     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
607     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
608     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
609     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
610   }
611   for (MVT VT : MVT::integer_valuetypes())
612     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
613 
614   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
615   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
616   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
617   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
618   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
619   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
620   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
621 
622   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
623   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
624 
625   // Indexed loads and stores are supported.
626   for (unsigned im = (unsigned)ISD::PRE_INC;
627        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
628     setIndexedLoadAction(im, MVT::i8, Legal);
629     setIndexedLoadAction(im, MVT::i16, Legal);
630     setIndexedLoadAction(im, MVT::i32, Legal);
631     setIndexedLoadAction(im, MVT::i64, Legal);
632     setIndexedLoadAction(im, MVT::f64, Legal);
633     setIndexedLoadAction(im, MVT::f32, Legal);
634     setIndexedLoadAction(im, MVT::f16, Legal);
635     setIndexedStoreAction(im, MVT::i8, Legal);
636     setIndexedStoreAction(im, MVT::i16, Legal);
637     setIndexedStoreAction(im, MVT::i32, Legal);
638     setIndexedStoreAction(im, MVT::i64, Legal);
639     setIndexedStoreAction(im, MVT::f64, Legal);
640     setIndexedStoreAction(im, MVT::f32, Legal);
641     setIndexedStoreAction(im, MVT::f16, Legal);
642   }
643 
644   // Trap.
645   setOperationAction(ISD::TRAP, MVT::Other, Legal);
646   if (Subtarget->isTargetWindows())
647     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
648 
649   // We combine OR nodes for bitfield operations.
650   setTargetDAGCombine(ISD::OR);
651   // Try to create BICs for vector ANDs.
652   setTargetDAGCombine(ISD::AND);
653 
654   // Vector add and sub nodes may conceal a high-half opportunity.
655   // Also, try to fold ADD into CSINC/CSINV..
656   setTargetDAGCombine(ISD::ADD);
657   setTargetDAGCombine(ISD::SUB);
658   setTargetDAGCombine(ISD::SRL);
659   setTargetDAGCombine(ISD::XOR);
660   setTargetDAGCombine(ISD::SINT_TO_FP);
661   setTargetDAGCombine(ISD::UINT_TO_FP);
662 
663   setTargetDAGCombine(ISD::FP_TO_SINT);
664   setTargetDAGCombine(ISD::FP_TO_UINT);
665   setTargetDAGCombine(ISD::FDIV);
666 
667   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
668 
669   setTargetDAGCombine(ISD::ANY_EXTEND);
670   setTargetDAGCombine(ISD::ZERO_EXTEND);
671   setTargetDAGCombine(ISD::SIGN_EXTEND);
672   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
673   setTargetDAGCombine(ISD::CONCAT_VECTORS);
674   setTargetDAGCombine(ISD::STORE);
675   if (Subtarget->supportsAddressTopByteIgnored())
676     setTargetDAGCombine(ISD::LOAD);
677 
678   setTargetDAGCombine(ISD::MUL);
679 
680   setTargetDAGCombine(ISD::SELECT);
681   setTargetDAGCombine(ISD::VSELECT);
682 
683   setTargetDAGCombine(ISD::INTRINSIC_VOID);
684   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
685   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
686 
687   setTargetDAGCombine(ISD::GlobalAddress);
688 
689   // In case of strict alignment, avoid an excessive number of byte wide stores.
690   MaxStoresPerMemsetOptSize = 8;
691   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
692                        ? MaxStoresPerMemsetOptSize : 32;
693 
694   MaxGluedStoresPerMemcpy = 4;
695   MaxStoresPerMemcpyOptSize = 4;
696   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
697                        ? MaxStoresPerMemcpyOptSize : 16;
698 
699   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
700 
701   MaxLoadsPerMemcmpOptSize = 4;
702   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
703                       ? MaxLoadsPerMemcmpOptSize : 8;
704 
705   setStackPointerRegisterToSaveRestore(AArch64::SP);
706 
707   setSchedulingPreference(Sched::Hybrid);
708 
709   EnableExtLdPromotion = true;
710 
711   // Set required alignment.
712   setMinFunctionAlignment(Align(4));
713   // Set preferred alignments.
714   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
715   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
716 
717   // Only change the limit for entries in a jump table if specified by
718   // the sub target, but not at the command line.
719   unsigned MaxJT = STI.getMaximumJumpTableSize();
720   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
721     setMaximumJumpTableSize(MaxJT);
722 
723   setHasExtractBitsInsn(true);
724 
725   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
726 
727   if (Subtarget->hasNEON()) {
728     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
729     // silliness like this:
730     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
731     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
732     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
734     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
735     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
736     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
737     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
738     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
739     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
740     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
741     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
742     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
743     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
744     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
745     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
746     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
747     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
748     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
749     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
750     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
751     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
752     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
753     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
754     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
755 
756     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
757     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
758     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
759     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
760     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
761 
762     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
763 
764     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
765     // elements smaller than i32, so promote the input to i32 first.
766     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
767     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
768     // i8 vector elements also need promotion to i32 for v8i8
769     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
770     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
771     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
772     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
773     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
774     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
775     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
776     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
777     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
778     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
779     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
780 
781     if (Subtarget->hasFullFP16()) {
782       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
783       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
784       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
785       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
786     } else {
787       // when AArch64 doesn't have fullfp16 support, promote the input
788       // to i32 first.
789       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
790       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
791       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
792       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
793     }
794 
795     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
796     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
797 
798     // AArch64 doesn't have MUL.2d:
799     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
800     // Custom handling for some quad-vector types to detect MULL.
801     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
802     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
803     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
804 
805     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
806                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
807       // Vector reductions
808       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
809       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
810       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
811       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
812       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
813 
814       // Saturates
815       setOperationAction(ISD::SADDSAT, VT, Legal);
816       setOperationAction(ISD::UADDSAT, VT, Legal);
817       setOperationAction(ISD::SSUBSAT, VT, Legal);
818       setOperationAction(ISD::USUBSAT, VT, Legal);
819     }
820     for (MVT VT : { MVT::v4f16, MVT::v2f32,
821                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
822       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
823       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
824     }
825 
826     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
827     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
828     // Likewise, narrowing and extending vector loads/stores aren't handled
829     // directly.
830     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
831       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
832 
833       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
834         setOperationAction(ISD::MULHS, VT, Legal);
835         setOperationAction(ISD::MULHU, VT, Legal);
836       } else {
837         setOperationAction(ISD::MULHS, VT, Expand);
838         setOperationAction(ISD::MULHU, VT, Expand);
839       }
840       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
842 
843       setOperationAction(ISD::BSWAP, VT, Expand);
844       setOperationAction(ISD::CTTZ, VT, Expand);
845 
846       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
847         setTruncStoreAction(VT, InnerVT, Expand);
848         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
849         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
850         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
851       }
852     }
853 
854     // AArch64 has implementations of a lot of rounding-like FP operations.
855     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
856       setOperationAction(ISD::FFLOOR, Ty, Legal);
857       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
858       setOperationAction(ISD::FCEIL, Ty, Legal);
859       setOperationAction(ISD::FRINT, Ty, Legal);
860       setOperationAction(ISD::FTRUNC, Ty, Legal);
861       setOperationAction(ISD::FROUND, Ty, Legal);
862     }
863 
864     if (Subtarget->hasFullFP16()) {
865       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
866         setOperationAction(ISD::FFLOOR, Ty, Legal);
867         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
868         setOperationAction(ISD::FCEIL, Ty, Legal);
869         setOperationAction(ISD::FRINT, Ty, Legal);
870         setOperationAction(ISD::FTRUNC, Ty, Legal);
871         setOperationAction(ISD::FROUND, Ty, Legal);
872       }
873     }
874 
875     if (Subtarget->hasSVE())
876       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
877 
878     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
879   }
880 
881   if (Subtarget->hasSVE()) {
882     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
883     // splat of 0 or undef) once vector selects supported in SVE codegen. See
884     // D68877 for more details.
885     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
886       if (isTypeLegal(VT))
887         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
888     }
889     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
890     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
891 
892     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
893       if (isTypeLegal(VT)) {
894         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
895       }
896     }
897   }
898 
899   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
900 }
901 
902 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
903   assert(VT.isVector() && "VT should be a vector type");
904 
905   if (VT.isFloatingPoint()) {
906     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
907     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
908     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
909   }
910 
911   // Mark vector float intrinsics as expand.
912   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
913     setOperationAction(ISD::FSIN, VT, Expand);
914     setOperationAction(ISD::FCOS, VT, Expand);
915     setOperationAction(ISD::FPOW, VT, Expand);
916     setOperationAction(ISD::FLOG, VT, Expand);
917     setOperationAction(ISD::FLOG2, VT, Expand);
918     setOperationAction(ISD::FLOG10, VT, Expand);
919     setOperationAction(ISD::FEXP, VT, Expand);
920     setOperationAction(ISD::FEXP2, VT, Expand);
921 
922     // But we do support custom-lowering for FCOPYSIGN.
923     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
924   }
925 
926   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
927   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
928   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
929   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
930   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
931   setOperationAction(ISD::SRA, VT, Custom);
932   setOperationAction(ISD::SRL, VT, Custom);
933   setOperationAction(ISD::SHL, VT, Custom);
934   setOperationAction(ISD::OR, VT, Custom);
935   setOperationAction(ISD::SETCC, VT, Custom);
936   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
937 
938   setOperationAction(ISD::SELECT, VT, Expand);
939   setOperationAction(ISD::SELECT_CC, VT, Expand);
940   setOperationAction(ISD::VSELECT, VT, Expand);
941   for (MVT InnerVT : MVT::all_valuetypes())
942     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
943 
944   // CNT supports only B element sizes, then use UADDLP to widen.
945   if (VT != MVT::v8i8 && VT != MVT::v16i8)
946     setOperationAction(ISD::CTPOP, VT, Custom);
947 
948   setOperationAction(ISD::UDIV, VT, Expand);
949   setOperationAction(ISD::SDIV, VT, Expand);
950   setOperationAction(ISD::UREM, VT, Expand);
951   setOperationAction(ISD::SREM, VT, Expand);
952   setOperationAction(ISD::FREM, VT, Expand);
953 
954   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
955   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
956 
957   if (!VT.isFloatingPoint())
958     setOperationAction(ISD::ABS, VT, Legal);
959 
960   // [SU][MIN|MAX] are available for all NEON types apart from i64.
961   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
962     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
963       setOperationAction(Opcode, VT, Legal);
964 
965   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
966   if (VT.isFloatingPoint() &&
967       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
968     for (unsigned Opcode :
969          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
970       setOperationAction(Opcode, VT, Legal);
971 
972   if (Subtarget->isLittleEndian()) {
973     for (unsigned im = (unsigned)ISD::PRE_INC;
974          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
975       setIndexedLoadAction(im, VT, Legal);
976       setIndexedStoreAction(im, VT, Legal);
977     }
978   }
979 }
980 
981 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
982   addRegisterClass(VT, &AArch64::FPR64RegClass);
983   addTypeForNEON(VT, MVT::v2i32);
984 }
985 
986 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
987   addRegisterClass(VT, &AArch64::FPR128RegClass);
988   addTypeForNEON(VT, MVT::v4i32);
989 }
990 
991 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
992                                               EVT VT) const {
993   if (!VT.isVector())
994     return MVT::i32;
995   return VT.changeVectorElementTypeToInteger();
996 }
997 
998 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
999                                const APInt &Demanded,
1000                                TargetLowering::TargetLoweringOpt &TLO,
1001                                unsigned NewOpc) {
1002   uint64_t OldImm = Imm, NewImm, Enc;
1003   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1004 
1005   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1006   // bimm64.
1007   if (Imm == 0 || Imm == Mask ||
1008       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1009     return false;
1010 
1011   unsigned EltSize = Size;
1012   uint64_t DemandedBits = Demanded.getZExtValue();
1013 
1014   // Clear bits that are not demanded.
1015   Imm &= DemandedBits;
1016 
1017   while (true) {
1018     // The goal here is to set the non-demanded bits in a way that minimizes
1019     // the number of switching between 0 and 1. In order to achieve this goal,
1020     // we set the non-demanded bits to the value of the preceding demanded bits.
1021     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1022     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1023     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1024     // The final result is 0b11000011.
1025     uint64_t NonDemandedBits = ~DemandedBits;
1026     uint64_t InvertedImm = ~Imm & DemandedBits;
1027     uint64_t RotatedImm =
1028         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1029         NonDemandedBits;
1030     uint64_t Sum = RotatedImm + NonDemandedBits;
1031     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1032     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1033     NewImm = (Imm | Ones) & Mask;
1034 
1035     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1036     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1037     // we halve the element size and continue the search.
1038     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1039       break;
1040 
1041     // We cannot shrink the element size any further if it is 2-bits.
1042     if (EltSize == 2)
1043       return false;
1044 
1045     EltSize /= 2;
1046     Mask >>= EltSize;
1047     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1048 
1049     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1050     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1051       return false;
1052 
1053     // Merge the upper and lower halves of Imm and DemandedBits.
1054     Imm |= Hi;
1055     DemandedBits |= DemandedBitsHi;
1056   }
1057 
1058   ++NumOptimizedImms;
1059 
1060   // Replicate the element across the register width.
1061   while (EltSize < Size) {
1062     NewImm |= NewImm << EltSize;
1063     EltSize *= 2;
1064   }
1065 
1066   (void)OldImm;
1067   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1068          "demanded bits should never be altered");
1069   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1070 
1071   // Create the new constant immediate node.
1072   EVT VT = Op.getValueType();
1073   SDLoc DL(Op);
1074   SDValue New;
1075 
1076   // If the new constant immediate is all-zeros or all-ones, let the target
1077   // independent DAG combine optimize this node.
1078   if (NewImm == 0 || NewImm == OrigMask) {
1079     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1080                           TLO.DAG.getConstant(NewImm, DL, VT));
1081   // Otherwise, create a machine node so that target independent DAG combine
1082   // doesn't undo this optimization.
1083   } else {
1084     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1085     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1086     New = SDValue(
1087         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1088   }
1089 
1090   return TLO.CombineTo(Op, New);
1091 }
1092 
1093 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1094     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1095   // Delay this optimization to as late as possible.
1096   if (!TLO.LegalOps)
1097     return false;
1098 
1099   if (!EnableOptimizeLogicalImm)
1100     return false;
1101 
1102   EVT VT = Op.getValueType();
1103   if (VT.isVector())
1104     return false;
1105 
1106   unsigned Size = VT.getSizeInBits();
1107   assert((Size == 32 || Size == 64) &&
1108          "i32 or i64 is expected after legalization.");
1109 
1110   // Exit early if we demand all bits.
1111   if (Demanded.countPopulation() == Size)
1112     return false;
1113 
1114   unsigned NewOpc;
1115   switch (Op.getOpcode()) {
1116   default:
1117     return false;
1118   case ISD::AND:
1119     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1120     break;
1121   case ISD::OR:
1122     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1123     break;
1124   case ISD::XOR:
1125     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1126     break;
1127   }
1128   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1129   if (!C)
1130     return false;
1131   uint64_t Imm = C->getZExtValue();
1132   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1133 }
1134 
1135 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1136 /// Mask are known to be either zero or one and return them Known.
1137 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1138     const SDValue Op, KnownBits &Known,
1139     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1140   switch (Op.getOpcode()) {
1141   default:
1142     break;
1143   case AArch64ISD::CSEL: {
1144     KnownBits Known2;
1145     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1146     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1147     Known.Zero &= Known2.Zero;
1148     Known.One &= Known2.One;
1149     break;
1150   }
1151   case AArch64ISD::LOADgot:
1152   case AArch64ISD::ADDlow: {
1153     if (!Subtarget->isTargetILP32())
1154       break;
1155     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1156     Known.Zero = APInt::getHighBitsSet(64, 32);
1157     break;
1158   }
1159   case ISD::INTRINSIC_W_CHAIN: {
1160     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1161     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1162     switch (IntID) {
1163     default: return;
1164     case Intrinsic::aarch64_ldaxr:
1165     case Intrinsic::aarch64_ldxr: {
1166       unsigned BitWidth = Known.getBitWidth();
1167       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1168       unsigned MemBits = VT.getScalarSizeInBits();
1169       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1170       return;
1171     }
1172     }
1173     break;
1174   }
1175   case ISD::INTRINSIC_WO_CHAIN:
1176   case ISD::INTRINSIC_VOID: {
1177     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1178     switch (IntNo) {
1179     default:
1180       break;
1181     case Intrinsic::aarch64_neon_umaxv:
1182     case Intrinsic::aarch64_neon_uminv: {
1183       // Figure out the datatype of the vector operand. The UMINV instruction
1184       // will zero extend the result, so we can mark as known zero all the
1185       // bits larger than the element datatype. 32-bit or larget doesn't need
1186       // this as those are legal types and will be handled by isel directly.
1187       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1188       unsigned BitWidth = Known.getBitWidth();
1189       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1190         assert(BitWidth >= 8 && "Unexpected width!");
1191         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1192         Known.Zero |= Mask;
1193       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1194         assert(BitWidth >= 16 && "Unexpected width!");
1195         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1196         Known.Zero |= Mask;
1197       }
1198       break;
1199     } break;
1200     }
1201   }
1202   }
1203 }
1204 
1205 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1206                                                   EVT) const {
1207   return MVT::i64;
1208 }
1209 
1210 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1211     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1212     bool *Fast) const {
1213   if (Subtarget->requiresStrictAlign())
1214     return false;
1215 
1216   if (Fast) {
1217     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1218     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1219             // See comments in performSTORECombine() for more details about
1220             // these conditions.
1221 
1222             // Code that uses clang vector extensions can mark that it
1223             // wants unaligned accesses to be treated as fast by
1224             // underspecifying alignment to be 1 or 2.
1225             Align <= 2 ||
1226 
1227             // Disregard v2i64. Memcpy lowering produces those and splitting
1228             // them regresses performance on micro-benchmarks and olden/bh.
1229             VT == MVT::v2i64;
1230   }
1231   return true;
1232 }
1233 
1234 // Same as above but handling LLTs instead.
1235 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1236     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1237     bool *Fast) const {
1238   if (Subtarget->requiresStrictAlign())
1239     return false;
1240 
1241   if (Fast) {
1242     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1243     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1244             Ty.getSizeInBytes() != 16 ||
1245             // See comments in performSTORECombine() for more details about
1246             // these conditions.
1247 
1248             // Code that uses clang vector extensions can mark that it
1249             // wants unaligned accesses to be treated as fast by
1250             // underspecifying alignment to be 1 or 2.
1251             Align <= 2 ||
1252 
1253             // Disregard v2i64. Memcpy lowering produces those and splitting
1254             // them regresses performance on micro-benchmarks and olden/bh.
1255             Ty == LLT::vector(2, 64);
1256   }
1257   return true;
1258 }
1259 
1260 FastISel *
1261 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1262                                       const TargetLibraryInfo *libInfo) const {
1263   return AArch64::createFastISel(funcInfo, libInfo);
1264 }
1265 
1266 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1267   switch ((AArch64ISD::NodeType)Opcode) {
1268   case AArch64ISD::FIRST_NUMBER:      break;
1269   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1270   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1271   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1272   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1273   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1274   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1275   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1276   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1277   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1278   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1279   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1280   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1281   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1282   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1283   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1284   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1285   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1286   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1287   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1288   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1289   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1290   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1291   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1292   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1293   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1294   case AArch64ISD::STRICT_FCMP:       return "AArch64ISD::STRICT_FCMP";
1295   case AArch64ISD::STRICT_FCMPE:      return "AArch64ISD::STRICT_FCMPE";
1296   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1297   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1298   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1299   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1300   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1301   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1302   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1303   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1304   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1305   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1306   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1307   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1308   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1309   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1310   case AArch64ISD::BSP:               return "AArch64ISD::BSP";
1311   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1312   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1313   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1314   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1315   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1316   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1317   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1318   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1319   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1320   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1321   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1322   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1323   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1324   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1325   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1326   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1327   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1328   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1329   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1330   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1331   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1332   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1333   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1334   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1335   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1336   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1337   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1338   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1339   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1340   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1341   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1342   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1343   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1344   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1345   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1346   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1347   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1348   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1349   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1350   case AArch64ISD::SMAXV_PRED:        return "AArch64ISD::SMAXV_PRED";
1351   case AArch64ISD::UMAXV_PRED:        return "AArch64ISD::UMAXV_PRED";
1352   case AArch64ISD::SMINV_PRED:        return "AArch64ISD::SMINV_PRED";
1353   case AArch64ISD::UMINV_PRED:        return "AArch64ISD::UMINV_PRED";
1354   case AArch64ISD::ORV_PRED:          return "AArch64ISD::ORV_PRED";
1355   case AArch64ISD::EORV_PRED:         return "AArch64ISD::EORV_PRED";
1356   case AArch64ISD::ANDV_PRED:         return "AArch64ISD::ANDV_PRED";
1357   case AArch64ISD::CLASTA_N:          return "AArch64ISD::CLASTA_N";
1358   case AArch64ISD::CLASTB_N:          return "AArch64ISD::CLASTB_N";
1359   case AArch64ISD::LASTA:             return "AArch64ISD::LASTA";
1360   case AArch64ISD::LASTB:             return "AArch64ISD::LASTB";
1361   case AArch64ISD::REV:               return "AArch64ISD::REV";
1362   case AArch64ISD::REINTERPRET_CAST:  return "AArch64ISD::REINTERPRET_CAST";
1363   case AArch64ISD::TBL:               return "AArch64ISD::TBL";
1364   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1365   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1366   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1367   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1368   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1369   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1370   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1371   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1372   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1373   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1374   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1375   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1376   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1377   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1378   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1379   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1380   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1381   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1382   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1383   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1384   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1385   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1386   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1387   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1388   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1389   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1390   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1391   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1392   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1393   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1394   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1395   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1396   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1397   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1398   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1399   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1400   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1401   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1402   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1403   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1404   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1405   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1406   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1407   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1408   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1409   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1410   case AArch64ISD::STG:               return "AArch64ISD::STG";
1411   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1412   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1413   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1414   case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1415   case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1416   case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1417   case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1418   case AArch64ISD::INSR:              return "AArch64ISD::INSR";
1419   case AArch64ISD::PTEST:             return "AArch64ISD::PTEST";
1420   case AArch64ISD::PTRUE:             return "AArch64ISD::PTRUE";
1421   case AArch64ISD::LDNF1:             return "AArch64ISD::LDNF1";
1422   case AArch64ISD::LDNF1S:            return "AArch64ISD::LDNF1S";
1423   case AArch64ISD::LDFF1:             return "AArch64ISD::LDFF1";
1424   case AArch64ISD::LDFF1S:            return "AArch64ISD::LDFF1S";
1425   case AArch64ISD::GLD1:              return "AArch64ISD::GLD1";
1426   case AArch64ISD::GLD1_SCALED:       return "AArch64ISD::GLD1_SCALED";
1427   case AArch64ISD::GLD1_SXTW:         return "AArch64ISD::GLD1_SXTW";
1428   case AArch64ISD::GLD1_UXTW:         return "AArch64ISD::GLD1_UXTW";
1429   case AArch64ISD::GLD1_SXTW_SCALED:  return "AArch64ISD::GLD1_SXTW_SCALED";
1430   case AArch64ISD::GLD1_UXTW_SCALED:  return "AArch64ISD::GLD1_UXTW_SCALED";
1431   case AArch64ISD::GLD1_IMM:          return "AArch64ISD::GLD1_IMM";
1432   case AArch64ISD::GLD1S:             return "AArch64ISD::GLD1S";
1433   case AArch64ISD::GLD1S_SCALED:      return "AArch64ISD::GLD1S_SCALED";
1434   case AArch64ISD::GLD1S_SXTW:        return "AArch64ISD::GLD1S_SXTW";
1435   case AArch64ISD::GLD1S_UXTW:        return "AArch64ISD::GLD1S_UXTW";
1436   case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1437   case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1438   case AArch64ISD::GLD1S_IMM:         return "AArch64ISD::GLD1S_IMM";
1439   case AArch64ISD::GLDFF1:            return "AArch64ISD::GLDFF1";
1440   case AArch64ISD::GLDFF1_SCALED:     return "AArch64ISD::GLDFF1_SCALED";
1441   case AArch64ISD::GLDFF1_SXTW:       return "AArch64ISD::GLDFF1_SXTW";
1442   case AArch64ISD::GLDFF1_UXTW:       return "AArch64ISD::GLDFF1_UXTW";
1443   case AArch64ISD::GLDFF1_SXTW_SCALED:return "AArch64ISD::GLDFF1_SXTW_SCALED";
1444   case AArch64ISD::GLDFF1_UXTW_SCALED:return "AArch64ISD::GLDFF1_UXTW_SCALED";
1445   case AArch64ISD::GLDFF1_IMM:        return "AArch64ISD::GLDFF1_IMM";
1446   case AArch64ISD::GLDFF1S:           return "AArch64ISD::GLDFF1S";
1447   case AArch64ISD::GLDFF1S_SCALED:    return "AArch64ISD::GLDFF1S_SCALED";
1448   case AArch64ISD::GLDFF1S_SXTW:      return "AArch64ISD::GLDFF1S_SXTW";
1449   case AArch64ISD::GLDFF1S_UXTW:      return "AArch64ISD::GLDFF1S_UXTW";
1450   case AArch64ISD::GLDFF1S_SXTW_SCALED:
1451     return "AArch64ISD::GLDFF1S_SXTW_SCALED";
1452   case AArch64ISD::GLDFF1S_UXTW_SCALED:
1453     return "AArch64ISD::GLDFF1S_UXTW_SCALED";
1454   case AArch64ISD::GLDFF1S_IMM:       return "AArch64ISD::GLDFF1S_IMM";
1455 
1456   case AArch64ISD::GLDNT1:            return "AArch64ISD::GLDNT1";
1457   case AArch64ISD::GLDNT1_INDEX:      return "AArch64ISD::GLDNT1_INDEX";
1458   case AArch64ISD::GLDNT1S:           return "AArch64ISD::GLDNT1S";
1459 
1460   case AArch64ISD::SST1:              return "AArch64ISD::SST1";
1461   case AArch64ISD::SST1_SCALED:       return "AArch64ISD::SST1_SCALED";
1462   case AArch64ISD::SST1_SXTW:         return "AArch64ISD::SST1_SXTW";
1463   case AArch64ISD::SST1_UXTW:         return "AArch64ISD::SST1_UXTW";
1464   case AArch64ISD::SST1_SXTW_SCALED:  return "AArch64ISD::SST1_SXTW_SCALED";
1465   case AArch64ISD::SST1_UXTW_SCALED:  return "AArch64ISD::SST1_UXTW_SCALED";
1466   case AArch64ISD::SST1_IMM:          return "AArch64ISD::SST1_IMM";
1467 
1468   case AArch64ISD::SSTNT1:            return "AArch64ISD::SSTNT1";
1469   case AArch64ISD::SSTNT1_INDEX:      return "AArch64ISD::SSTNT1_INDEX";
1470 
1471   case AArch64ISD::LDP:               return "AArch64ISD::LDP";
1472   case AArch64ISD::STP:               return "AArch64ISD::STP";
1473   case AArch64ISD::STNP:              return "AArch64ISD::STNP";
1474   case AArch64ISD::DUP_PRED:          return "AArch64ISD::DUP_PRED";
1475   case AArch64ISD::INDEX_VECTOR:      return "AArch64ISD::INDEX_VECTOR";
1476   }
1477   return nullptr;
1478 }
1479 
1480 MachineBasicBlock *
1481 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1482                                     MachineBasicBlock *MBB) const {
1483   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1484   // phi node:
1485 
1486   // OrigBB:
1487   //     [... previous instrs leading to comparison ...]
1488   //     b.ne TrueBB
1489   //     b EndBB
1490   // TrueBB:
1491   //     ; Fallthrough
1492   // EndBB:
1493   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1494 
1495   MachineFunction *MF = MBB->getParent();
1496   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1497   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1498   DebugLoc DL = MI.getDebugLoc();
1499   MachineFunction::iterator It = ++MBB->getIterator();
1500 
1501   Register DestReg = MI.getOperand(0).getReg();
1502   Register IfTrueReg = MI.getOperand(1).getReg();
1503   Register IfFalseReg = MI.getOperand(2).getReg();
1504   unsigned CondCode = MI.getOperand(3).getImm();
1505   bool NZCVKilled = MI.getOperand(4).isKill();
1506 
1507   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1508   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1509   MF->insert(It, TrueBB);
1510   MF->insert(It, EndBB);
1511 
1512   // Transfer rest of current basic-block to EndBB
1513   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1514                 MBB->end());
1515   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1516 
1517   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1518   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1519   MBB->addSuccessor(TrueBB);
1520   MBB->addSuccessor(EndBB);
1521 
1522   // TrueBB falls through to the end.
1523   TrueBB->addSuccessor(EndBB);
1524 
1525   if (!NZCVKilled) {
1526     TrueBB->addLiveIn(AArch64::NZCV);
1527     EndBB->addLiveIn(AArch64::NZCV);
1528   }
1529 
1530   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1531       .addReg(IfTrueReg)
1532       .addMBB(TrueBB)
1533       .addReg(IfFalseReg)
1534       .addMBB(MBB);
1535 
1536   MI.eraseFromParent();
1537   return EndBB;
1538 }
1539 
1540 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1541        MachineInstr &MI, MachineBasicBlock *BB) const {
1542   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1543              BB->getParent()->getFunction().getPersonalityFn())) &&
1544          "SEH does not use catchret!");
1545   return BB;
1546 }
1547 
1548 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1549     MachineInstr &MI, MachineBasicBlock *BB) const {
1550   switch (MI.getOpcode()) {
1551   default:
1552 #ifndef NDEBUG
1553     MI.dump();
1554 #endif
1555     llvm_unreachable("Unexpected instruction for custom inserter!");
1556 
1557   case AArch64::F128CSEL:
1558     return EmitF128CSEL(MI, BB);
1559 
1560   case TargetOpcode::STACKMAP:
1561   case TargetOpcode::PATCHPOINT:
1562     return emitPatchPoint(MI, BB);
1563 
1564   case AArch64::CATCHRET:
1565     return EmitLoweredCatchRet(MI, BB);
1566   }
1567 }
1568 
1569 //===----------------------------------------------------------------------===//
1570 // AArch64 Lowering private implementation.
1571 //===----------------------------------------------------------------------===//
1572 
1573 //===----------------------------------------------------------------------===//
1574 // Lowering Code
1575 //===----------------------------------------------------------------------===//
1576 
1577 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1578 /// CC
1579 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1580   switch (CC) {
1581   default:
1582     llvm_unreachable("Unknown condition code!");
1583   case ISD::SETNE:
1584     return AArch64CC::NE;
1585   case ISD::SETEQ:
1586     return AArch64CC::EQ;
1587   case ISD::SETGT:
1588     return AArch64CC::GT;
1589   case ISD::SETGE:
1590     return AArch64CC::GE;
1591   case ISD::SETLT:
1592     return AArch64CC::LT;
1593   case ISD::SETLE:
1594     return AArch64CC::LE;
1595   case ISD::SETUGT:
1596     return AArch64CC::HI;
1597   case ISD::SETUGE:
1598     return AArch64CC::HS;
1599   case ISD::SETULT:
1600     return AArch64CC::LO;
1601   case ISD::SETULE:
1602     return AArch64CC::LS;
1603   }
1604 }
1605 
1606 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1607 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1608                                   AArch64CC::CondCode &CondCode,
1609                                   AArch64CC::CondCode &CondCode2) {
1610   CondCode2 = AArch64CC::AL;
1611   switch (CC) {
1612   default:
1613     llvm_unreachable("Unknown FP condition!");
1614   case ISD::SETEQ:
1615   case ISD::SETOEQ:
1616     CondCode = AArch64CC::EQ;
1617     break;
1618   case ISD::SETGT:
1619   case ISD::SETOGT:
1620     CondCode = AArch64CC::GT;
1621     break;
1622   case ISD::SETGE:
1623   case ISD::SETOGE:
1624     CondCode = AArch64CC::GE;
1625     break;
1626   case ISD::SETOLT:
1627     CondCode = AArch64CC::MI;
1628     break;
1629   case ISD::SETOLE:
1630     CondCode = AArch64CC::LS;
1631     break;
1632   case ISD::SETONE:
1633     CondCode = AArch64CC::MI;
1634     CondCode2 = AArch64CC::GT;
1635     break;
1636   case ISD::SETO:
1637     CondCode = AArch64CC::VC;
1638     break;
1639   case ISD::SETUO:
1640     CondCode = AArch64CC::VS;
1641     break;
1642   case ISD::SETUEQ:
1643     CondCode = AArch64CC::EQ;
1644     CondCode2 = AArch64CC::VS;
1645     break;
1646   case ISD::SETUGT:
1647     CondCode = AArch64CC::HI;
1648     break;
1649   case ISD::SETUGE:
1650     CondCode = AArch64CC::PL;
1651     break;
1652   case ISD::SETLT:
1653   case ISD::SETULT:
1654     CondCode = AArch64CC::LT;
1655     break;
1656   case ISD::SETLE:
1657   case ISD::SETULE:
1658     CondCode = AArch64CC::LE;
1659     break;
1660   case ISD::SETNE:
1661   case ISD::SETUNE:
1662     CondCode = AArch64CC::NE;
1663     break;
1664   }
1665 }
1666 
1667 /// Convert a DAG fp condition code to an AArch64 CC.
1668 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1669 /// should be AND'ed instead of OR'ed.
1670 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1671                                      AArch64CC::CondCode &CondCode,
1672                                      AArch64CC::CondCode &CondCode2) {
1673   CondCode2 = AArch64CC::AL;
1674   switch (CC) {
1675   default:
1676     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1677     assert(CondCode2 == AArch64CC::AL);
1678     break;
1679   case ISD::SETONE:
1680     // (a one b)
1681     // == ((a olt b) || (a ogt b))
1682     // == ((a ord b) && (a une b))
1683     CondCode = AArch64CC::VC;
1684     CondCode2 = AArch64CC::NE;
1685     break;
1686   case ISD::SETUEQ:
1687     // (a ueq b)
1688     // == ((a uno b) || (a oeq b))
1689     // == ((a ule b) && (a uge b))
1690     CondCode = AArch64CC::PL;
1691     CondCode2 = AArch64CC::LE;
1692     break;
1693   }
1694 }
1695 
1696 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1697 /// CC usable with the vector instructions. Fewer operations are available
1698 /// without a real NZCV register, so we have to use less efficient combinations
1699 /// to get the same effect.
1700 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1701                                         AArch64CC::CondCode &CondCode,
1702                                         AArch64CC::CondCode &CondCode2,
1703                                         bool &Invert) {
1704   Invert = false;
1705   switch (CC) {
1706   default:
1707     // Mostly the scalar mappings work fine.
1708     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1709     break;
1710   case ISD::SETUO:
1711     Invert = true;
1712     LLVM_FALLTHROUGH;
1713   case ISD::SETO:
1714     CondCode = AArch64CC::MI;
1715     CondCode2 = AArch64CC::GE;
1716     break;
1717   case ISD::SETUEQ:
1718   case ISD::SETULT:
1719   case ISD::SETULE:
1720   case ISD::SETUGT:
1721   case ISD::SETUGE:
1722     // All of the compare-mask comparisons are ordered, but we can switch
1723     // between the two by a double inversion. E.g. ULE == !OGT.
1724     Invert = true;
1725     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1726                           CondCode, CondCode2);
1727     break;
1728   }
1729 }
1730 
1731 static bool isLegalArithImmed(uint64_t C) {
1732   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1733   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1734   LLVM_DEBUG(dbgs() << "Is imm " << C
1735                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1736   return IsLegal;
1737 }
1738 
1739 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1740 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1741 // can be set differently by this operation. It comes down to whether
1742 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1743 // everything is fine. If not then the optimization is wrong. Thus general
1744 // comparisons are only valid if op2 != 0.
1745 //
1746 // So, finally, the only LLVM-native comparisons that don't mention C and V
1747 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1748 // the absence of information about op2.
1749 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1750   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1751          (CC == ISD::SETEQ || CC == ISD::SETNE);
1752 }
1753 
1754 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1755                                       SelectionDAG &DAG, SDValue Chain,
1756                                       bool IsSignaling) {
1757   EVT VT = LHS.getValueType();
1758   assert(VT != MVT::f128);
1759   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1760   unsigned Opcode =
1761       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1762   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1763 }
1764 
1765 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1766                               const SDLoc &dl, SelectionDAG &DAG) {
1767   EVT VT = LHS.getValueType();
1768   const bool FullFP16 =
1769     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1770 
1771   if (VT.isFloatingPoint()) {
1772     assert(VT != MVT::f128);
1773     if (VT == MVT::f16 && !FullFP16) {
1774       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1775       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1776       VT = MVT::f32;
1777     }
1778     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1779   }
1780 
1781   // The CMP instruction is just an alias for SUBS, and representing it as
1782   // SUBS means that it's possible to get CSE with subtract operations.
1783   // A later phase can perform the optimization of setting the destination
1784   // register to WZR/XZR if it ends up being unused.
1785   unsigned Opcode = AArch64ISD::SUBS;
1786 
1787   if (isCMN(RHS, CC)) {
1788     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1789     Opcode = AArch64ISD::ADDS;
1790     RHS = RHS.getOperand(1);
1791   } else if (isCMN(LHS, CC)) {
1792     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1793     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1794     Opcode = AArch64ISD::ADDS;
1795     LHS = LHS.getOperand(1);
1796   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
1797     if (LHS.getOpcode() == ISD::AND) {
1798       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1799       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1800       // of the signed comparisons.
1801       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
1802                                            DAG.getVTList(VT, MVT_CC),
1803                                            LHS.getOperand(0),
1804                                            LHS.getOperand(1));
1805       // Replace all users of (and X, Y) with newly generated (ands X, Y)
1806       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
1807       return ANDSNode.getValue(1);
1808     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
1809       // Use result of ANDS
1810       return LHS.getValue(1);
1811     }
1812   }
1813 
1814   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1815       .getValue(1);
1816 }
1817 
1818 /// \defgroup AArch64CCMP CMP;CCMP matching
1819 ///
1820 /// These functions deal with the formation of CMP;CCMP;... sequences.
1821 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1822 /// a comparison. They set the NZCV flags to a predefined value if their
1823 /// predicate is false. This allows to express arbitrary conjunctions, for
1824 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1825 /// expressed as:
1826 ///   cmp A
1827 ///   ccmp B, inv(CB), CA
1828 ///   check for CB flags
1829 ///
1830 /// This naturally lets us implement chains of AND operations with SETCC
1831 /// operands. And we can even implement some other situations by transforming
1832 /// them:
1833 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1834 ///     negating the flags used in a CCMP/FCCMP operations.
1835 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1836 ///     by negating the flags we test for afterwards. i.e.
1837 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1838 ///   - Note that we can only ever negate all previously processed results.
1839 ///     What we can not implement by flipping the flags to test is a negation
1840 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1841 ///     far, so the 2nd sub-tree we emit would also affect the first).
1842 /// With those tools we can implement some OR operations:
1843 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1844 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1845 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1846 ///     elimination rules from earlier to implement the whole thing as a
1847 ///     CCMP/FCCMP chain.
1848 ///
1849 /// As complete example:
1850 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1851 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1852 /// can be reassociated to:
1853 ///     or (and (setCC (cmp C)) setCD (cmp D))
1854 //         (or (setCA (cmp A)) (setCB (cmp B)))
1855 /// can be transformed to:
1856 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1857 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1858 /// which can be implemented as:
1859 ///   cmp C
1860 ///   ccmp D, inv(CD), CC
1861 ///   ccmp A, CA, inv(CD)
1862 ///   ccmp B, CB, inv(CA)
1863 ///   check for CB flags
1864 ///
1865 /// A counterexample is "or (and A B) (and C D)" which translates to
1866 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1867 /// can only implement 1 of the inner (not) operations, but not both!
1868 /// @{
1869 
1870 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1871 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1872                                          ISD::CondCode CC, SDValue CCOp,
1873                                          AArch64CC::CondCode Predicate,
1874                                          AArch64CC::CondCode OutCC,
1875                                          const SDLoc &DL, SelectionDAG &DAG) {
1876   unsigned Opcode = 0;
1877   const bool FullFP16 =
1878     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1879 
1880   if (LHS.getValueType().isFloatingPoint()) {
1881     assert(LHS.getValueType() != MVT::f128);
1882     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1883       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1884       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1885     }
1886     Opcode = AArch64ISD::FCCMP;
1887   } else if (RHS.getOpcode() == ISD::SUB) {
1888     SDValue SubOp0 = RHS.getOperand(0);
1889     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1890       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1891       Opcode = AArch64ISD::CCMN;
1892       RHS = RHS.getOperand(1);
1893     }
1894   }
1895   if (Opcode == 0)
1896     Opcode = AArch64ISD::CCMP;
1897 
1898   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1899   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1900   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1901   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1902   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1903 }
1904 
1905 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1906 /// expressed as a conjunction. See \ref AArch64CCMP.
1907 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1908 ///                     changing the conditions on the SETCC tests.
1909 ///                     (this means we can call emitConjunctionRec() with
1910 ///                      Negate==true on this sub-tree)
1911 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1912 ///                     cannot do the negation naturally. We are required to
1913 ///                     emit the subtree first in this case.
1914 /// \param WillNegate   Is true if are called when the result of this
1915 ///                     subexpression must be negated. This happens when the
1916 ///                     outer expression is an OR. We can use this fact to know
1917 ///                     that we have a double negation (or (or ...) ...) that
1918 ///                     can be implemented for free.
1919 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1920                                bool &MustBeFirst, bool WillNegate,
1921                                unsigned Depth = 0) {
1922   if (!Val.hasOneUse())
1923     return false;
1924   unsigned Opcode = Val->getOpcode();
1925   if (Opcode == ISD::SETCC) {
1926     if (Val->getOperand(0).getValueType() == MVT::f128)
1927       return false;
1928     CanNegate = true;
1929     MustBeFirst = false;
1930     return true;
1931   }
1932   // Protect against exponential runtime and stack overflow.
1933   if (Depth > 6)
1934     return false;
1935   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1936     bool IsOR = Opcode == ISD::OR;
1937     SDValue O0 = Val->getOperand(0);
1938     SDValue O1 = Val->getOperand(1);
1939     bool CanNegateL;
1940     bool MustBeFirstL;
1941     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1942       return false;
1943     bool CanNegateR;
1944     bool MustBeFirstR;
1945     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1946       return false;
1947 
1948     if (MustBeFirstL && MustBeFirstR)
1949       return false;
1950 
1951     if (IsOR) {
1952       // For an OR expression we need to be able to naturally negate at least
1953       // one side or we cannot do the transformation at all.
1954       if (!CanNegateL && !CanNegateR)
1955         return false;
1956       // If we the result of the OR will be negated and we can naturally negate
1957       // the leafs, then this sub-tree as a whole negates naturally.
1958       CanNegate = WillNegate && CanNegateL && CanNegateR;
1959       // If we cannot naturally negate the whole sub-tree, then this must be
1960       // emitted first.
1961       MustBeFirst = !CanNegate;
1962     } else {
1963       assert(Opcode == ISD::AND && "Must be OR or AND");
1964       // We cannot naturally negate an AND operation.
1965       CanNegate = false;
1966       MustBeFirst = MustBeFirstL || MustBeFirstR;
1967     }
1968     return true;
1969   }
1970   return false;
1971 }
1972 
1973 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1974 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1975 /// Tries to transform the given i1 producing node @p Val to a series compare
1976 /// and conditional compare operations. @returns an NZCV flags producing node
1977 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1978 /// transformation was not possible.
1979 /// \p Negate is true if we want this sub-tree being negated just by changing
1980 /// SETCC conditions.
1981 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1982     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1983     AArch64CC::CondCode Predicate) {
1984   // We're at a tree leaf, produce a conditional comparison operation.
1985   unsigned Opcode = Val->getOpcode();
1986   if (Opcode == ISD::SETCC) {
1987     SDValue LHS = Val->getOperand(0);
1988     SDValue RHS = Val->getOperand(1);
1989     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1990     bool isInteger = LHS.getValueType().isInteger();
1991     if (Negate)
1992       CC = getSetCCInverse(CC, LHS.getValueType());
1993     SDLoc DL(Val);
1994     // Determine OutCC and handle FP special case.
1995     if (isInteger) {
1996       OutCC = changeIntCCToAArch64CC(CC);
1997     } else {
1998       assert(LHS.getValueType().isFloatingPoint());
1999       AArch64CC::CondCode ExtraCC;
2000       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2001       // Some floating point conditions can't be tested with a single condition
2002       // code. Construct an additional comparison in this case.
2003       if (ExtraCC != AArch64CC::AL) {
2004         SDValue ExtraCmp;
2005         if (!CCOp.getNode())
2006           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2007         else
2008           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2009                                                ExtraCC, DL, DAG);
2010         CCOp = ExtraCmp;
2011         Predicate = ExtraCC;
2012       }
2013     }
2014 
2015     // Produce a normal comparison if we are first in the chain
2016     if (!CCOp)
2017       return emitComparison(LHS, RHS, CC, DL, DAG);
2018     // Otherwise produce a ccmp.
2019     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2020                                      DAG);
2021   }
2022   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2023 
2024   bool IsOR = Opcode == ISD::OR;
2025 
2026   SDValue LHS = Val->getOperand(0);
2027   bool CanNegateL;
2028   bool MustBeFirstL;
2029   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2030   assert(ValidL && "Valid conjunction/disjunction tree");
2031   (void)ValidL;
2032 
2033   SDValue RHS = Val->getOperand(1);
2034   bool CanNegateR;
2035   bool MustBeFirstR;
2036   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2037   assert(ValidR && "Valid conjunction/disjunction tree");
2038   (void)ValidR;
2039 
2040   // Swap sub-tree that must come first to the right side.
2041   if (MustBeFirstL) {
2042     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2043     std::swap(LHS, RHS);
2044     std::swap(CanNegateL, CanNegateR);
2045     std::swap(MustBeFirstL, MustBeFirstR);
2046   }
2047 
2048   bool NegateR;
2049   bool NegateAfterR;
2050   bool NegateL;
2051   bool NegateAfterAll;
2052   if (Opcode == ISD::OR) {
2053     // Swap the sub-tree that we can negate naturally to the left.
2054     if (!CanNegateL) {
2055       assert(CanNegateR && "at least one side must be negatable");
2056       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2057       assert(!Negate);
2058       std::swap(LHS, RHS);
2059       NegateR = false;
2060       NegateAfterR = true;
2061     } else {
2062       // Negate the left sub-tree if possible, otherwise negate the result.
2063       NegateR = CanNegateR;
2064       NegateAfterR = !CanNegateR;
2065     }
2066     NegateL = true;
2067     NegateAfterAll = !Negate;
2068   } else {
2069     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2070     assert(!Negate && "Valid conjunction/disjunction tree");
2071 
2072     NegateL = false;
2073     NegateR = false;
2074     NegateAfterR = false;
2075     NegateAfterAll = false;
2076   }
2077 
2078   // Emit sub-trees.
2079   AArch64CC::CondCode RHSCC;
2080   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2081   if (NegateAfterR)
2082     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2083   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2084   if (NegateAfterAll)
2085     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2086   return CmpL;
2087 }
2088 
2089 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2090 /// In some cases this is even possible with OR operations in the expression.
2091 /// See \ref AArch64CCMP.
2092 /// \see emitConjunctionRec().
2093 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2094                                AArch64CC::CondCode &OutCC) {
2095   bool DummyCanNegate;
2096   bool DummyMustBeFirst;
2097   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2098     return SDValue();
2099 
2100   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2101 }
2102 
2103 /// @}
2104 
2105 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2106 /// extension operations.
2107 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2108   auto isSupportedExtend = [&](SDValue V) {
2109     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2110       return true;
2111 
2112     if (V.getOpcode() == ISD::AND)
2113       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2114         uint64_t Mask = MaskCst->getZExtValue();
2115         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2116       }
2117 
2118     return false;
2119   };
2120 
2121   if (!Op.hasOneUse())
2122     return 0;
2123 
2124   if (isSupportedExtend(Op))
2125     return 1;
2126 
2127   unsigned Opc = Op.getOpcode();
2128   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2129     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2130       uint64_t Shift = ShiftCst->getZExtValue();
2131       if (isSupportedExtend(Op.getOperand(0)))
2132         return (Shift <= 4) ? 2 : 1;
2133       EVT VT = Op.getValueType();
2134       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2135         return 1;
2136     }
2137 
2138   return 0;
2139 }
2140 
2141 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2142                              SDValue &AArch64cc, SelectionDAG &DAG,
2143                              const SDLoc &dl) {
2144   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2145     EVT VT = RHS.getValueType();
2146     uint64_t C = RHSC->getZExtValue();
2147     if (!isLegalArithImmed(C)) {
2148       // Constant does not fit, try adjusting it by one?
2149       switch (CC) {
2150       default:
2151         break;
2152       case ISD::SETLT:
2153       case ISD::SETGE:
2154         if ((VT == MVT::i32 && C != 0x80000000 &&
2155              isLegalArithImmed((uint32_t)(C - 1))) ||
2156             (VT == MVT::i64 && C != 0x80000000ULL &&
2157              isLegalArithImmed(C - 1ULL))) {
2158           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2159           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2160           RHS = DAG.getConstant(C, dl, VT);
2161         }
2162         break;
2163       case ISD::SETULT:
2164       case ISD::SETUGE:
2165         if ((VT == MVT::i32 && C != 0 &&
2166              isLegalArithImmed((uint32_t)(C - 1))) ||
2167             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2168           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2169           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2170           RHS = DAG.getConstant(C, dl, VT);
2171         }
2172         break;
2173       case ISD::SETLE:
2174       case ISD::SETGT:
2175         if ((VT == MVT::i32 && C != INT32_MAX &&
2176              isLegalArithImmed((uint32_t)(C + 1))) ||
2177             (VT == MVT::i64 && C != INT64_MAX &&
2178              isLegalArithImmed(C + 1ULL))) {
2179           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2180           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2181           RHS = DAG.getConstant(C, dl, VT);
2182         }
2183         break;
2184       case ISD::SETULE:
2185       case ISD::SETUGT:
2186         if ((VT == MVT::i32 && C != UINT32_MAX &&
2187              isLegalArithImmed((uint32_t)(C + 1))) ||
2188             (VT == MVT::i64 && C != UINT64_MAX &&
2189              isLegalArithImmed(C + 1ULL))) {
2190           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2191           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2192           RHS = DAG.getConstant(C, dl, VT);
2193         }
2194         break;
2195       }
2196     }
2197   }
2198 
2199   // Comparisons are canonicalized so that the RHS operand is simpler than the
2200   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2201   // can fold some shift+extend operations on the RHS operand, so swap the
2202   // operands if that can be done.
2203   //
2204   // For example:
2205   //    lsl     w13, w11, #1
2206   //    cmp     w13, w12
2207   // can be turned into:
2208   //    cmp     w12, w11, lsl #1
2209   if (!isa<ConstantSDNode>(RHS) ||
2210       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2211     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2212 
2213     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2214       std::swap(LHS, RHS);
2215       CC = ISD::getSetCCSwappedOperands(CC);
2216     }
2217   }
2218 
2219   SDValue Cmp;
2220   AArch64CC::CondCode AArch64CC;
2221   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2222     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2223 
2224     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2225     // For the i8 operand, the largest immediate is 255, so this can be easily
2226     // encoded in the compare instruction. For the i16 operand, however, the
2227     // largest immediate cannot be encoded in the compare.
2228     // Therefore, use a sign extending load and cmn to avoid materializing the
2229     // -1 constant. For example,
2230     // movz w1, #65535
2231     // ldrh w0, [x0, #0]
2232     // cmp w0, w1
2233     // >
2234     // ldrsh w0, [x0, #0]
2235     // cmn w0, #1
2236     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2237     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2238     // ensure both the LHS and RHS are truly zero extended and to make sure the
2239     // transformation is profitable.
2240     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2241         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2242         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2243         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2244       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2245       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2246         SDValue SExt =
2247             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2248                         DAG.getValueType(MVT::i16));
2249         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2250                                                    RHS.getValueType()),
2251                              CC, dl, DAG);
2252         AArch64CC = changeIntCCToAArch64CC(CC);
2253       }
2254     }
2255 
2256     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2257       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2258         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2259           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2260       }
2261     }
2262   }
2263 
2264   if (!Cmp) {
2265     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2266     AArch64CC = changeIntCCToAArch64CC(CC);
2267   }
2268   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2269   return Cmp;
2270 }
2271 
2272 static std::pair<SDValue, SDValue>
2273 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2274   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2275          "Unsupported value type");
2276   SDValue Value, Overflow;
2277   SDLoc DL(Op);
2278   SDValue LHS = Op.getOperand(0);
2279   SDValue RHS = Op.getOperand(1);
2280   unsigned Opc = 0;
2281   switch (Op.getOpcode()) {
2282   default:
2283     llvm_unreachable("Unknown overflow instruction!");
2284   case ISD::SADDO:
2285     Opc = AArch64ISD::ADDS;
2286     CC = AArch64CC::VS;
2287     break;
2288   case ISD::UADDO:
2289     Opc = AArch64ISD::ADDS;
2290     CC = AArch64CC::HS;
2291     break;
2292   case ISD::SSUBO:
2293     Opc = AArch64ISD::SUBS;
2294     CC = AArch64CC::VS;
2295     break;
2296   case ISD::USUBO:
2297     Opc = AArch64ISD::SUBS;
2298     CC = AArch64CC::LO;
2299     break;
2300   // Multiply needs a little bit extra work.
2301   case ISD::SMULO:
2302   case ISD::UMULO: {
2303     CC = AArch64CC::NE;
2304     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2305     if (Op.getValueType() == MVT::i32) {
2306       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2307       // For a 32 bit multiply with overflow check we want the instruction
2308       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2309       // need to generate the following pattern:
2310       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2311       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2312       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2313       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2314       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2315                                 DAG.getConstant(0, DL, MVT::i64));
2316       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2317       // operation. We need to clear out the upper 32 bits, because we used a
2318       // widening multiply that wrote all 64 bits. In the end this should be a
2319       // noop.
2320       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2321       if (IsSigned) {
2322         // The signed overflow check requires more than just a simple check for
2323         // any bit set in the upper 32 bits of the result. These bits could be
2324         // just the sign bits of a negative number. To perform the overflow
2325         // check we have to arithmetic shift right the 32nd bit of the result by
2326         // 31 bits. Then we compare the result to the upper 32 bits.
2327         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2328                                         DAG.getConstant(32, DL, MVT::i64));
2329         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2330         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2331                                         DAG.getConstant(31, DL, MVT::i64));
2332         // It is important that LowerBits is last, otherwise the arithmetic
2333         // shift will not be folded into the compare (SUBS).
2334         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2335         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2336                        .getValue(1);
2337       } else {
2338         // The overflow check for unsigned multiply is easy. We only need to
2339         // check if any of the upper 32 bits are set. This can be done with a
2340         // CMP (shifted register). For that we need to generate the following
2341         // pattern:
2342         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2343         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2344                                         DAG.getConstant(32, DL, MVT::i64));
2345         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2346         Overflow =
2347             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2348                         DAG.getConstant(0, DL, MVT::i64),
2349                         UpperBits).getValue(1);
2350       }
2351       break;
2352     }
2353     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2354     // For the 64 bit multiply
2355     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2356     if (IsSigned) {
2357       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2358       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2359                                       DAG.getConstant(63, DL, MVT::i64));
2360       // It is important that LowerBits is last, otherwise the arithmetic
2361       // shift will not be folded into the compare (SUBS).
2362       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2363       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2364                      .getValue(1);
2365     } else {
2366       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2367       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2368       Overflow =
2369           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2370                       DAG.getConstant(0, DL, MVT::i64),
2371                       UpperBits).getValue(1);
2372     }
2373     break;
2374   }
2375   } // switch (...)
2376 
2377   if (Opc) {
2378     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2379 
2380     // Emit the AArch64 operation with overflow check.
2381     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2382     Overflow = Value.getValue(1);
2383   }
2384   return std::make_pair(Value, Overflow);
2385 }
2386 
2387 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2388                                              RTLIB::Libcall Call) const {
2389   bool IsStrict = Op->isStrictFPOpcode();
2390   unsigned Offset = IsStrict ? 1 : 0;
2391   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2392   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2393   MakeLibCallOptions CallOptions;
2394   SDValue Result;
2395   SDLoc dl(Op);
2396   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2397                                         CallOptions, dl, Chain);
2398   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2399 }
2400 
2401 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2402   SDValue Sel = Op.getOperand(0);
2403   SDValue Other = Op.getOperand(1);
2404   SDLoc dl(Sel);
2405 
2406   // If the operand is an overflow checking operation, invert the condition
2407   // code and kill the Not operation. I.e., transform:
2408   // (xor (overflow_op_bool, 1))
2409   //   -->
2410   // (csel 1, 0, invert(cc), overflow_op_bool)
2411   // ... which later gets transformed to just a cset instruction with an
2412   // inverted condition code, rather than a cset + eor sequence.
2413   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2414     // Only lower legal XALUO ops.
2415     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2416       return SDValue();
2417 
2418     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2419     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2420     AArch64CC::CondCode CC;
2421     SDValue Value, Overflow;
2422     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2423     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2424     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2425                        CCVal, Overflow);
2426   }
2427   // If neither operand is a SELECT_CC, give up.
2428   if (Sel.getOpcode() != ISD::SELECT_CC)
2429     std::swap(Sel, Other);
2430   if (Sel.getOpcode() != ISD::SELECT_CC)
2431     return Op;
2432 
2433   // The folding we want to perform is:
2434   // (xor x, (select_cc a, b, cc, 0, -1) )
2435   //   -->
2436   // (csel x, (xor x, -1), cc ...)
2437   //
2438   // The latter will get matched to a CSINV instruction.
2439 
2440   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2441   SDValue LHS = Sel.getOperand(0);
2442   SDValue RHS = Sel.getOperand(1);
2443   SDValue TVal = Sel.getOperand(2);
2444   SDValue FVal = Sel.getOperand(3);
2445 
2446   // FIXME: This could be generalized to non-integer comparisons.
2447   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2448     return Op;
2449 
2450   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2451   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2452 
2453   // The values aren't constants, this isn't the pattern we're looking for.
2454   if (!CFVal || !CTVal)
2455     return Op;
2456 
2457   // We can commute the SELECT_CC by inverting the condition.  This
2458   // might be needed to make this fit into a CSINV pattern.
2459   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2460     std::swap(TVal, FVal);
2461     std::swap(CTVal, CFVal);
2462     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2463   }
2464 
2465   // If the constants line up, perform the transform!
2466   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2467     SDValue CCVal;
2468     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2469 
2470     FVal = Other;
2471     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2472                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2473 
2474     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2475                        CCVal, Cmp);
2476   }
2477 
2478   return Op;
2479 }
2480 
2481 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2482   EVT VT = Op.getValueType();
2483 
2484   // Let legalize expand this if it isn't a legal type yet.
2485   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2486     return SDValue();
2487 
2488   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2489 
2490   unsigned Opc;
2491   bool ExtraOp = false;
2492   switch (Op.getOpcode()) {
2493   default:
2494     llvm_unreachable("Invalid code");
2495   case ISD::ADDC:
2496     Opc = AArch64ISD::ADDS;
2497     break;
2498   case ISD::SUBC:
2499     Opc = AArch64ISD::SUBS;
2500     break;
2501   case ISD::ADDE:
2502     Opc = AArch64ISD::ADCS;
2503     ExtraOp = true;
2504     break;
2505   case ISD::SUBE:
2506     Opc = AArch64ISD::SBCS;
2507     ExtraOp = true;
2508     break;
2509   }
2510 
2511   if (!ExtraOp)
2512     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2513   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2514                      Op.getOperand(2));
2515 }
2516 
2517 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2518   // Let legalize expand this if it isn't a legal type yet.
2519   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2520     return SDValue();
2521 
2522   SDLoc dl(Op);
2523   AArch64CC::CondCode CC;
2524   // The actual operation that sets the overflow or carry flag.
2525   SDValue Value, Overflow;
2526   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2527 
2528   // We use 0 and 1 as false and true values.
2529   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2530   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2531 
2532   // We use an inverted condition, because the conditional select is inverted
2533   // too. This will allow it to be selected to a single instruction:
2534   // CSINC Wd, WZR, WZR, invert(cond).
2535   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2536   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2537                          CCVal, Overflow);
2538 
2539   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2540   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2541 }
2542 
2543 // Prefetch operands are:
2544 // 1: Address to prefetch
2545 // 2: bool isWrite
2546 // 3: int locality (0 = no locality ... 3 = extreme locality)
2547 // 4: bool isDataCache
2548 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2549   SDLoc DL(Op);
2550   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2551   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2552   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2553 
2554   bool IsStream = !Locality;
2555   // When the locality number is set
2556   if (Locality) {
2557     // The front-end should have filtered out the out-of-range values
2558     assert(Locality <= 3 && "Prefetch locality out-of-range");
2559     // The locality degree is the opposite of the cache speed.
2560     // Put the number the other way around.
2561     // The encoding starts at 0 for level 1
2562     Locality = 3 - Locality;
2563   }
2564 
2565   // built the mask value encoding the expected behavior.
2566   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2567                    (!IsData << 3) |     // IsDataCache bit
2568                    (Locality << 1) |    // Cache level bits
2569                    (unsigned)IsStream;  // Stream bit
2570   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2571                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2572 }
2573 
2574 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2575                                               SelectionDAG &DAG) const {
2576   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2577 
2578   RTLIB::Libcall LC;
2579   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2580 
2581   return LowerF128Call(Op, DAG, LC);
2582 }
2583 
2584 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2585                                              SelectionDAG &DAG) const {
2586   bool IsStrict = Op->isStrictFPOpcode();
2587   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2588   if (SrcVal.getValueType() != MVT::f128) {
2589     // It's legal except when f128 is involved
2590     return Op;
2591   }
2592 
2593   RTLIB::Libcall LC;
2594   LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType());
2595 
2596   // FP_ROUND node has a second operand indicating whether it is known to be
2597   // precise. That doesn't take part in the LibCall so we can't directly use
2598   // LowerF128Call.
2599   MakeLibCallOptions CallOptions;
2600   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2601   SDValue Result;
2602   SDLoc dl(Op);
2603   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2604                                         CallOptions, dl, Chain);
2605   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2606 }
2607 
2608 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2609                                                     SelectionDAG &DAG) const {
2610   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2611   // Any additional optimization in this function should be recorded
2612   // in the cost tables.
2613   EVT InVT = Op.getOperand(0).getValueType();
2614   EVT VT = Op.getValueType();
2615   unsigned NumElts = InVT.getVectorNumElements();
2616 
2617   // f16 conversions are promoted to f32 when full fp16 is not supported.
2618   if (InVT.getVectorElementType() == MVT::f16 &&
2619       !Subtarget->hasFullFP16()) {
2620     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2621     SDLoc dl(Op);
2622     return DAG.getNode(
2623         Op.getOpcode(), dl, Op.getValueType(),
2624         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2625   }
2626 
2627   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2628     SDLoc dl(Op);
2629     SDValue Cv =
2630         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2631                     Op.getOperand(0));
2632     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2633   }
2634 
2635   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2636     SDLoc dl(Op);
2637     MVT ExtVT =
2638         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2639                          VT.getVectorNumElements());
2640     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2641     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2642   }
2643 
2644   // Type changing conversions are illegal.
2645   return Op;
2646 }
2647 
2648 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2649                                               SelectionDAG &DAG) const {
2650   bool IsStrict = Op->isStrictFPOpcode();
2651   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2652 
2653   if (SrcVal.getValueType().isVector())
2654     return LowerVectorFP_TO_INT(Op, DAG);
2655 
2656   // f16 conversions are promoted to f32 when full fp16 is not supported.
2657   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2658     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2659     SDLoc dl(Op);
2660     return DAG.getNode(
2661         Op.getOpcode(), dl, Op.getValueType(),
2662         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2663   }
2664 
2665   if (SrcVal.getValueType() != MVT::f128) {
2666     // It's legal except when f128 is involved
2667     return Op;
2668   }
2669 
2670   RTLIB::Libcall LC;
2671   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2672       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2673     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2674   else
2675     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2676 
2677   return LowerF128Call(Op, DAG, LC);
2678 }
2679 
2680 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2681   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2682   // Any additional optimization in this function should be recorded
2683   // in the cost tables.
2684   EVT VT = Op.getValueType();
2685   SDLoc dl(Op);
2686   SDValue In = Op.getOperand(0);
2687   EVT InVT = In.getValueType();
2688 
2689   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2690     MVT CastVT =
2691         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2692                          InVT.getVectorNumElements());
2693     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2694     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2695   }
2696 
2697   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2698     unsigned CastOpc =
2699         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2700     EVT CastVT = VT.changeVectorElementTypeToInteger();
2701     In = DAG.getNode(CastOpc, dl, CastVT, In);
2702     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2703   }
2704 
2705   return Op;
2706 }
2707 
2708 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2709                                             SelectionDAG &DAG) const {
2710   if (Op.getValueType().isVector())
2711     return LowerVectorINT_TO_FP(Op, DAG);
2712 
2713   bool IsStrict = Op->isStrictFPOpcode();
2714   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2715 
2716   // f16 conversions are promoted to f32 when full fp16 is not supported.
2717   if (Op.getValueType() == MVT::f16 &&
2718       !Subtarget->hasFullFP16()) {
2719     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2720     SDLoc dl(Op);
2721     return DAG.getNode(
2722         ISD::FP_ROUND, dl, MVT::f16,
2723         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2724         DAG.getIntPtrConstant(0, dl));
2725   }
2726 
2727   // i128 conversions are libcalls.
2728   if (SrcVal.getValueType() == MVT::i128)
2729     return SDValue();
2730 
2731   // Other conversions are legal, unless it's to the completely software-based
2732   // fp128.
2733   if (Op.getValueType() != MVT::f128)
2734     return Op;
2735 
2736   RTLIB::Libcall LC;
2737   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2738       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2739     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2740   else
2741     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2742 
2743   return LowerF128Call(Op, DAG, LC);
2744 }
2745 
2746 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2747                                             SelectionDAG &DAG) const {
2748   // For iOS, we want to call an alternative entry point: __sincos_stret,
2749   // which returns the values in two S / D registers.
2750   SDLoc dl(Op);
2751   SDValue Arg = Op.getOperand(0);
2752   EVT ArgVT = Arg.getValueType();
2753   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2754 
2755   ArgListTy Args;
2756   ArgListEntry Entry;
2757 
2758   Entry.Node = Arg;
2759   Entry.Ty = ArgTy;
2760   Entry.IsSExt = false;
2761   Entry.IsZExt = false;
2762   Args.push_back(Entry);
2763 
2764   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2765                                         : RTLIB::SINCOS_STRET_F32;
2766   const char *LibcallName = getLibcallName(LC);
2767   SDValue Callee =
2768       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2769 
2770   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2771   TargetLowering::CallLoweringInfo CLI(DAG);
2772   CLI.setDebugLoc(dl)
2773       .setChain(DAG.getEntryNode())
2774       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2775 
2776   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2777   return CallResult.first;
2778 }
2779 
2780 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2781   if (Op.getValueType() != MVT::f16)
2782     return SDValue();
2783 
2784   assert(Op.getOperand(0).getValueType() == MVT::i16);
2785   SDLoc DL(Op);
2786 
2787   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2788   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2789   return SDValue(
2790       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2791                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2792       0);
2793 }
2794 
2795 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2796   if (OrigVT.getSizeInBits() >= 64)
2797     return OrigVT;
2798 
2799   assert(OrigVT.isSimple() && "Expecting a simple value type");
2800 
2801   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2802   switch (OrigSimpleTy) {
2803   default: llvm_unreachable("Unexpected Vector Type");
2804   case MVT::v2i8:
2805   case MVT::v2i16:
2806      return MVT::v2i32;
2807   case MVT::v4i8:
2808     return  MVT::v4i16;
2809   }
2810 }
2811 
2812 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2813                                                  const EVT &OrigTy,
2814                                                  const EVT &ExtTy,
2815                                                  unsigned ExtOpcode) {
2816   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2817   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2818   // 64-bits we need to insert a new extension so that it will be 64-bits.
2819   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2820   if (OrigTy.getSizeInBits() >= 64)
2821     return N;
2822 
2823   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2824   EVT NewVT = getExtensionTo64Bits(OrigTy);
2825 
2826   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2827 }
2828 
2829 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2830                                    bool isSigned) {
2831   EVT VT = N->getValueType(0);
2832 
2833   if (N->getOpcode() != ISD::BUILD_VECTOR)
2834     return false;
2835 
2836   for (const SDValue &Elt : N->op_values()) {
2837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2838       unsigned EltSize = VT.getScalarSizeInBits();
2839       unsigned HalfSize = EltSize / 2;
2840       if (isSigned) {
2841         if (!isIntN(HalfSize, C->getSExtValue()))
2842           return false;
2843       } else {
2844         if (!isUIntN(HalfSize, C->getZExtValue()))
2845           return false;
2846       }
2847       continue;
2848     }
2849     return false;
2850   }
2851 
2852   return true;
2853 }
2854 
2855 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2856   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2857     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2858                                              N->getOperand(0)->getValueType(0),
2859                                              N->getValueType(0),
2860                                              N->getOpcode());
2861 
2862   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2863   EVT VT = N->getValueType(0);
2864   SDLoc dl(N);
2865   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2866   unsigned NumElts = VT.getVectorNumElements();
2867   MVT TruncVT = MVT::getIntegerVT(EltSize);
2868   SmallVector<SDValue, 8> Ops;
2869   for (unsigned i = 0; i != NumElts; ++i) {
2870     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2871     const APInt &CInt = C->getAPIntValue();
2872     // Element types smaller than 32 bits are not legal, so use i32 elements.
2873     // The values are implicitly truncated so sext vs. zext doesn't matter.
2874     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2875   }
2876   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2877 }
2878 
2879 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2880   return N->getOpcode() == ISD::SIGN_EXTEND ||
2881          isExtendedBUILD_VECTOR(N, DAG, true);
2882 }
2883 
2884 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2885   return N->getOpcode() == ISD::ZERO_EXTEND ||
2886          isExtendedBUILD_VECTOR(N, DAG, false);
2887 }
2888 
2889 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2890   unsigned Opcode = N->getOpcode();
2891   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2892     SDNode *N0 = N->getOperand(0).getNode();
2893     SDNode *N1 = N->getOperand(1).getNode();
2894     return N0->hasOneUse() && N1->hasOneUse() &&
2895       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2896   }
2897   return false;
2898 }
2899 
2900 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2901   unsigned Opcode = N->getOpcode();
2902   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2903     SDNode *N0 = N->getOperand(0).getNode();
2904     SDNode *N1 = N->getOperand(1).getNode();
2905     return N0->hasOneUse() && N1->hasOneUse() &&
2906       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2907   }
2908   return false;
2909 }
2910 
2911 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2912                                                 SelectionDAG &DAG) const {
2913   // The rounding mode is in bits 23:22 of the FPSCR.
2914   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2915   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2916   // so that the shift + and get folded into a bitfield extract.
2917   SDLoc dl(Op);
2918 
2919   SDValue Chain = Op.getOperand(0);
2920   SDValue FPCR_64 = DAG.getNode(
2921       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
2922       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
2923   Chain = FPCR_64.getValue(1);
2924   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2925   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2926                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2927   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2928                               DAG.getConstant(22, dl, MVT::i32));
2929   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2930                             DAG.getConstant(3, dl, MVT::i32));
2931   return DAG.getMergeValues({AND, Chain}, dl);
2932 }
2933 
2934 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2935   // Multiplications are only custom-lowered for 128-bit vectors so that
2936   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2937   EVT VT = Op.getValueType();
2938   assert(VT.is128BitVector() && VT.isInteger() &&
2939          "unexpected type for custom-lowering ISD::MUL");
2940   SDNode *N0 = Op.getOperand(0).getNode();
2941   SDNode *N1 = Op.getOperand(1).getNode();
2942   unsigned NewOpc = 0;
2943   bool isMLA = false;
2944   bool isN0SExt = isSignExtended(N0, DAG);
2945   bool isN1SExt = isSignExtended(N1, DAG);
2946   if (isN0SExt && isN1SExt)
2947     NewOpc = AArch64ISD::SMULL;
2948   else {
2949     bool isN0ZExt = isZeroExtended(N0, DAG);
2950     bool isN1ZExt = isZeroExtended(N1, DAG);
2951     if (isN0ZExt && isN1ZExt)
2952       NewOpc = AArch64ISD::UMULL;
2953     else if (isN1SExt || isN1ZExt) {
2954       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2955       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2956       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2957         NewOpc = AArch64ISD::SMULL;
2958         isMLA = true;
2959       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2960         NewOpc =  AArch64ISD::UMULL;
2961         isMLA = true;
2962       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2963         std::swap(N0, N1);
2964         NewOpc =  AArch64ISD::UMULL;
2965         isMLA = true;
2966       }
2967     }
2968 
2969     if (!NewOpc) {
2970       if (VT == MVT::v2i64)
2971         // Fall through to expand this.  It is not legal.
2972         return SDValue();
2973       else
2974         // Other vector multiplications are legal.
2975         return Op;
2976     }
2977   }
2978 
2979   // Legalize to a S/UMULL instruction
2980   SDLoc DL(Op);
2981   SDValue Op0;
2982   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2983   if (!isMLA) {
2984     Op0 = skipExtensionForVectorMULL(N0, DAG);
2985     assert(Op0.getValueType().is64BitVector() &&
2986            Op1.getValueType().is64BitVector() &&
2987            "unexpected types for extended operands to VMULL");
2988     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2989   }
2990   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2991   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2992   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2993   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2994   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2995   EVT Op1VT = Op1.getValueType();
2996   return DAG.getNode(N0->getOpcode(), DL, VT,
2997                      DAG.getNode(NewOpc, DL, VT,
2998                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2999                      DAG.getNode(NewOpc, DL, VT,
3000                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3001 }
3002 
3003 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3004                                int Pattern) {
3005   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3006                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3007 }
3008 
3009 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3010                                                      SelectionDAG &DAG) const {
3011   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3012   SDLoc dl(Op);
3013   switch (IntNo) {
3014   default: return SDValue();    // Don't custom lower most intrinsics.
3015   case Intrinsic::thread_pointer: {
3016     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3017     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3018   }
3019   case Intrinsic::aarch64_neon_abs: {
3020     EVT Ty = Op.getValueType();
3021     if (Ty == MVT::i64) {
3022       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3023                                    Op.getOperand(1));
3024       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3025       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3026     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3027       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3028     } else {
3029       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3030     }
3031   }
3032   case Intrinsic::aarch64_neon_smax:
3033     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3034                        Op.getOperand(1), Op.getOperand(2));
3035   case Intrinsic::aarch64_neon_umax:
3036     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3037                        Op.getOperand(1), Op.getOperand(2));
3038   case Intrinsic::aarch64_neon_smin:
3039     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3040                        Op.getOperand(1), Op.getOperand(2));
3041   case Intrinsic::aarch64_neon_umin:
3042     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3043                        Op.getOperand(1), Op.getOperand(2));
3044 
3045   case Intrinsic::aarch64_sve_sunpkhi:
3046     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3047                        Op.getOperand(1));
3048   case Intrinsic::aarch64_sve_sunpklo:
3049     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3050                        Op.getOperand(1));
3051   case Intrinsic::aarch64_sve_uunpkhi:
3052     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3053                        Op.getOperand(1));
3054   case Intrinsic::aarch64_sve_uunpklo:
3055     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3056                        Op.getOperand(1));
3057   case Intrinsic::aarch64_sve_clasta_n:
3058     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3059                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3060   case Intrinsic::aarch64_sve_clastb_n:
3061     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3062                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3063   case Intrinsic::aarch64_sve_lasta:
3064     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3065                        Op.getOperand(1), Op.getOperand(2));
3066   case Intrinsic::aarch64_sve_lastb:
3067     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3068                        Op.getOperand(1), Op.getOperand(2));
3069   case Intrinsic::aarch64_sve_rev:
3070     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3071                        Op.getOperand(1));
3072   case Intrinsic::aarch64_sve_tbl:
3073     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3074                        Op.getOperand(1), Op.getOperand(2));
3075   case Intrinsic::aarch64_sve_trn1:
3076     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3077                        Op.getOperand(1), Op.getOperand(2));
3078   case Intrinsic::aarch64_sve_trn2:
3079     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3080                        Op.getOperand(1), Op.getOperand(2));
3081   case Intrinsic::aarch64_sve_uzp1:
3082     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3083                        Op.getOperand(1), Op.getOperand(2));
3084   case Intrinsic::aarch64_sve_uzp2:
3085     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3086                        Op.getOperand(1), Op.getOperand(2));
3087   case Intrinsic::aarch64_sve_zip1:
3088     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3089                        Op.getOperand(1), Op.getOperand(2));
3090   case Intrinsic::aarch64_sve_zip2:
3091     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3092                        Op.getOperand(1), Op.getOperand(2));
3093   case Intrinsic::aarch64_sve_ptrue:
3094     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3095                        Op.getOperand(1));
3096   case Intrinsic::aarch64_sve_dupq_lane:
3097     return LowerDUPQLane(Op, DAG);
3098   case Intrinsic::aarch64_sve_convert_from_svbool:
3099     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3100                        Op.getOperand(1));
3101   case Intrinsic::aarch64_sve_convert_to_svbool: {
3102     EVT OutVT = Op.getValueType();
3103     EVT InVT = Op.getOperand(1).getValueType();
3104     // Return the operand if the cast isn't changing type,
3105     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3106     if (InVT == OutVT)
3107       return Op.getOperand(1);
3108     // Otherwise, zero the newly introduced lanes.
3109     SDValue Reinterpret =
3110         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3111     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3112     SDValue MaskReinterpret =
3113         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3114     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3115   }
3116 
3117   case Intrinsic::aarch64_sve_insr: {
3118     SDValue Scalar = Op.getOperand(2);
3119     EVT ScalarTy = Scalar.getValueType();
3120     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3121       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3122 
3123     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3124                        Op.getOperand(1), Scalar);
3125   }
3126 
3127   case Intrinsic::localaddress: {
3128     const auto &MF = DAG.getMachineFunction();
3129     const auto *RegInfo = Subtarget->getRegisterInfo();
3130     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3131     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3132                               Op.getSimpleValueType());
3133   }
3134 
3135   case Intrinsic::eh_recoverfp: {
3136     // FIXME: This needs to be implemented to correctly handle highly aligned
3137     // stack objects. For now we simply return the incoming FP. Refer D53541
3138     // for more details.
3139     SDValue FnOp = Op.getOperand(1);
3140     SDValue IncomingFPOp = Op.getOperand(2);
3141     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3142     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3143     if (!Fn)
3144       report_fatal_error(
3145           "llvm.eh.recoverfp must take a function as the first argument");
3146     return IncomingFPOp;
3147   }
3148   }
3149 }
3150 
3151 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3152   return ExtVal.getValueType().isScalableVector();
3153 }
3154 
3155 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3156 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3157                                         EVT VT, EVT MemVT,
3158                                         SelectionDAG &DAG) {
3159   assert(VT.isVector() && "VT should be a vector type");
3160   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3161 
3162   SDValue Value = ST->getValue();
3163 
3164   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3165   // the word lane which represent the v4i8 subvector.  It optimizes the store
3166   // to:
3167   //
3168   //   xtn  v0.8b, v0.8h
3169   //   str  s0, [x0]
3170 
3171   SDValue Undef = DAG.getUNDEF(MVT::i16);
3172   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3173                                         {Undef, Undef, Undef, Undef});
3174 
3175   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3176                                  Value, UndefVec);
3177   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3178 
3179   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3180   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3181                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3182 
3183   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3184                       ST->getBasePtr(), ST->getMemOperand());
3185 }
3186 
3187 // Custom lowering for any store, vector or scalar and/or default or with
3188 // a truncate operations.  Currently only custom lower truncate operation
3189 // from vector v4i16 to v4i8 or volatile stores of i128.
3190 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3191                                           SelectionDAG &DAG) const {
3192   SDLoc Dl(Op);
3193   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3194   assert (StoreNode && "Can only custom lower store nodes");
3195 
3196   SDValue Value = StoreNode->getValue();
3197 
3198   EVT VT = Value.getValueType();
3199   EVT MemVT = StoreNode->getMemoryVT();
3200 
3201   if (VT.isVector()) {
3202     unsigned AS = StoreNode->getAddressSpace();
3203     unsigned Align = StoreNode->getAlignment();
3204     if (Align < MemVT.getStoreSize() &&
3205         !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3206                                         StoreNode->getMemOperand()->getFlags(),
3207                                         nullptr)) {
3208       return scalarizeVectorStore(StoreNode, DAG);
3209     }
3210 
3211     if (StoreNode->isTruncatingStore()) {
3212       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3213     }
3214     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3215     // the custom lowering, as there are no un-paired non-temporal stores and
3216     // legalization will break up 256 bit inputs.
3217     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3218         MemVT.getVectorElementCount().Min % 2u == 0 &&
3219         ((MemVT.getScalarSizeInBits() == 8u ||
3220           MemVT.getScalarSizeInBits() == 16u ||
3221           MemVT.getScalarSizeInBits() == 32u ||
3222           MemVT.getScalarSizeInBits() == 64u))) {
3223       SDValue Lo =
3224           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3225                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3226                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3227       SDValue Hi = DAG.getNode(
3228           ISD::EXTRACT_SUBVECTOR, Dl,
3229           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3230           StoreNode->getValue(),
3231           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3232       SDValue Result = DAG.getMemIntrinsicNode(
3233           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3234           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3235           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3236       return Result;
3237     }
3238   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3239     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3240     SDValue Lo =
3241         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3242                     DAG.getConstant(0, Dl, MVT::i64));
3243     SDValue Hi =
3244         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3245                     DAG.getConstant(1, Dl, MVT::i64));
3246     SDValue Result = DAG.getMemIntrinsicNode(
3247         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3248         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3249         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3250     return Result;
3251   }
3252 
3253   return SDValue();
3254 }
3255 
3256 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3257                                               SelectionDAG &DAG) const {
3258   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3259   LLVM_DEBUG(Op.dump());
3260 
3261   switch (Op.getOpcode()) {
3262   default:
3263     llvm_unreachable("unimplemented operand");
3264     return SDValue();
3265   case ISD::BITCAST:
3266     return LowerBITCAST(Op, DAG);
3267   case ISD::GlobalAddress:
3268     return LowerGlobalAddress(Op, DAG);
3269   case ISD::GlobalTLSAddress:
3270     return LowerGlobalTLSAddress(Op, DAG);
3271   case ISD::SETCC:
3272   case ISD::STRICT_FSETCC:
3273   case ISD::STRICT_FSETCCS:
3274     return LowerSETCC(Op, DAG);
3275   case ISD::BR_CC:
3276     return LowerBR_CC(Op, DAG);
3277   case ISD::SELECT:
3278     return LowerSELECT(Op, DAG);
3279   case ISD::SELECT_CC:
3280     return LowerSELECT_CC(Op, DAG);
3281   case ISD::JumpTable:
3282     return LowerJumpTable(Op, DAG);
3283   case ISD::BR_JT:
3284     return LowerBR_JT(Op, DAG);
3285   case ISD::ConstantPool:
3286     return LowerConstantPool(Op, DAG);
3287   case ISD::BlockAddress:
3288     return LowerBlockAddress(Op, DAG);
3289   case ISD::VASTART:
3290     return LowerVASTART(Op, DAG);
3291   case ISD::VACOPY:
3292     return LowerVACOPY(Op, DAG);
3293   case ISD::VAARG:
3294     return LowerVAARG(Op, DAG);
3295   case ISD::ADDC:
3296   case ISD::ADDE:
3297   case ISD::SUBC:
3298   case ISD::SUBE:
3299     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3300   case ISD::SADDO:
3301   case ISD::UADDO:
3302   case ISD::SSUBO:
3303   case ISD::USUBO:
3304   case ISD::SMULO:
3305   case ISD::UMULO:
3306     return LowerXALUO(Op, DAG);
3307   case ISD::FADD:
3308     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3309   case ISD::FSUB:
3310     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3311   case ISD::FMUL:
3312     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3313   case ISD::FDIV:
3314     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3315   case ISD::FP_ROUND:
3316   case ISD::STRICT_FP_ROUND:
3317     return LowerFP_ROUND(Op, DAG);
3318   case ISD::FP_EXTEND:
3319     return LowerFP_EXTEND(Op, DAG);
3320   case ISD::FRAMEADDR:
3321     return LowerFRAMEADDR(Op, DAG);
3322   case ISD::SPONENTRY:
3323     return LowerSPONENTRY(Op, DAG);
3324   case ISD::RETURNADDR:
3325     return LowerRETURNADDR(Op, DAG);
3326   case ISD::ADDROFRETURNADDR:
3327     return LowerADDROFRETURNADDR(Op, DAG);
3328   case ISD::INSERT_VECTOR_ELT:
3329     return LowerINSERT_VECTOR_ELT(Op, DAG);
3330   case ISD::EXTRACT_VECTOR_ELT:
3331     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3332   case ISD::BUILD_VECTOR:
3333     return LowerBUILD_VECTOR(Op, DAG);
3334   case ISD::VECTOR_SHUFFLE:
3335     return LowerVECTOR_SHUFFLE(Op, DAG);
3336   case ISD::SPLAT_VECTOR:
3337     return LowerSPLAT_VECTOR(Op, DAG);
3338   case ISD::EXTRACT_SUBVECTOR:
3339     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3340   case ISD::SRA:
3341   case ISD::SRL:
3342   case ISD::SHL:
3343     return LowerVectorSRA_SRL_SHL(Op, DAG);
3344   case ISD::SHL_PARTS:
3345     return LowerShiftLeftParts(Op, DAG);
3346   case ISD::SRL_PARTS:
3347   case ISD::SRA_PARTS:
3348     return LowerShiftRightParts(Op, DAG);
3349   case ISD::CTPOP:
3350     return LowerCTPOP(Op, DAG);
3351   case ISD::FCOPYSIGN:
3352     return LowerFCOPYSIGN(Op, DAG);
3353   case ISD::OR:
3354     return LowerVectorOR(Op, DAG);
3355   case ISD::XOR:
3356     return LowerXOR(Op, DAG);
3357   case ISD::PREFETCH:
3358     return LowerPREFETCH(Op, DAG);
3359   case ISD::SINT_TO_FP:
3360   case ISD::UINT_TO_FP:
3361   case ISD::STRICT_SINT_TO_FP:
3362   case ISD::STRICT_UINT_TO_FP:
3363     return LowerINT_TO_FP(Op, DAG);
3364   case ISD::FP_TO_SINT:
3365   case ISD::FP_TO_UINT:
3366   case ISD::STRICT_FP_TO_SINT:
3367   case ISD::STRICT_FP_TO_UINT:
3368     return LowerFP_TO_INT(Op, DAG);
3369   case ISD::FSINCOS:
3370     return LowerFSINCOS(Op, DAG);
3371   case ISD::FLT_ROUNDS_:
3372     return LowerFLT_ROUNDS_(Op, DAG);
3373   case ISD::MUL:
3374     return LowerMUL(Op, DAG);
3375   case ISD::INTRINSIC_WO_CHAIN:
3376     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3377   case ISD::STORE:
3378     return LowerSTORE(Op, DAG);
3379   case ISD::VECREDUCE_ADD:
3380   case ISD::VECREDUCE_SMAX:
3381   case ISD::VECREDUCE_SMIN:
3382   case ISD::VECREDUCE_UMAX:
3383   case ISD::VECREDUCE_UMIN:
3384   case ISD::VECREDUCE_FMAX:
3385   case ISD::VECREDUCE_FMIN:
3386     return LowerVECREDUCE(Op, DAG);
3387   case ISD::ATOMIC_LOAD_SUB:
3388     return LowerATOMIC_LOAD_SUB(Op, DAG);
3389   case ISD::ATOMIC_LOAD_AND:
3390     return LowerATOMIC_LOAD_AND(Op, DAG);
3391   case ISD::DYNAMIC_STACKALLOC:
3392     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3393   case ISD::VSCALE:
3394     return LowerVSCALE(Op, DAG);
3395   }
3396 }
3397 
3398 //===----------------------------------------------------------------------===//
3399 //                      Calling Convention Implementation
3400 //===----------------------------------------------------------------------===//
3401 
3402 /// Selects the correct CCAssignFn for a given CallingConvention value.
3403 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3404                                                      bool IsVarArg) const {
3405   switch (CC) {
3406   default:
3407     report_fatal_error("Unsupported calling convention.");
3408   case CallingConv::WebKit_JS:
3409     return CC_AArch64_WebKit_JS;
3410   case CallingConv::GHC:
3411     return CC_AArch64_GHC;
3412   case CallingConv::C:
3413   case CallingConv::Fast:
3414   case CallingConv::PreserveMost:
3415   case CallingConv::CXX_FAST_TLS:
3416   case CallingConv::Swift:
3417     if (Subtarget->isTargetWindows() && IsVarArg)
3418       return CC_AArch64_Win64_VarArg;
3419     if (!Subtarget->isTargetDarwin())
3420       return CC_AArch64_AAPCS;
3421     if (!IsVarArg)
3422       return CC_AArch64_DarwinPCS;
3423     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3424                                       : CC_AArch64_DarwinPCS_VarArg;
3425    case CallingConv::Win64:
3426     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3427    case CallingConv::CFGuard_Check:
3428      return CC_AArch64_Win64_CFGuard_Check;
3429    case CallingConv::AArch64_VectorCall:
3430    case CallingConv::AArch64_SVE_VectorCall:
3431      return CC_AArch64_AAPCS;
3432   }
3433 }
3434 
3435 CCAssignFn *
3436 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3437   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3438                                       : RetCC_AArch64_AAPCS;
3439 }
3440 
3441 SDValue AArch64TargetLowering::LowerFormalArguments(
3442     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3443     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3444     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3445   MachineFunction &MF = DAG.getMachineFunction();
3446   MachineFrameInfo &MFI = MF.getFrameInfo();
3447   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3448 
3449   // Assign locations to all of the incoming arguments.
3450   SmallVector<CCValAssign, 16> ArgLocs;
3451   DenseMap<unsigned, SDValue> CopiedRegs;
3452   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3453                  *DAG.getContext());
3454 
3455   // At this point, Ins[].VT may already be promoted to i32. To correctly
3456   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3457   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3458   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3459   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3460   // LocVT.
3461   unsigned NumArgs = Ins.size();
3462   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3463   unsigned CurArgIdx = 0;
3464   for (unsigned i = 0; i != NumArgs; ++i) {
3465     MVT ValVT = Ins[i].VT;
3466     if (Ins[i].isOrigArg()) {
3467       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3468       CurArgIdx = Ins[i].getOrigArgIndex();
3469 
3470       // Get type of the original argument.
3471       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3472                                   /*AllowUnknown*/ true);
3473       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3474       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3475       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3476         ValVT = MVT::i8;
3477       else if (ActualMVT == MVT::i16)
3478         ValVT = MVT::i16;
3479     }
3480     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3481     bool Res =
3482         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3483     assert(!Res && "Call operand has unhandled type");
3484     (void)Res;
3485   }
3486   assert(ArgLocs.size() == Ins.size());
3487   SmallVector<SDValue, 16> ArgValues;
3488   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3489     CCValAssign &VA = ArgLocs[i];
3490 
3491     if (Ins[i].Flags.isByVal()) {
3492       // Byval is used for HFAs in the PCS, but the system should work in a
3493       // non-compliant manner for larger structs.
3494       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3495       int Size = Ins[i].Flags.getByValSize();
3496       unsigned NumRegs = (Size + 7) / 8;
3497 
3498       // FIXME: This works on big-endian for composite byvals, which are the common
3499       // case. It should also work for fundamental types too.
3500       unsigned FrameIdx =
3501         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3502       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3503       InVals.push_back(FrameIdxN);
3504 
3505       continue;
3506     }
3507 
3508     SDValue ArgValue;
3509     if (VA.isRegLoc()) {
3510       // Arguments stored in registers.
3511       EVT RegVT = VA.getLocVT();
3512       const TargetRegisterClass *RC;
3513 
3514       if (RegVT == MVT::i32)
3515         RC = &AArch64::GPR32RegClass;
3516       else if (RegVT == MVT::i64)
3517         RC = &AArch64::GPR64RegClass;
3518       else if (RegVT == MVT::f16)
3519         RC = &AArch64::FPR16RegClass;
3520       else if (RegVT == MVT::f32)
3521         RC = &AArch64::FPR32RegClass;
3522       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3523         RC = &AArch64::FPR64RegClass;
3524       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3525         RC = &AArch64::FPR128RegClass;
3526       else if (RegVT.isScalableVector() &&
3527                RegVT.getVectorElementType() == MVT::i1)
3528         RC = &AArch64::PPRRegClass;
3529       else if (RegVT.isScalableVector())
3530         RC = &AArch64::ZPRRegClass;
3531       else
3532         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3533 
3534       // Transform the arguments in physical registers into virtual ones.
3535       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3536       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3537 
3538       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3539       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3540       // truncate to the right size.
3541       switch (VA.getLocInfo()) {
3542       default:
3543         llvm_unreachable("Unknown loc info!");
3544       case CCValAssign::Full:
3545         break;
3546       case CCValAssign::Indirect:
3547         assert(VA.getValVT().isScalableVector() &&
3548                "Only scalable vectors can be passed indirectly");
3549         break;
3550       case CCValAssign::BCvt:
3551         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3552         break;
3553       case CCValAssign::AExt:
3554       case CCValAssign::SExt:
3555       case CCValAssign::ZExt:
3556         break;
3557       case CCValAssign::AExtUpper:
3558         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3559                                DAG.getConstant(32, DL, RegVT));
3560         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3561         break;
3562       }
3563     } else { // VA.isRegLoc()
3564       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3565       unsigned ArgOffset = VA.getLocMemOffset();
3566       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3567                               ? VA.getLocVT().getSizeInBits()
3568                               : VA.getValVT().getSizeInBits()) / 8;
3569 
3570       uint32_t BEAlign = 0;
3571       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3572           !Ins[i].Flags.isInConsecutiveRegs())
3573         BEAlign = 8 - ArgSize;
3574 
3575       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3576 
3577       // Create load nodes to retrieve arguments from the stack.
3578       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3579 
3580       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3581       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3582       MVT MemVT = VA.getValVT();
3583 
3584       switch (VA.getLocInfo()) {
3585       default:
3586         break;
3587       case CCValAssign::Trunc:
3588       case CCValAssign::BCvt:
3589         MemVT = VA.getLocVT();
3590         break;
3591       case CCValAssign::Indirect:
3592         assert(VA.getValVT().isScalableVector() &&
3593                "Only scalable vectors can be passed indirectly");
3594         MemVT = VA.getLocVT();
3595         break;
3596       case CCValAssign::SExt:
3597         ExtType = ISD::SEXTLOAD;
3598         break;
3599       case CCValAssign::ZExt:
3600         ExtType = ISD::ZEXTLOAD;
3601         break;
3602       case CCValAssign::AExt:
3603         ExtType = ISD::EXTLOAD;
3604         break;
3605       }
3606 
3607       ArgValue = DAG.getExtLoad(
3608           ExtType, DL, VA.getLocVT(), Chain, FIN,
3609           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3610           MemVT);
3611 
3612     }
3613 
3614     if (VA.getLocInfo() == CCValAssign::Indirect) {
3615       assert(VA.getValVT().isScalableVector() &&
3616            "Only scalable vectors can be passed indirectly");
3617       // If value is passed via pointer - do a load.
3618       ArgValue =
3619           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
3620     }
3621 
3622     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3623       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3624                              ArgValue, DAG.getValueType(MVT::i32));
3625     InVals.push_back(ArgValue);
3626   }
3627 
3628   // varargs
3629   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3630   if (isVarArg) {
3631     if (!Subtarget->isTargetDarwin() || IsWin64) {
3632       // The AAPCS variadic function ABI is identical to the non-variadic
3633       // one. As a result there may be more arguments in registers and we should
3634       // save them for future reference.
3635       // Win64 variadic functions also pass arguments in registers, but all float
3636       // arguments are passed in integer registers.
3637       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3638     }
3639 
3640     // This will point to the next argument passed via stack.
3641     unsigned StackOffset = CCInfo.getNextStackOffset();
3642     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3643     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3644     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3645 
3646     if (MFI.hasMustTailInVarArgFunc()) {
3647       SmallVector<MVT, 2> RegParmTypes;
3648       RegParmTypes.push_back(MVT::i64);
3649       RegParmTypes.push_back(MVT::f128);
3650       // Compute the set of forwarded registers. The rest are scratch.
3651       SmallVectorImpl<ForwardedRegister> &Forwards =
3652                                        FuncInfo->getForwardedMustTailRegParms();
3653       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3654                                                CC_AArch64_AAPCS);
3655 
3656       // Conservatively forward X8, since it might be used for aggregate return.
3657       if (!CCInfo.isAllocated(AArch64::X8)) {
3658         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3659         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3660       }
3661     }
3662   }
3663 
3664   // On Windows, InReg pointers must be returned, so record the pointer in a
3665   // virtual register at the start of the function so it can be returned in the
3666   // epilogue.
3667   if (IsWin64) {
3668     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3669       if (Ins[I].Flags.isInReg()) {
3670         assert(!FuncInfo->getSRetReturnReg());
3671 
3672         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3673         Register Reg =
3674             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3675         FuncInfo->setSRetReturnReg(Reg);
3676 
3677         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3678         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3679         break;
3680       }
3681     }
3682   }
3683 
3684   unsigned StackArgSize = CCInfo.getNextStackOffset();
3685   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3686   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3687     // This is a non-standard ABI so by fiat I say we're allowed to make full
3688     // use of the stack area to be popped, which must be aligned to 16 bytes in
3689     // any case:
3690     StackArgSize = alignTo(StackArgSize, 16);
3691 
3692     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3693     // a multiple of 16.
3694     FuncInfo->setArgumentStackToRestore(StackArgSize);
3695 
3696     // This realignment carries over to the available bytes below. Our own
3697     // callers will guarantee the space is free by giving an aligned value to
3698     // CALLSEQ_START.
3699   }
3700   // Even if we're not expected to free up the space, it's useful to know how
3701   // much is there while considering tail calls (because we can reuse it).
3702   FuncInfo->setBytesInStackArgArea(StackArgSize);
3703 
3704   if (Subtarget->hasCustomCallingConv())
3705     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3706 
3707   return Chain;
3708 }
3709 
3710 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3711                                                 SelectionDAG &DAG,
3712                                                 const SDLoc &DL,
3713                                                 SDValue &Chain) const {
3714   MachineFunction &MF = DAG.getMachineFunction();
3715   MachineFrameInfo &MFI = MF.getFrameInfo();
3716   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3717   auto PtrVT = getPointerTy(DAG.getDataLayout());
3718   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3719 
3720   SmallVector<SDValue, 8> MemOps;
3721 
3722   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3723                                           AArch64::X3, AArch64::X4, AArch64::X5,
3724                                           AArch64::X6, AArch64::X7 };
3725   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3726   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3727 
3728   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3729   int GPRIdx = 0;
3730   if (GPRSaveSize != 0) {
3731     if (IsWin64) {
3732       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3733       if (GPRSaveSize & 15)
3734         // The extra size here, if triggered, will always be 8.
3735         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3736     } else
3737       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3738 
3739     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3740 
3741     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3742       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3743       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3744       SDValue Store = DAG.getStore(
3745           Val.getValue(1), DL, Val, FIN,
3746           IsWin64
3747               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3748                                                   GPRIdx,
3749                                                   (i - FirstVariadicGPR) * 8)
3750               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3751       MemOps.push_back(Store);
3752       FIN =
3753           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3754     }
3755   }
3756   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3757   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3758 
3759   if (Subtarget->hasFPARMv8() && !IsWin64) {
3760     static const MCPhysReg FPRArgRegs[] = {
3761         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3762         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3763     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3764     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3765 
3766     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3767     int FPRIdx = 0;
3768     if (FPRSaveSize != 0) {
3769       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3770 
3771       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3772 
3773       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3774         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3775         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3776 
3777         SDValue Store = DAG.getStore(
3778             Val.getValue(1), DL, Val, FIN,
3779             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3780         MemOps.push_back(Store);
3781         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3782                           DAG.getConstant(16, DL, PtrVT));
3783       }
3784     }
3785     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3786     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3787   }
3788 
3789   if (!MemOps.empty()) {
3790     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3791   }
3792 }
3793 
3794 /// LowerCallResult - Lower the result values of a call into the
3795 /// appropriate copies out of appropriate physical registers.
3796 SDValue AArch64TargetLowering::LowerCallResult(
3797     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3798     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3799     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3800     SDValue ThisVal) const {
3801   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3802                           ? RetCC_AArch64_WebKit_JS
3803                           : RetCC_AArch64_AAPCS;
3804   // Assign locations to each value returned by this call.
3805   SmallVector<CCValAssign, 16> RVLocs;
3806   DenseMap<unsigned, SDValue> CopiedRegs;
3807   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3808                  *DAG.getContext());
3809   CCInfo.AnalyzeCallResult(Ins, RetCC);
3810 
3811   // Copy all of the result registers out of their specified physreg.
3812   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3813     CCValAssign VA = RVLocs[i];
3814 
3815     // Pass 'this' value directly from the argument to return value, to avoid
3816     // reg unit interference
3817     if (i == 0 && isThisReturn) {
3818       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3819              "unexpected return calling convention register assignment");
3820       InVals.push_back(ThisVal);
3821       continue;
3822     }
3823 
3824     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3825     // allows one use of a physreg per block.
3826     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3827     if (!Val) {
3828       Val =
3829           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3830       Chain = Val.getValue(1);
3831       InFlag = Val.getValue(2);
3832       CopiedRegs[VA.getLocReg()] = Val;
3833     }
3834 
3835     switch (VA.getLocInfo()) {
3836     default:
3837       llvm_unreachable("Unknown loc info!");
3838     case CCValAssign::Full:
3839       break;
3840     case CCValAssign::BCvt:
3841       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3842       break;
3843     case CCValAssign::AExtUpper:
3844       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3845                         DAG.getConstant(32, DL, VA.getLocVT()));
3846       LLVM_FALLTHROUGH;
3847     case CCValAssign::AExt:
3848       LLVM_FALLTHROUGH;
3849     case CCValAssign::ZExt:
3850       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3851       break;
3852     }
3853 
3854     InVals.push_back(Val);
3855   }
3856 
3857   return Chain;
3858 }
3859 
3860 /// Return true if the calling convention is one that we can guarantee TCO for.
3861 static bool canGuaranteeTCO(CallingConv::ID CC) {
3862   return CC == CallingConv::Fast;
3863 }
3864 
3865 /// Return true if we might ever do TCO for calls with this calling convention.
3866 static bool mayTailCallThisCC(CallingConv::ID CC) {
3867   switch (CC) {
3868   case CallingConv::C:
3869   case CallingConv::PreserveMost:
3870   case CallingConv::Swift:
3871     return true;
3872   default:
3873     return canGuaranteeTCO(CC);
3874   }
3875 }
3876 
3877 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3878     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3879     const SmallVectorImpl<ISD::OutputArg> &Outs,
3880     const SmallVectorImpl<SDValue> &OutVals,
3881     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3882   if (!mayTailCallThisCC(CalleeCC))
3883     return false;
3884 
3885   MachineFunction &MF = DAG.getMachineFunction();
3886   const Function &CallerF = MF.getFunction();
3887   CallingConv::ID CallerCC = CallerF.getCallingConv();
3888   bool CCMatch = CallerCC == CalleeCC;
3889 
3890   // Byval parameters hand the function a pointer directly into the stack area
3891   // we want to reuse during a tail call. Working around this *is* possible (see
3892   // X86) but less efficient and uglier in LowerCall.
3893   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3894                                     e = CallerF.arg_end();
3895        i != e; ++i) {
3896     if (i->hasByValAttr())
3897       return false;
3898 
3899     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3900     // In this case, it is necessary to save/restore X0 in the callee. Tail
3901     // call opt interferes with this. So we disable tail call opt when the
3902     // caller has an argument with "inreg" attribute.
3903 
3904     // FIXME: Check whether the callee also has an "inreg" argument.
3905     if (i->hasInRegAttr())
3906       return false;
3907   }
3908 
3909   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3910     return canGuaranteeTCO(CalleeCC) && CCMatch;
3911 
3912   // Externally-defined functions with weak linkage should not be
3913   // tail-called on AArch64 when the OS does not support dynamic
3914   // pre-emption of symbols, as the AAELF spec requires normal calls
3915   // to undefined weak functions to be replaced with a NOP or jump to the
3916   // next instruction. The behaviour of branch instructions in this
3917   // situation (as used for tail calls) is implementation-defined, so we
3918   // cannot rely on the linker replacing the tail call with a return.
3919   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3920     const GlobalValue *GV = G->getGlobal();
3921     const Triple &TT = getTargetMachine().getTargetTriple();
3922     if (GV->hasExternalWeakLinkage() &&
3923         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3924       return false;
3925   }
3926 
3927   // Now we search for cases where we can use a tail call without changing the
3928   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3929   // concept.
3930 
3931   // I want anyone implementing a new calling convention to think long and hard
3932   // about this assert.
3933   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3934          "Unexpected variadic calling convention");
3935 
3936   LLVMContext &C = *DAG.getContext();
3937   if (isVarArg && !Outs.empty()) {
3938     // At least two cases here: if caller is fastcc then we can't have any
3939     // memory arguments (we'd be expected to clean up the stack afterwards). If
3940     // caller is C then we could potentially use its argument area.
3941 
3942     // FIXME: for now we take the most conservative of these in both cases:
3943     // disallow all variadic memory operands.
3944     SmallVector<CCValAssign, 16> ArgLocs;
3945     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3946 
3947     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3948     for (const CCValAssign &ArgLoc : ArgLocs)
3949       if (!ArgLoc.isRegLoc())
3950         return false;
3951   }
3952 
3953   // Check that the call results are passed in the same way.
3954   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3955                                   CCAssignFnForCall(CalleeCC, isVarArg),
3956                                   CCAssignFnForCall(CallerCC, isVarArg)))
3957     return false;
3958   // The callee has to preserve all registers the caller needs to preserve.
3959   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3960   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3961   if (!CCMatch) {
3962     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3963     if (Subtarget->hasCustomCallingConv()) {
3964       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3965       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3966     }
3967     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3968       return false;
3969   }
3970 
3971   // Nothing more to check if the callee is taking no arguments
3972   if (Outs.empty())
3973     return true;
3974 
3975   SmallVector<CCValAssign, 16> ArgLocs;
3976   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3977 
3978   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3979 
3980   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3981 
3982   // If any of the arguments is passed indirectly, it must be SVE, so the
3983   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
3984   // allocate space on the stack. That is why we determine this explicitly here
3985   // the call cannot be a tailcall.
3986   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
3987         assert((A.getLocInfo() != CCValAssign::Indirect ||
3988                 A.getValVT().isScalableVector()) &&
3989                "Expected value to be scalable");
3990         return A.getLocInfo() == CCValAssign::Indirect;
3991       }))
3992     return false;
3993 
3994   // If the stack arguments for this call do not fit into our own save area then
3995   // the call cannot be made tail.
3996   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3997     return false;
3998 
3999   const MachineRegisterInfo &MRI = MF.getRegInfo();
4000   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4001     return false;
4002 
4003   return true;
4004 }
4005 
4006 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4007                                                    SelectionDAG &DAG,
4008                                                    MachineFrameInfo &MFI,
4009                                                    int ClobberedFI) const {
4010   SmallVector<SDValue, 8> ArgChains;
4011   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4012   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4013 
4014   // Include the original chain at the beginning of the list. When this is
4015   // used by target LowerCall hooks, this helps legalize find the
4016   // CALLSEQ_BEGIN node.
4017   ArgChains.push_back(Chain);
4018 
4019   // Add a chain value for each stack argument corresponding
4020   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4021                             UE = DAG.getEntryNode().getNode()->use_end();
4022        U != UE; ++U)
4023     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4024       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4025         if (FI->getIndex() < 0) {
4026           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4027           int64_t InLastByte = InFirstByte;
4028           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4029 
4030           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4031               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4032             ArgChains.push_back(SDValue(L, 1));
4033         }
4034 
4035   // Build a tokenfactor for all the chains.
4036   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4037 }
4038 
4039 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4040                                                    bool TailCallOpt) const {
4041   return CallCC == CallingConv::Fast && TailCallOpt;
4042 }
4043 
4044 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4045 /// and add input and output parameter nodes.
4046 SDValue
4047 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4048                                  SmallVectorImpl<SDValue> &InVals) const {
4049   SelectionDAG &DAG = CLI.DAG;
4050   SDLoc &DL = CLI.DL;
4051   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4052   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4053   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4054   SDValue Chain = CLI.Chain;
4055   SDValue Callee = CLI.Callee;
4056   bool &IsTailCall = CLI.IsTailCall;
4057   CallingConv::ID CallConv = CLI.CallConv;
4058   bool IsVarArg = CLI.IsVarArg;
4059 
4060   MachineFunction &MF = DAG.getMachineFunction();
4061   MachineFunction::CallSiteInfo CSInfo;
4062   bool IsThisReturn = false;
4063 
4064   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4065   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4066   bool IsSibCall = false;
4067 
4068   if (IsTailCall) {
4069     // Check if it's really possible to do a tail call.
4070     IsTailCall = isEligibleForTailCallOptimization(
4071         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4072     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
4073       report_fatal_error("failed to perform tail call elimination on a call "
4074                          "site marked musttail");
4075 
4076     // A sibling call is one where we're under the usual C ABI and not planning
4077     // to change that but can still do a tail call:
4078     if (!TailCallOpt && IsTailCall)
4079       IsSibCall = true;
4080 
4081     if (IsTailCall)
4082       ++NumTailCalls;
4083   }
4084 
4085   // Analyze operands of the call, assigning locations to each operand.
4086   SmallVector<CCValAssign, 16> ArgLocs;
4087   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4088                  *DAG.getContext());
4089 
4090   if (IsVarArg) {
4091     // Handle fixed and variable vector arguments differently.
4092     // Variable vector arguments always go into memory.
4093     unsigned NumArgs = Outs.size();
4094 
4095     for (unsigned i = 0; i != NumArgs; ++i) {
4096       MVT ArgVT = Outs[i].VT;
4097       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4098       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4099                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4100       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4101       assert(!Res && "Call operand has unhandled type");
4102       (void)Res;
4103     }
4104   } else {
4105     // At this point, Outs[].VT may already be promoted to i32. To correctly
4106     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4107     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4108     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4109     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4110     // LocVT.
4111     unsigned NumArgs = Outs.size();
4112     for (unsigned i = 0; i != NumArgs; ++i) {
4113       MVT ValVT = Outs[i].VT;
4114       // Get type of the original argument.
4115       EVT ActualVT = getValueType(DAG.getDataLayout(),
4116                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4117                                   /*AllowUnknown*/ true);
4118       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4119       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4120       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4121       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4122         ValVT = MVT::i8;
4123       else if (ActualMVT == MVT::i16)
4124         ValVT = MVT::i16;
4125 
4126       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4127       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4128       assert(!Res && "Call operand has unhandled type");
4129       (void)Res;
4130     }
4131   }
4132 
4133   // Get a count of how many bytes are to be pushed on the stack.
4134   unsigned NumBytes = CCInfo.getNextStackOffset();
4135 
4136   if (IsSibCall) {
4137     // Since we're not changing the ABI to make this a tail call, the memory
4138     // operands are already available in the caller's incoming argument space.
4139     NumBytes = 0;
4140   }
4141 
4142   // FPDiff is the byte offset of the call's argument area from the callee's.
4143   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4144   // by this amount for a tail call. In a sibling call it must be 0 because the
4145   // caller will deallocate the entire stack and the callee still expects its
4146   // arguments to begin at SP+0. Completely unused for non-tail calls.
4147   int FPDiff = 0;
4148 
4149   if (IsTailCall && !IsSibCall) {
4150     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4151 
4152     // Since callee will pop argument stack as a tail call, we must keep the
4153     // popped size 16-byte aligned.
4154     NumBytes = alignTo(NumBytes, 16);
4155 
4156     // FPDiff will be negative if this tail call requires more space than we
4157     // would automatically have in our incoming argument space. Positive if we
4158     // can actually shrink the stack.
4159     FPDiff = NumReusableBytes - NumBytes;
4160 
4161     // The stack pointer must be 16-byte aligned at all times it's used for a
4162     // memory operation, which in practice means at *all* times and in
4163     // particular across call boundaries. Therefore our own arguments started at
4164     // a 16-byte aligned SP and the delta applied for the tail call should
4165     // satisfy the same constraint.
4166     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4167   }
4168 
4169   // Adjust the stack pointer for the new arguments...
4170   // These operations are automatically eliminated by the prolog/epilog pass
4171   if (!IsSibCall)
4172     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4173 
4174   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4175                                         getPointerTy(DAG.getDataLayout()));
4176 
4177   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4178   SmallSet<unsigned, 8> RegsUsed;
4179   SmallVector<SDValue, 8> MemOpChains;
4180   auto PtrVT = getPointerTy(DAG.getDataLayout());
4181 
4182   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
4183     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4184     for (const auto &F : Forwards) {
4185       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4186        RegsToPass.emplace_back(F.PReg, Val);
4187     }
4188   }
4189 
4190   // Walk the register/memloc assignments, inserting copies/loads.
4191   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4192     CCValAssign &VA = ArgLocs[i];
4193     SDValue Arg = OutVals[i];
4194     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4195 
4196     // Promote the value if needed.
4197     switch (VA.getLocInfo()) {
4198     default:
4199       llvm_unreachable("Unknown loc info!");
4200     case CCValAssign::Full:
4201       break;
4202     case CCValAssign::SExt:
4203       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4204       break;
4205     case CCValAssign::ZExt:
4206       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4207       break;
4208     case CCValAssign::AExt:
4209       if (Outs[i].ArgVT == MVT::i1) {
4210         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4211         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4212         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4213       }
4214       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4215       break;
4216     case CCValAssign::AExtUpper:
4217       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4218       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4219       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4220                         DAG.getConstant(32, DL, VA.getLocVT()));
4221       break;
4222     case CCValAssign::BCvt:
4223       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4224       break;
4225     case CCValAssign::Trunc:
4226       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4227       break;
4228     case CCValAssign::FPExt:
4229       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4230       break;
4231     case CCValAssign::Indirect:
4232       assert(VA.getValVT().isScalableVector() &&
4233              "Only scalable vectors can be passed indirectly");
4234       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4235       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4236       unsigned Align = DAG.getDataLayout().getPrefTypeAlignment(Ty);
4237       int FI = MFI.CreateStackObject(
4238           VA.getValVT().getStoreSize().getKnownMinSize(), Align, false);
4239       MFI.setStackID(FI, TargetStackID::SVEVector);
4240 
4241       SDValue SpillSlot = DAG.getFrameIndex(
4242           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4243       Chain = DAG.getStore(
4244           Chain, DL, Arg, SpillSlot,
4245           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4246       Arg = SpillSlot;
4247       break;
4248     }
4249 
4250     if (VA.isRegLoc()) {
4251       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4252           Outs[0].VT == MVT::i64) {
4253         assert(VA.getLocVT() == MVT::i64 &&
4254                "unexpected calling convention register assignment");
4255         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4256                "unexpected use of 'returned'");
4257         IsThisReturn = true;
4258       }
4259       if (RegsUsed.count(VA.getLocReg())) {
4260         // If this register has already been used then we're trying to pack
4261         // parts of an [N x i32] into an X-register. The extension type will
4262         // take care of putting the two halves in the right place but we have to
4263         // combine them.
4264         SDValue &Bits =
4265             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4266                          [=](const std::pair<unsigned, SDValue> &Elt) {
4267                            return Elt.first == VA.getLocReg();
4268                          })
4269                 ->second;
4270         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4271         // Call site info is used for function's parameter entry value
4272         // tracking. For now we track only simple cases when parameter
4273         // is transferred through whole register.
4274         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4275                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4276                                       return ArgReg.Reg == VA.getLocReg();
4277                                     }),
4278                      CSInfo.end());
4279       } else {
4280         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4281         RegsUsed.insert(VA.getLocReg());
4282         const TargetOptions &Options = DAG.getTarget().Options;
4283         if (Options.EmitCallSiteInfo)
4284           CSInfo.emplace_back(VA.getLocReg(), i);
4285       }
4286     } else {
4287       assert(VA.isMemLoc());
4288 
4289       SDValue DstAddr;
4290       MachinePointerInfo DstInfo;
4291 
4292       // FIXME: This works on big-endian for composite byvals, which are the
4293       // common case. It should also work for fundamental types too.
4294       uint32_t BEAlign = 0;
4295       unsigned OpSize;
4296       if (VA.getLocInfo() == CCValAssign::Indirect)
4297         OpSize = VA.getLocVT().getSizeInBits();
4298       else
4299         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4300                                  : VA.getValVT().getSizeInBits();
4301       OpSize = (OpSize + 7) / 8;
4302       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4303           !Flags.isInConsecutiveRegs()) {
4304         if (OpSize < 8)
4305           BEAlign = 8 - OpSize;
4306       }
4307       unsigned LocMemOffset = VA.getLocMemOffset();
4308       int32_t Offset = LocMemOffset + BEAlign;
4309       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4310       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4311 
4312       if (IsTailCall) {
4313         Offset = Offset + FPDiff;
4314         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4315 
4316         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4317         DstInfo =
4318             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4319 
4320         // Make sure any stack arguments overlapping with where we're storing
4321         // are loaded before this eventual operation. Otherwise they'll be
4322         // clobbered.
4323         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4324       } else {
4325         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4326 
4327         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4328         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4329                                                LocMemOffset);
4330       }
4331 
4332       if (Outs[i].Flags.isByVal()) {
4333         SDValue SizeNode =
4334             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4335         SDValue Cpy = DAG.getMemcpy(
4336             Chain, DL, DstAddr, Arg, SizeNode,
4337             Outs[i].Flags.getNonZeroByValAlign(),
4338             /*isVol = */ false, /*AlwaysInline = */ false,
4339             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4340 
4341         MemOpChains.push_back(Cpy);
4342       } else {
4343         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4344         // promoted to a legal register type i32, we should truncate Arg back to
4345         // i1/i8/i16.
4346         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4347             VA.getValVT() == MVT::i16)
4348           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4349 
4350         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4351         MemOpChains.push_back(Store);
4352       }
4353     }
4354   }
4355 
4356   if (!MemOpChains.empty())
4357     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4358 
4359   // Build a sequence of copy-to-reg nodes chained together with token chain
4360   // and flag operands which copy the outgoing args into the appropriate regs.
4361   SDValue InFlag;
4362   for (auto &RegToPass : RegsToPass) {
4363     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4364                              RegToPass.second, InFlag);
4365     InFlag = Chain.getValue(1);
4366   }
4367 
4368   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4369   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4370   // node so that legalize doesn't hack it.
4371   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4372     auto GV = G->getGlobal();
4373     unsigned OpFlags =
4374         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4375     if (OpFlags & AArch64II::MO_GOT) {
4376       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4377       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4378     } else {
4379       const GlobalValue *GV = G->getGlobal();
4380       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4381     }
4382   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4383     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4384         Subtarget->isTargetMachO()) {
4385       const char *Sym = S->getSymbol();
4386       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4387       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4388     } else {
4389       const char *Sym = S->getSymbol();
4390       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4391     }
4392   }
4393 
4394   // We don't usually want to end the call-sequence here because we would tidy
4395   // the frame up *after* the call, however in the ABI-changing tail-call case
4396   // we've carefully laid out the parameters so that when sp is reset they'll be
4397   // in the correct location.
4398   if (IsTailCall && !IsSibCall) {
4399     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4400                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4401     InFlag = Chain.getValue(1);
4402   }
4403 
4404   std::vector<SDValue> Ops;
4405   Ops.push_back(Chain);
4406   Ops.push_back(Callee);
4407 
4408   if (IsTailCall) {
4409     // Each tail call may have to adjust the stack by a different amount, so
4410     // this information must travel along with the operation for eventual
4411     // consumption by emitEpilogue.
4412     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4413   }
4414 
4415   // Add argument registers to the end of the list so that they are known live
4416   // into the call.
4417   for (auto &RegToPass : RegsToPass)
4418     Ops.push_back(DAG.getRegister(RegToPass.first,
4419                                   RegToPass.second.getValueType()));
4420 
4421   // Check callee args/returns for SVE registers and set calling convention
4422   // accordingly.
4423   if (CallConv == CallingConv::C) {
4424     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4425       return Out.VT.isScalableVector();
4426     });
4427     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4428       return In.VT.isScalableVector();
4429     });
4430 
4431     if (CalleeInSVE || CalleeOutSVE)
4432       CallConv = CallingConv::AArch64_SVE_VectorCall;
4433   }
4434 
4435   // Add a register mask operand representing the call-preserved registers.
4436   const uint32_t *Mask;
4437   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4438   if (IsThisReturn) {
4439     // For 'this' returns, use the X0-preserving mask if applicable
4440     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4441     if (!Mask) {
4442       IsThisReturn = false;
4443       Mask = TRI->getCallPreservedMask(MF, CallConv);
4444     }
4445   } else
4446     Mask = TRI->getCallPreservedMask(MF, CallConv);
4447 
4448   if (Subtarget->hasCustomCallingConv())
4449     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4450 
4451   if (TRI->isAnyArgRegReserved(MF))
4452     TRI->emitReservedArgRegCallError(MF);
4453 
4454   assert(Mask && "Missing call preserved mask for calling convention");
4455   Ops.push_back(DAG.getRegisterMask(Mask));
4456 
4457   if (InFlag.getNode())
4458     Ops.push_back(InFlag);
4459 
4460   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4461 
4462   // If we're doing a tall call, use a TC_RETURN here rather than an
4463   // actual call instruction.
4464   if (IsTailCall) {
4465     MF.getFrameInfo().setHasTailCall();
4466     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4467     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4468     return Ret;
4469   }
4470 
4471   // Returns a chain and a flag for retval copy to use.
4472   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4473   InFlag = Chain.getValue(1);
4474   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4475 
4476   uint64_t CalleePopBytes =
4477       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4478 
4479   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4480                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4481                              InFlag, DL);
4482   if (!Ins.empty())
4483     InFlag = Chain.getValue(1);
4484 
4485   // Handle result values, copying them out of physregs into vregs that we
4486   // return.
4487   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4488                          InVals, IsThisReturn,
4489                          IsThisReturn ? OutVals[0] : SDValue());
4490 }
4491 
4492 bool AArch64TargetLowering::CanLowerReturn(
4493     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4494     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4495   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4496                           ? RetCC_AArch64_WebKit_JS
4497                           : RetCC_AArch64_AAPCS;
4498   SmallVector<CCValAssign, 16> RVLocs;
4499   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4500   return CCInfo.CheckReturn(Outs, RetCC);
4501 }
4502 
4503 SDValue
4504 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4505                                    bool isVarArg,
4506                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4507                                    const SmallVectorImpl<SDValue> &OutVals,
4508                                    const SDLoc &DL, SelectionDAG &DAG) const {
4509   auto &MF = DAG.getMachineFunction();
4510   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4511 
4512   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4513                           ? RetCC_AArch64_WebKit_JS
4514                           : RetCC_AArch64_AAPCS;
4515   SmallVector<CCValAssign, 16> RVLocs;
4516   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4517                  *DAG.getContext());
4518   CCInfo.AnalyzeReturn(Outs, RetCC);
4519 
4520   // Copy the result values into the output registers.
4521   SDValue Flag;
4522   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4523   SmallSet<unsigned, 4> RegsUsed;
4524   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4525        ++i, ++realRVLocIdx) {
4526     CCValAssign &VA = RVLocs[i];
4527     assert(VA.isRegLoc() && "Can only return in registers!");
4528     SDValue Arg = OutVals[realRVLocIdx];
4529 
4530     switch (VA.getLocInfo()) {
4531     default:
4532       llvm_unreachable("Unknown loc info!");
4533     case CCValAssign::Full:
4534       if (Outs[i].ArgVT == MVT::i1) {
4535         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4536         // value. This is strictly redundant on Darwin (which uses "zeroext
4537         // i1"), but will be optimised out before ISel.
4538         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4539         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4540       }
4541       break;
4542     case CCValAssign::BCvt:
4543       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4544       break;
4545     case CCValAssign::AExt:
4546     case CCValAssign::ZExt:
4547       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4548       break;
4549     case CCValAssign::AExtUpper:
4550       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4551       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4552       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4553                         DAG.getConstant(32, DL, VA.getLocVT()));
4554       break;
4555     }
4556 
4557     if (RegsUsed.count(VA.getLocReg())) {
4558       SDValue &Bits =
4559           std::find_if(RetVals.begin(), RetVals.end(),
4560                        [=](const std::pair<unsigned, SDValue> &Elt) {
4561                          return Elt.first == VA.getLocReg();
4562                        })
4563               ->second;
4564       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4565     } else {
4566       RetVals.emplace_back(VA.getLocReg(), Arg);
4567       RegsUsed.insert(VA.getLocReg());
4568     }
4569   }
4570 
4571   SmallVector<SDValue, 4> RetOps(1, Chain);
4572   for (auto &RetVal : RetVals) {
4573     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4574     Flag = Chain.getValue(1);
4575     RetOps.push_back(
4576         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4577   }
4578 
4579   // Windows AArch64 ABIs require that for returning structs by value we copy
4580   // the sret argument into X0 for the return.
4581   // We saved the argument into a virtual register in the entry block,
4582   // so now we copy the value out and into X0.
4583   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4584     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4585                                      getPointerTy(MF.getDataLayout()));
4586 
4587     unsigned RetValReg = AArch64::X0;
4588     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4589     Flag = Chain.getValue(1);
4590 
4591     RetOps.push_back(
4592       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4593   }
4594 
4595   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4596   const MCPhysReg *I =
4597       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4598   if (I) {
4599     for (; *I; ++I) {
4600       if (AArch64::GPR64RegClass.contains(*I))
4601         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4602       else if (AArch64::FPR64RegClass.contains(*I))
4603         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4604       else
4605         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4606     }
4607   }
4608 
4609   RetOps[0] = Chain; // Update chain.
4610 
4611   // Add the flag if we have it.
4612   if (Flag.getNode())
4613     RetOps.push_back(Flag);
4614 
4615   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4616 }
4617 
4618 //===----------------------------------------------------------------------===//
4619 //  Other Lowering Code
4620 //===----------------------------------------------------------------------===//
4621 
4622 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4623                                              SelectionDAG &DAG,
4624                                              unsigned Flag) const {
4625   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4626                                     N->getOffset(), Flag);
4627 }
4628 
4629 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4630                                              SelectionDAG &DAG,
4631                                              unsigned Flag) const {
4632   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4633 }
4634 
4635 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4636                                              SelectionDAG &DAG,
4637                                              unsigned Flag) const {
4638   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4639                                    N->getOffset(), Flag);
4640 }
4641 
4642 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4643                                              SelectionDAG &DAG,
4644                                              unsigned Flag) const {
4645   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4646 }
4647 
4648 // (loadGOT sym)
4649 template <class NodeTy>
4650 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4651                                       unsigned Flags) const {
4652   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4653   SDLoc DL(N);
4654   EVT Ty = getPointerTy(DAG.getDataLayout());
4655   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4656   // FIXME: Once remat is capable of dealing with instructions with register
4657   // operands, expand this into two nodes instead of using a wrapper node.
4658   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4659 }
4660 
4661 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4662 template <class NodeTy>
4663 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4664                                             unsigned Flags) const {
4665   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4666   SDLoc DL(N);
4667   EVT Ty = getPointerTy(DAG.getDataLayout());
4668   const unsigned char MO_NC = AArch64II::MO_NC;
4669   return DAG.getNode(
4670       AArch64ISD::WrapperLarge, DL, Ty,
4671       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4672       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4673       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4674       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4675 }
4676 
4677 // (addlow (adrp %hi(sym)) %lo(sym))
4678 template <class NodeTy>
4679 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4680                                        unsigned Flags) const {
4681   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4682   SDLoc DL(N);
4683   EVT Ty = getPointerTy(DAG.getDataLayout());
4684   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4685   SDValue Lo = getTargetNode(N, Ty, DAG,
4686                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4687   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4688   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4689 }
4690 
4691 // (adr sym)
4692 template <class NodeTy>
4693 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4694                                            unsigned Flags) const {
4695   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4696   SDLoc DL(N);
4697   EVT Ty = getPointerTy(DAG.getDataLayout());
4698   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4699   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4700 }
4701 
4702 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4703                                                   SelectionDAG &DAG) const {
4704   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4705   const GlobalValue *GV = GN->getGlobal();
4706   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4707 
4708   if (OpFlags != AArch64II::MO_NO_FLAG)
4709     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4710            "unexpected offset in global node");
4711 
4712   // This also catches the large code model case for Darwin, and tiny code
4713   // model with got relocations.
4714   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4715     return getGOT(GN, DAG, OpFlags);
4716   }
4717 
4718   SDValue Result;
4719   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4720     Result = getAddrLarge(GN, DAG, OpFlags);
4721   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4722     Result = getAddrTiny(GN, DAG, OpFlags);
4723   } else {
4724     Result = getAddr(GN, DAG, OpFlags);
4725   }
4726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4727   SDLoc DL(GN);
4728   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4729     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4730                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4731   return Result;
4732 }
4733 
4734 /// Convert a TLS address reference into the correct sequence of loads
4735 /// and calls to compute the variable's address (for Darwin, currently) and
4736 /// return an SDValue containing the final node.
4737 
4738 /// Darwin only has one TLS scheme which must be capable of dealing with the
4739 /// fully general situation, in the worst case. This means:
4740 ///     + "extern __thread" declaration.
4741 ///     + Defined in a possibly unknown dynamic library.
4742 ///
4743 /// The general system is that each __thread variable has a [3 x i64] descriptor
4744 /// which contains information used by the runtime to calculate the address. The
4745 /// only part of this the compiler needs to know about is the first xword, which
4746 /// contains a function pointer that must be called with the address of the
4747 /// entire descriptor in "x0".
4748 ///
4749 /// Since this descriptor may be in a different unit, in general even the
4750 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4751 /// is:
4752 ///     adrp x0, _var@TLVPPAGE
4753 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4754 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4755 ///                                      ; the function pointer
4756 ///     blr x1                           ; Uses descriptor address in x0
4757 ///     ; Address of _var is now in x0.
4758 ///
4759 /// If the address of _var's descriptor *is* known to the linker, then it can
4760 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4761 /// a slight efficiency gain.
4762 SDValue
4763 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4764                                                    SelectionDAG &DAG) const {
4765   assert(Subtarget->isTargetDarwin() &&
4766          "This function expects a Darwin target");
4767 
4768   SDLoc DL(Op);
4769   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4770   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4771   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4772 
4773   SDValue TLVPAddr =
4774       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4775   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4776 
4777   // The first entry in the descriptor is a function pointer that we must call
4778   // to obtain the address of the variable.
4779   SDValue Chain = DAG.getEntryNode();
4780   SDValue FuncTLVGet = DAG.getLoad(
4781       PtrMemVT, DL, Chain, DescAddr,
4782       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4783       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4784       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4785   Chain = FuncTLVGet.getValue(1);
4786 
4787   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4788   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4789 
4790   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4791   MFI.setAdjustsStack(true);
4792 
4793   // TLS calls preserve all registers except those that absolutely must be
4794   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4795   // silly).
4796   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4797   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4798   if (Subtarget->hasCustomCallingConv())
4799     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4800 
4801   // Finally, we can make the call. This is just a degenerate version of a
4802   // normal AArch64 call node: x0 takes the address of the descriptor, and
4803   // returns the address of the variable in this thread.
4804   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4805   Chain =
4806       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4807                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4808                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4809   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4810 }
4811 
4812 /// Convert a thread-local variable reference into a sequence of instructions to
4813 /// compute the variable's address for the local exec TLS model of ELF targets.
4814 /// The sequence depends on the maximum TLS area size.
4815 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4816                                                     SDValue ThreadBase,
4817                                                     const SDLoc &DL,
4818                                                     SelectionDAG &DAG) const {
4819   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4820   SDValue TPOff, Addr;
4821 
4822   switch (DAG.getTarget().Options.TLSSize) {
4823   default:
4824     llvm_unreachable("Unexpected TLS size");
4825 
4826   case 12: {
4827     // mrs   x0, TPIDR_EL0
4828     // add   x0, x0, :tprel_lo12:a
4829     SDValue Var = DAG.getTargetGlobalAddress(
4830         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4831     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4832                                       Var,
4833                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4834                    0);
4835   }
4836 
4837   case 24: {
4838     // mrs   x0, TPIDR_EL0
4839     // add   x0, x0, :tprel_hi12:a
4840     // add   x0, x0, :tprel_lo12_nc:a
4841     SDValue HiVar = DAG.getTargetGlobalAddress(
4842         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4843     SDValue LoVar = DAG.getTargetGlobalAddress(
4844         GV, DL, PtrVT, 0,
4845         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4846     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4847                                       HiVar,
4848                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4849                    0);
4850     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4851                                       LoVar,
4852                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4853                    0);
4854   }
4855 
4856   case 32: {
4857     // mrs   x1, TPIDR_EL0
4858     // movz  x0, #:tprel_g1:a
4859     // movk  x0, #:tprel_g0_nc:a
4860     // add   x0, x1, x0
4861     SDValue HiVar = DAG.getTargetGlobalAddress(
4862         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4863     SDValue LoVar = DAG.getTargetGlobalAddress(
4864         GV, DL, PtrVT, 0,
4865         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4866     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4867                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4868                     0);
4869     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4870                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4871                     0);
4872     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4873   }
4874 
4875   case 48: {
4876     // mrs   x1, TPIDR_EL0
4877     // movz  x0, #:tprel_g2:a
4878     // movk  x0, #:tprel_g1_nc:a
4879     // movk  x0, #:tprel_g0_nc:a
4880     // add   x0, x1, x0
4881     SDValue HiVar = DAG.getTargetGlobalAddress(
4882         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4883     SDValue MiVar = DAG.getTargetGlobalAddress(
4884         GV, DL, PtrVT, 0,
4885         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4886     SDValue LoVar = DAG.getTargetGlobalAddress(
4887         GV, DL, PtrVT, 0,
4888         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4889     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4890                                        DAG.getTargetConstant(32, DL, MVT::i32)),
4891                     0);
4892     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4893                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4894                     0);
4895     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4896                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4897                     0);
4898     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4899   }
4900   }
4901 }
4902 
4903 /// When accessing thread-local variables under either the general-dynamic or
4904 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4905 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4906 /// is a function pointer to carry out the resolution.
4907 ///
4908 /// The sequence is:
4909 ///    adrp  x0, :tlsdesc:var
4910 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4911 ///    add   x0, x0, #:tlsdesc_lo12:var
4912 ///    .tlsdesccall var
4913 ///    blr   x1
4914 ///    (TPIDR_EL0 offset now in x0)
4915 ///
4916 ///  The above sequence must be produced unscheduled, to enable the linker to
4917 ///  optimize/relax this sequence.
4918 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4919 ///  above sequence, and expanded really late in the compilation flow, to ensure
4920 ///  the sequence is produced as per above.
4921 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4922                                                       const SDLoc &DL,
4923                                                       SelectionDAG &DAG) const {
4924   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4925 
4926   SDValue Chain = DAG.getEntryNode();
4927   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4928 
4929   Chain =
4930       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4931   SDValue Glue = Chain.getValue(1);
4932 
4933   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4934 }
4935 
4936 SDValue
4937 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4938                                                 SelectionDAG &DAG) const {
4939   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4940 
4941   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4942 
4943   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4944 
4945   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4946     if (Model == TLSModel::LocalDynamic)
4947       Model = TLSModel::GeneralDynamic;
4948   }
4949 
4950   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4951       Model != TLSModel::LocalExec)
4952     report_fatal_error("ELF TLS only supported in small memory model or "
4953                        "in local exec TLS model");
4954   // Different choices can be made for the maximum size of the TLS area for a
4955   // module. For the small address model, the default TLS size is 16MiB and the
4956   // maximum TLS size is 4GiB.
4957   // FIXME: add tiny and large code model support for TLS access models other
4958   // than local exec. We currently generate the same code as small for tiny,
4959   // which may be larger than needed.
4960 
4961   SDValue TPOff;
4962   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4963   SDLoc DL(Op);
4964   const GlobalValue *GV = GA->getGlobal();
4965 
4966   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4967 
4968   if (Model == TLSModel::LocalExec) {
4969     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4970   } else if (Model == TLSModel::InitialExec) {
4971     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4972     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4973   } else if (Model == TLSModel::LocalDynamic) {
4974     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4975     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4976     // the beginning of the module's TLS region, followed by a DTPREL offset
4977     // calculation.
4978 
4979     // These accesses will need deduplicating if there's more than one.
4980     AArch64FunctionInfo *MFI =
4981         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4982     MFI->incNumLocalDynamicTLSAccesses();
4983 
4984     // The call needs a relocation too for linker relaxation. It doesn't make
4985     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4986     // the address.
4987     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4988                                                   AArch64II::MO_TLS);
4989 
4990     // Now we can calculate the offset from TPIDR_EL0 to this module's
4991     // thread-local area.
4992     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4993 
4994     // Now use :dtprel_whatever: operations to calculate this variable's offset
4995     // in its thread-storage area.
4996     SDValue HiVar = DAG.getTargetGlobalAddress(
4997         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4998     SDValue LoVar = DAG.getTargetGlobalAddress(
4999         GV, DL, MVT::i64, 0,
5000         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5001 
5002     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5003                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5004                     0);
5005     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5006                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5007                     0);
5008   } else if (Model == TLSModel::GeneralDynamic) {
5009     // The call needs a relocation too for linker relaxation. It doesn't make
5010     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5011     // the address.
5012     SDValue SymAddr =
5013         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5014 
5015     // Finally we can make a call to calculate the offset from tpidr_el0.
5016     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5017   } else
5018     llvm_unreachable("Unsupported ELF TLS access model");
5019 
5020   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5021 }
5022 
5023 SDValue
5024 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5025                                                     SelectionDAG &DAG) const {
5026   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5027 
5028   SDValue Chain = DAG.getEntryNode();
5029   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5030   SDLoc DL(Op);
5031 
5032   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5033 
5034   // Load the ThreadLocalStoragePointer from the TEB
5035   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5036   SDValue TLSArray =
5037       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5038   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5039   Chain = TLSArray.getValue(1);
5040 
5041   // Load the TLS index from the C runtime;
5042   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5043   // This also does the same as LOADgot, but using a generic i32 load,
5044   // while LOADgot only loads i64.
5045   SDValue TLSIndexHi =
5046       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5047   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5048       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5049   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5050   SDValue TLSIndex =
5051       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5052   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5053   Chain = TLSIndex.getValue(1);
5054 
5055   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5056   // offset into the TLSArray.
5057   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5058   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5059                              DAG.getConstant(3, DL, PtrVT));
5060   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5061                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5062                             MachinePointerInfo());
5063   Chain = TLS.getValue(1);
5064 
5065   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5066   const GlobalValue *GV = GA->getGlobal();
5067   SDValue TGAHi = DAG.getTargetGlobalAddress(
5068       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5069   SDValue TGALo = DAG.getTargetGlobalAddress(
5070       GV, DL, PtrVT, 0,
5071       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5072 
5073   // Add the offset from the start of the .tls section (section base).
5074   SDValue Addr =
5075       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5076                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5077               0);
5078   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5079   return Addr;
5080 }
5081 
5082 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5083                                                      SelectionDAG &DAG) const {
5084   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5085   if (DAG.getTarget().useEmulatedTLS())
5086     return LowerToTLSEmulatedModel(GA, DAG);
5087 
5088   if (Subtarget->isTargetDarwin())
5089     return LowerDarwinGlobalTLSAddress(Op, DAG);
5090   if (Subtarget->isTargetELF())
5091     return LowerELFGlobalTLSAddress(Op, DAG);
5092   if (Subtarget->isTargetWindows())
5093     return LowerWindowsGlobalTLSAddress(Op, DAG);
5094 
5095   llvm_unreachable("Unexpected platform trying to use TLS");
5096 }
5097 
5098 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5099   SDValue Chain = Op.getOperand(0);
5100   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5101   SDValue LHS = Op.getOperand(2);
5102   SDValue RHS = Op.getOperand(3);
5103   SDValue Dest = Op.getOperand(4);
5104   SDLoc dl(Op);
5105 
5106   MachineFunction &MF = DAG.getMachineFunction();
5107   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5108   // will not be produced, as they are conditional branch instructions that do
5109   // not set flags.
5110   bool ProduceNonFlagSettingCondBr =
5111       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5112 
5113   // Handle f128 first, since lowering it will result in comparing the return
5114   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5115   // is expecting to deal with.
5116   if (LHS.getValueType() == MVT::f128) {
5117     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5118 
5119     // If softenSetCCOperands returned a scalar, we need to compare the result
5120     // against zero to select between true and false values.
5121     if (!RHS.getNode()) {
5122       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5123       CC = ISD::SETNE;
5124     }
5125   }
5126 
5127   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5128   // instruction.
5129   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5130       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5131     // Only lower legal XALUO ops.
5132     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5133       return SDValue();
5134 
5135     // The actual operation with overflow check.
5136     AArch64CC::CondCode OFCC;
5137     SDValue Value, Overflow;
5138     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5139 
5140     if (CC == ISD::SETNE)
5141       OFCC = getInvertedCondCode(OFCC);
5142     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5143 
5144     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5145                        Overflow);
5146   }
5147 
5148   if (LHS.getValueType().isInteger()) {
5149     assert((LHS.getValueType() == RHS.getValueType()) &&
5150            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5151 
5152     // If the RHS of the comparison is zero, we can potentially fold this
5153     // to a specialized branch.
5154     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5155     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5156       if (CC == ISD::SETEQ) {
5157         // See if we can use a TBZ to fold in an AND as well.
5158         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5159         // out of bounds, a late MI-layer pass rewrites branches.
5160         // 403.gcc is an example that hits this case.
5161         if (LHS.getOpcode() == ISD::AND &&
5162             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5163             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5164           SDValue Test = LHS.getOperand(0);
5165           uint64_t Mask = LHS.getConstantOperandVal(1);
5166           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5167                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5168                              Dest);
5169         }
5170 
5171         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5172       } else if (CC == ISD::SETNE) {
5173         // See if we can use a TBZ to fold in an AND as well.
5174         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5175         // out of bounds, a late MI-layer pass rewrites branches.
5176         // 403.gcc is an example that hits this case.
5177         if (LHS.getOpcode() == ISD::AND &&
5178             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5179             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5180           SDValue Test = LHS.getOperand(0);
5181           uint64_t Mask = LHS.getConstantOperandVal(1);
5182           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5183                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5184                              Dest);
5185         }
5186 
5187         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5188       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5189         // Don't combine AND since emitComparison converts the AND to an ANDS
5190         // (a.k.a. TST) and the test in the test bit and branch instruction
5191         // becomes redundant.  This would also increase register pressure.
5192         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5193         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5194                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5195       }
5196     }
5197     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5198         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5199       // Don't combine AND since emitComparison converts the AND to an ANDS
5200       // (a.k.a. TST) and the test in the test bit and branch instruction
5201       // becomes redundant.  This would also increase register pressure.
5202       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5203       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5204                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5205     }
5206 
5207     SDValue CCVal;
5208     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5209     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5210                        Cmp);
5211   }
5212 
5213   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5214          LHS.getValueType() == MVT::f64);
5215 
5216   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5217   // clean.  Some of them require two branches to implement.
5218   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5219   AArch64CC::CondCode CC1, CC2;
5220   changeFPCCToAArch64CC(CC, CC1, CC2);
5221   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5222   SDValue BR1 =
5223       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5224   if (CC2 != AArch64CC::AL) {
5225     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5226     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5227                        Cmp);
5228   }
5229 
5230   return BR1;
5231 }
5232 
5233 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5234                                               SelectionDAG &DAG) const {
5235   EVT VT = Op.getValueType();
5236   SDLoc DL(Op);
5237 
5238   SDValue In1 = Op.getOperand(0);
5239   SDValue In2 = Op.getOperand(1);
5240   EVT SrcVT = In2.getValueType();
5241 
5242   if (SrcVT.bitsLT(VT))
5243     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5244   else if (SrcVT.bitsGT(VT))
5245     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5246 
5247   EVT VecVT;
5248   uint64_t EltMask;
5249   SDValue VecVal1, VecVal2;
5250 
5251   auto setVecVal = [&] (int Idx) {
5252     if (!VT.isVector()) {
5253       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5254                                           DAG.getUNDEF(VecVT), In1);
5255       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5256                                           DAG.getUNDEF(VecVT), In2);
5257     } else {
5258       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5259       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5260     }
5261   };
5262 
5263   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5264     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5265     EltMask = 0x80000000ULL;
5266     setVecVal(AArch64::ssub);
5267   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5268     VecVT = MVT::v2i64;
5269 
5270     // We want to materialize a mask with the high bit set, but the AdvSIMD
5271     // immediate moves cannot materialize that in a single instruction for
5272     // 64-bit elements. Instead, materialize zero and then negate it.
5273     EltMask = 0;
5274 
5275     setVecVal(AArch64::dsub);
5276   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5277     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5278     EltMask = 0x8000ULL;
5279     setVecVal(AArch64::hsub);
5280   } else {
5281     llvm_unreachable("Invalid type for copysign!");
5282   }
5283 
5284   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5285 
5286   // If we couldn't materialize the mask above, then the mask vector will be
5287   // the zero vector, and we need to negate it here.
5288   if (VT == MVT::f64 || VT == MVT::v2f64) {
5289     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5290     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5291     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5292   }
5293 
5294   SDValue Sel =
5295       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5296 
5297   if (VT == MVT::f16)
5298     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5299   if (VT == MVT::f32)
5300     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5301   else if (VT == MVT::f64)
5302     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5303   else
5304     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5305 }
5306 
5307 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5308   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5309           Attribute::NoImplicitFloat))
5310     return SDValue();
5311 
5312   if (!Subtarget->hasNEON())
5313     return SDValue();
5314 
5315   // While there is no integer popcount instruction, it can
5316   // be more efficiently lowered to the following sequence that uses
5317   // AdvSIMD registers/instructions as long as the copies to/from
5318   // the AdvSIMD registers are cheap.
5319   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5320   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5321   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5322   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5323   SDValue Val = Op.getOperand(0);
5324   SDLoc DL(Op);
5325   EVT VT = Op.getValueType();
5326 
5327   if (VT == MVT::i32 || VT == MVT::i64) {
5328     if (VT == MVT::i32)
5329       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5330     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5331 
5332     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5333     SDValue UaddLV = DAG.getNode(
5334         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5335         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5336 
5337     if (VT == MVT::i64)
5338       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5339     return UaddLV;
5340   }
5341 
5342   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5343           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5344          "Unexpected type for custom ctpop lowering");
5345 
5346   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5347   Val = DAG.getBitcast(VT8Bit, Val);
5348   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5349 
5350   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5351   unsigned EltSize = 8;
5352   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5353   while (EltSize != VT.getScalarSizeInBits()) {
5354     EltSize *= 2;
5355     NumElts /= 2;
5356     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5357     Val = DAG.getNode(
5358         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5359         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5360   }
5361 
5362   return Val;
5363 }
5364 
5365 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5366 
5367   if (Op.getValueType().isVector())
5368     return LowerVSETCC(Op, DAG);
5369 
5370   bool IsStrict = Op->isStrictFPOpcode();
5371   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5372   unsigned OpNo = IsStrict ? 1 : 0;
5373   SDValue Chain;
5374   if (IsStrict)
5375     Chain = Op.getOperand(0);
5376   SDValue LHS = Op.getOperand(OpNo + 0);
5377   SDValue RHS = Op.getOperand(OpNo + 1);
5378   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5379   SDLoc dl(Op);
5380 
5381   // We chose ZeroOrOneBooleanContents, so use zero and one.
5382   EVT VT = Op.getValueType();
5383   SDValue TVal = DAG.getConstant(1, dl, VT);
5384   SDValue FVal = DAG.getConstant(0, dl, VT);
5385 
5386   // Handle f128 first, since one possible outcome is a normal integer
5387   // comparison which gets picked up by the next if statement.
5388   if (LHS.getValueType() == MVT::f128) {
5389     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5390                         IsSignaling);
5391 
5392     // If softenSetCCOperands returned a scalar, use it.
5393     if (!RHS.getNode()) {
5394       assert(LHS.getValueType() == Op.getValueType() &&
5395              "Unexpected setcc expansion!");
5396       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5397     }
5398   }
5399 
5400   if (LHS.getValueType().isInteger()) {
5401     SDValue CCVal;
5402     SDValue Cmp = getAArch64Cmp(
5403         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5404 
5405     // Note that we inverted the condition above, so we reverse the order of
5406     // the true and false operands here.  This will allow the setcc to be
5407     // matched to a single CSINC instruction.
5408     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5409     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5410   }
5411 
5412   // Now we know we're dealing with FP values.
5413   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5414          LHS.getValueType() == MVT::f64);
5415 
5416   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5417   // and do the comparison.
5418   SDValue Cmp;
5419   if (IsStrict)
5420     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5421   else
5422     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5423 
5424   AArch64CC::CondCode CC1, CC2;
5425   changeFPCCToAArch64CC(CC, CC1, CC2);
5426   SDValue Res;
5427   if (CC2 == AArch64CC::AL) {
5428     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5429                           CC2);
5430     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5431 
5432     // Note that we inverted the condition above, so we reverse the order of
5433     // the true and false operands here.  This will allow the setcc to be
5434     // matched to a single CSINC instruction.
5435     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5436   } else {
5437     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5438     // totally clean.  Some of them require two CSELs to implement.  As is in
5439     // this case, we emit the first CSEL and then emit a second using the output
5440     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5441 
5442     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5443     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5444     SDValue CS1 =
5445         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5446 
5447     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5448     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5449   }
5450   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5451 }
5452 
5453 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5454                                               SDValue RHS, SDValue TVal,
5455                                               SDValue FVal, const SDLoc &dl,
5456                                               SelectionDAG &DAG) const {
5457   // Handle f128 first, because it will result in a comparison of some RTLIB
5458   // call result against zero.
5459   if (LHS.getValueType() == MVT::f128) {
5460     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5461 
5462     // If softenSetCCOperands returned a scalar, we need to compare the result
5463     // against zero to select between true and false values.
5464     if (!RHS.getNode()) {
5465       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5466       CC = ISD::SETNE;
5467     }
5468   }
5469 
5470   // Also handle f16, for which we need to do a f32 comparison.
5471   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5472     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5473     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5474   }
5475 
5476   // Next, handle integers.
5477   if (LHS.getValueType().isInteger()) {
5478     assert((LHS.getValueType() == RHS.getValueType()) &&
5479            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5480 
5481     unsigned Opcode = AArch64ISD::CSEL;
5482 
5483     // If both the TVal and the FVal are constants, see if we can swap them in
5484     // order to for a CSINV or CSINC out of them.
5485     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5486     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5487 
5488     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5489       std::swap(TVal, FVal);
5490       std::swap(CTVal, CFVal);
5491       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5492     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5493       std::swap(TVal, FVal);
5494       std::swap(CTVal, CFVal);
5495       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5496     } else if (TVal.getOpcode() == ISD::XOR) {
5497       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5498       // with a CSINV rather than a CSEL.
5499       if (isAllOnesConstant(TVal.getOperand(1))) {
5500         std::swap(TVal, FVal);
5501         std::swap(CTVal, CFVal);
5502         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5503       }
5504     } else if (TVal.getOpcode() == ISD::SUB) {
5505       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5506       // that we can match with a CSNEG rather than a CSEL.
5507       if (isNullConstant(TVal.getOperand(0))) {
5508         std::swap(TVal, FVal);
5509         std::swap(CTVal, CFVal);
5510         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5511       }
5512     } else if (CTVal && CFVal) {
5513       const int64_t TrueVal = CTVal->getSExtValue();
5514       const int64_t FalseVal = CFVal->getSExtValue();
5515       bool Swap = false;
5516 
5517       // If both TVal and FVal are constants, see if FVal is the
5518       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5519       // instead of a CSEL in that case.
5520       if (TrueVal == ~FalseVal) {
5521         Opcode = AArch64ISD::CSINV;
5522       } else if (TrueVal == -FalseVal) {
5523         Opcode = AArch64ISD::CSNEG;
5524       } else if (TVal.getValueType() == MVT::i32) {
5525         // If our operands are only 32-bit wide, make sure we use 32-bit
5526         // arithmetic for the check whether we can use CSINC. This ensures that
5527         // the addition in the check will wrap around properly in case there is
5528         // an overflow (which would not be the case if we do the check with
5529         // 64-bit arithmetic).
5530         const uint32_t TrueVal32 = CTVal->getZExtValue();
5531         const uint32_t FalseVal32 = CFVal->getZExtValue();
5532 
5533         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5534           Opcode = AArch64ISD::CSINC;
5535 
5536           if (TrueVal32 > FalseVal32) {
5537             Swap = true;
5538           }
5539         }
5540         // 64-bit check whether we can use CSINC.
5541       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5542         Opcode = AArch64ISD::CSINC;
5543 
5544         if (TrueVal > FalseVal) {
5545           Swap = true;
5546         }
5547       }
5548 
5549       // Swap TVal and FVal if necessary.
5550       if (Swap) {
5551         std::swap(TVal, FVal);
5552         std::swap(CTVal, CFVal);
5553         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5554       }
5555 
5556       if (Opcode != AArch64ISD::CSEL) {
5557         // Drop FVal since we can get its value by simply inverting/negating
5558         // TVal.
5559         FVal = TVal;
5560       }
5561     }
5562 
5563     // Avoid materializing a constant when possible by reusing a known value in
5564     // a register.  However, don't perform this optimization if the known value
5565     // is one, zero or negative one in the case of a CSEL.  We can always
5566     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5567     // FVal, respectively.
5568     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5569     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5570         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5571       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5572       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5573       // "a != C ? x : a" to avoid materializing C.
5574       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5575         TVal = LHS;
5576       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5577         FVal = LHS;
5578     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5579       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5580       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5581       // avoid materializing C.
5582       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5583       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5584         Opcode = AArch64ISD::CSINV;
5585         TVal = LHS;
5586         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5587       }
5588     }
5589 
5590     SDValue CCVal;
5591     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5592     EVT VT = TVal.getValueType();
5593     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5594   }
5595 
5596   // Now we know we're dealing with FP values.
5597   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5598          LHS.getValueType() == MVT::f64);
5599   assert(LHS.getValueType() == RHS.getValueType());
5600   EVT VT = TVal.getValueType();
5601   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5602 
5603   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5604   // clean.  Some of them require two CSELs to implement.
5605   AArch64CC::CondCode CC1, CC2;
5606   changeFPCCToAArch64CC(CC, CC1, CC2);
5607 
5608   if (DAG.getTarget().Options.UnsafeFPMath) {
5609     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5610     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5611     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5612     if (RHSVal && RHSVal->isZero()) {
5613       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5614       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5615 
5616       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5617           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5618         TVal = LHS;
5619       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5620                CFVal && CFVal->isZero() &&
5621                FVal.getValueType() == LHS.getValueType())
5622         FVal = LHS;
5623     }
5624   }
5625 
5626   // Emit first, and possibly only, CSEL.
5627   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5628   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5629 
5630   // If we need a second CSEL, emit it, using the output of the first as the
5631   // RHS.  We're effectively OR'ing the two CC's together.
5632   if (CC2 != AArch64CC::AL) {
5633     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5634     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5635   }
5636 
5637   // Otherwise, return the output of the first CSEL.
5638   return CS1;
5639 }
5640 
5641 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5642                                               SelectionDAG &DAG) const {
5643   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5644   SDValue LHS = Op.getOperand(0);
5645   SDValue RHS = Op.getOperand(1);
5646   SDValue TVal = Op.getOperand(2);
5647   SDValue FVal = Op.getOperand(3);
5648   SDLoc DL(Op);
5649   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5650 }
5651 
5652 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5653                                            SelectionDAG &DAG) const {
5654   SDValue CCVal = Op->getOperand(0);
5655   SDValue TVal = Op->getOperand(1);
5656   SDValue FVal = Op->getOperand(2);
5657   SDLoc DL(Op);
5658 
5659   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5660   // instruction.
5661   if (ISD::isOverflowIntrOpRes(CCVal)) {
5662     // Only lower legal XALUO ops.
5663     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5664       return SDValue();
5665 
5666     AArch64CC::CondCode OFCC;
5667     SDValue Value, Overflow;
5668     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5669     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5670 
5671     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5672                        CCVal, Overflow);
5673   }
5674 
5675   // Lower it the same way as we would lower a SELECT_CC node.
5676   ISD::CondCode CC;
5677   SDValue LHS, RHS;
5678   if (CCVal.getOpcode() == ISD::SETCC) {
5679     LHS = CCVal.getOperand(0);
5680     RHS = CCVal.getOperand(1);
5681     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5682   } else {
5683     LHS = CCVal;
5684     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5685     CC = ISD::SETNE;
5686   }
5687   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5688 }
5689 
5690 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5691                                               SelectionDAG &DAG) const {
5692   // Jump table entries as PC relative offsets. No additional tweaking
5693   // is necessary here. Just get the address of the jump table.
5694   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5695 
5696   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5697       !Subtarget->isTargetMachO()) {
5698     return getAddrLarge(JT, DAG);
5699   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5700     return getAddrTiny(JT, DAG);
5701   }
5702   return getAddr(JT, DAG);
5703 }
5704 
5705 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5706                                           SelectionDAG &DAG) const {
5707   // Jump table entries as PC relative offsets. No additional tweaking
5708   // is necessary here. Just get the address of the jump table.
5709   SDLoc DL(Op);
5710   SDValue JT = Op.getOperand(1);
5711   SDValue Entry = Op.getOperand(2);
5712   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5713 
5714   SDNode *Dest =
5715       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5716                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5717   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5718                      SDValue(Dest, 0));
5719 }
5720 
5721 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5722                                                  SelectionDAG &DAG) const {
5723   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5724 
5725   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5726     // Use the GOT for the large code model on iOS.
5727     if (Subtarget->isTargetMachO()) {
5728       return getGOT(CP, DAG);
5729     }
5730     return getAddrLarge(CP, DAG);
5731   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5732     return getAddrTiny(CP, DAG);
5733   } else {
5734     return getAddr(CP, DAG);
5735   }
5736 }
5737 
5738 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5739                                                SelectionDAG &DAG) const {
5740   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5741   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5742       !Subtarget->isTargetMachO()) {
5743     return getAddrLarge(BA, DAG);
5744   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5745     return getAddrTiny(BA, DAG);
5746   }
5747   return getAddr(BA, DAG);
5748 }
5749 
5750 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5751                                                  SelectionDAG &DAG) const {
5752   AArch64FunctionInfo *FuncInfo =
5753       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5754 
5755   SDLoc DL(Op);
5756   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5757                                  getPointerTy(DAG.getDataLayout()));
5758   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5759   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5760   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5761                       MachinePointerInfo(SV));
5762 }
5763 
5764 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5765                                                   SelectionDAG &DAG) const {
5766   AArch64FunctionInfo *FuncInfo =
5767       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5768 
5769   SDLoc DL(Op);
5770   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5771                                      ? FuncInfo->getVarArgsGPRIndex()
5772                                      : FuncInfo->getVarArgsStackIndex(),
5773                                  getPointerTy(DAG.getDataLayout()));
5774   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5775   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5776                       MachinePointerInfo(SV));
5777 }
5778 
5779 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5780                                                 SelectionDAG &DAG) const {
5781   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5782   // Standard, section B.3.
5783   MachineFunction &MF = DAG.getMachineFunction();
5784   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5785   auto PtrVT = getPointerTy(DAG.getDataLayout());
5786   SDLoc DL(Op);
5787 
5788   SDValue Chain = Op.getOperand(0);
5789   SDValue VAList = Op.getOperand(1);
5790   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5791   SmallVector<SDValue, 4> MemOps;
5792 
5793   // void *__stack at offset 0
5794   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5795   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5796                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5797 
5798   // void *__gr_top at offset 8
5799   int GPRSize = FuncInfo->getVarArgsGPRSize();
5800   if (GPRSize > 0) {
5801     SDValue GRTop, GRTopAddr;
5802 
5803     GRTopAddr =
5804         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5805 
5806     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5807     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5808                         DAG.getConstant(GPRSize, DL, PtrVT));
5809 
5810     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5811                                   MachinePointerInfo(SV, 8),
5812                                   /* Alignment = */ 8));
5813   }
5814 
5815   // void *__vr_top at offset 16
5816   int FPRSize = FuncInfo->getVarArgsFPRSize();
5817   if (FPRSize > 0) {
5818     SDValue VRTop, VRTopAddr;
5819     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5820                             DAG.getConstant(16, DL, PtrVT));
5821 
5822     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5823     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5824                         DAG.getConstant(FPRSize, DL, PtrVT));
5825 
5826     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5827                                   MachinePointerInfo(SV, 16),
5828                                   /* Alignment = */ 8));
5829   }
5830 
5831   // int __gr_offs at offset 24
5832   SDValue GROffsAddr =
5833       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5834   MemOps.push_back(DAG.getStore(
5835       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5836       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5837 
5838   // int __vr_offs at offset 28
5839   SDValue VROffsAddr =
5840       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5841   MemOps.push_back(DAG.getStore(
5842       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5843       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5844 
5845   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5846 }
5847 
5848 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5849                                             SelectionDAG &DAG) const {
5850   MachineFunction &MF = DAG.getMachineFunction();
5851 
5852   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5853     return LowerWin64_VASTART(Op, DAG);
5854   else if (Subtarget->isTargetDarwin())
5855     return LowerDarwin_VASTART(Op, DAG);
5856   else
5857     return LowerAAPCS_VASTART(Op, DAG);
5858 }
5859 
5860 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5861                                            SelectionDAG &DAG) const {
5862   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5863   // pointer.
5864   SDLoc DL(Op);
5865   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5866   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5867                          Subtarget->isTargetWindows()) ? PtrSize : 32;
5868   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5869   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5870 
5871   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5872                        DAG.getConstant(VaListSize, DL, MVT::i32),
5873                        Align(PtrSize), false, false, false,
5874                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
5875 }
5876 
5877 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5878   assert(Subtarget->isTargetDarwin() &&
5879          "automatic va_arg instruction only works on Darwin");
5880 
5881   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5882   EVT VT = Op.getValueType();
5883   SDLoc DL(Op);
5884   SDValue Chain = Op.getOperand(0);
5885   SDValue Addr = Op.getOperand(1);
5886   unsigned Align = Op.getConstantOperandVal(3);
5887   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5888   auto PtrVT = getPointerTy(DAG.getDataLayout());
5889   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5890   SDValue VAList =
5891       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5892   Chain = VAList.getValue(1);
5893   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5894 
5895   if (Align > MinSlotSize) {
5896     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5897     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5898                          DAG.getConstant(Align - 1, DL, PtrVT));
5899     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5900                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5901   }
5902 
5903   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5904   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5905 
5906   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5907   // up to 64 bits.  At the very least, we have to increase the striding of the
5908   // vaargs list to match this, and for FP values we need to introduce
5909   // FP_ROUND nodes as well.
5910   if (VT.isInteger() && !VT.isVector())
5911     ArgSize = std::max(ArgSize, MinSlotSize);
5912   bool NeedFPTrunc = false;
5913   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5914     ArgSize = 8;
5915     NeedFPTrunc = true;
5916   }
5917 
5918   // Increment the pointer, VAList, to the next vaarg
5919   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5920                                DAG.getConstant(ArgSize, DL, PtrVT));
5921   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5922 
5923   // Store the incremented VAList to the legalized pointer
5924   SDValue APStore =
5925       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5926 
5927   // Load the actual argument out of the pointer VAList
5928   if (NeedFPTrunc) {
5929     // Load the value as an f64.
5930     SDValue WideFP =
5931         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5932     // Round the value down to an f32.
5933     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5934                                    DAG.getIntPtrConstant(1, DL));
5935     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5936     // Merge the rounded value with the chain output of the load.
5937     return DAG.getMergeValues(Ops, DL);
5938   }
5939 
5940   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5941 }
5942 
5943 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5944                                               SelectionDAG &DAG) const {
5945   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5946   MFI.setFrameAddressIsTaken(true);
5947 
5948   EVT VT = Op.getValueType();
5949   SDLoc DL(Op);
5950   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5951   SDValue FrameAddr =
5952       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5953   while (Depth--)
5954     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5955                             MachinePointerInfo());
5956 
5957   if (Subtarget->isTargetILP32())
5958     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5959                             DAG.getValueType(VT));
5960 
5961   return FrameAddr;
5962 }
5963 
5964 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5965                                               SelectionDAG &DAG) const {
5966   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5967 
5968   EVT VT = getPointerTy(DAG.getDataLayout());
5969   SDLoc DL(Op);
5970   int FI = MFI.CreateFixedObject(4, 0, false);
5971   return DAG.getFrameIndex(FI, VT);
5972 }
5973 
5974 #define GET_REGISTER_MATCHER
5975 #include "AArch64GenAsmMatcher.inc"
5976 
5977 // FIXME? Maybe this could be a TableGen attribute on some registers and
5978 // this table could be generated automatically from RegInfo.
5979 Register AArch64TargetLowering::
5980 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5981   Register Reg = MatchRegisterName(RegName);
5982   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5983     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5984     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5985     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5986       Reg = 0;
5987   }
5988   if (Reg)
5989     return Reg;
5990   report_fatal_error(Twine("Invalid register name \""
5991                               + StringRef(RegName)  + "\"."));
5992 }
5993 
5994 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5995                                                      SelectionDAG &DAG) const {
5996   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5997 
5998   EVT VT = Op.getValueType();
5999   SDLoc DL(Op);
6000 
6001   SDValue FrameAddr =
6002       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6003   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6004 
6005   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6006 }
6007 
6008 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6009                                                SelectionDAG &DAG) const {
6010   MachineFunction &MF = DAG.getMachineFunction();
6011   MachineFrameInfo &MFI = MF.getFrameInfo();
6012   MFI.setReturnAddressIsTaken(true);
6013 
6014   EVT VT = Op.getValueType();
6015   SDLoc DL(Op);
6016   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6017   if (Depth) {
6018     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6019     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6020     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6021                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6022                        MachinePointerInfo());
6023   }
6024 
6025   // Return LR, which contains the return address. Mark it an implicit live-in.
6026   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6027   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6028 }
6029 
6030 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6031 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6032 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6033                                                     SelectionDAG &DAG) const {
6034   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6035   EVT VT = Op.getValueType();
6036   unsigned VTBits = VT.getSizeInBits();
6037   SDLoc dl(Op);
6038   SDValue ShOpLo = Op.getOperand(0);
6039   SDValue ShOpHi = Op.getOperand(1);
6040   SDValue ShAmt = Op.getOperand(2);
6041   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6042 
6043   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6044 
6045   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6046                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6047   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6048 
6049   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6050   // is "undef". We wanted 0, so CSEL it directly.
6051   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6052                                ISD::SETEQ, dl, DAG);
6053   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6054   HiBitsForLo =
6055       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6056                   HiBitsForLo, CCVal, Cmp);
6057 
6058   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6059                                    DAG.getConstant(VTBits, dl, MVT::i64));
6060 
6061   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6062   SDValue LoForNormalShift =
6063       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6064 
6065   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6066                        dl, DAG);
6067   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6068   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6069   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6070                            LoForNormalShift, CCVal, Cmp);
6071 
6072   // AArch64 shifts larger than the register width are wrapped rather than
6073   // clamped, so we can't just emit "hi >> x".
6074   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6075   SDValue HiForBigShift =
6076       Opc == ISD::SRA
6077           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6078                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6079           : DAG.getConstant(0, dl, VT);
6080   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6081                            HiForNormalShift, CCVal, Cmp);
6082 
6083   SDValue Ops[2] = { Lo, Hi };
6084   return DAG.getMergeValues(Ops, dl);
6085 }
6086 
6087 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6088 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6089 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6090                                                    SelectionDAG &DAG) const {
6091   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6092   EVT VT = Op.getValueType();
6093   unsigned VTBits = VT.getSizeInBits();
6094   SDLoc dl(Op);
6095   SDValue ShOpLo = Op.getOperand(0);
6096   SDValue ShOpHi = Op.getOperand(1);
6097   SDValue ShAmt = Op.getOperand(2);
6098 
6099   assert(Op.getOpcode() == ISD::SHL_PARTS);
6100   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6101                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6102   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6103 
6104   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6105   // is "undef". We wanted 0, so CSEL it directly.
6106   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6107                                ISD::SETEQ, dl, DAG);
6108   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6109   LoBitsForHi =
6110       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6111                   LoBitsForHi, CCVal, Cmp);
6112 
6113   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6114                                    DAG.getConstant(VTBits, dl, MVT::i64));
6115   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6116   SDValue HiForNormalShift =
6117       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6118 
6119   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6120 
6121   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6122                        dl, DAG);
6123   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6124   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6125                            HiForNormalShift, CCVal, Cmp);
6126 
6127   // AArch64 shifts of larger than register sizes are wrapped rather than
6128   // clamped, so we can't just emit "lo << a" if a is too big.
6129   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6130   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6131   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6132                            LoForNormalShift, CCVal, Cmp);
6133 
6134   SDValue Ops[2] = { Lo, Hi };
6135   return DAG.getMergeValues(Ops, dl);
6136 }
6137 
6138 bool AArch64TargetLowering::isOffsetFoldingLegal(
6139     const GlobalAddressSDNode *GA) const {
6140   // Offsets are folded in the DAG combine rather than here so that we can
6141   // intelligently choose an offset based on the uses.
6142   return false;
6143 }
6144 
6145 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6146                                          bool OptForSize) const {
6147   bool IsLegal = false;
6148   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6149   // 16-bit case when target has full fp16 support.
6150   // FIXME: We should be able to handle f128 as well with a clever lowering.
6151   const APInt ImmInt = Imm.bitcastToAPInt();
6152   if (VT == MVT::f64)
6153     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6154   else if (VT == MVT::f32)
6155     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6156   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6157     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6158   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6159   //       generate that fmov.
6160 
6161   // If we can not materialize in immediate field for fmov, check if the
6162   // value can be encoded as the immediate operand of a logical instruction.
6163   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6164   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6165     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6166     // however the mov+fmov sequence is always better because of the reduced
6167     // cache pressure. The timings are still the same if you consider
6168     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6169     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6170     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6171     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6172 			      Insn);
6173     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6174     IsLegal = Insn.size() <= Limit;
6175   }
6176 
6177   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6178                     << " imm value: "; Imm.dump(););
6179   return IsLegal;
6180 }
6181 
6182 //===----------------------------------------------------------------------===//
6183 //                          AArch64 Optimization Hooks
6184 //===----------------------------------------------------------------------===//
6185 
6186 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6187                            SDValue Operand, SelectionDAG &DAG,
6188                            int &ExtraSteps) {
6189   EVT VT = Operand.getValueType();
6190   if (ST->hasNEON() &&
6191       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6192        VT == MVT::f32 || VT == MVT::v1f32 ||
6193        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6194     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6195       // For the reciprocal estimates, convergence is quadratic, so the number
6196       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6197       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6198       // the result for float (23 mantissa bits) is 2 and for double (52
6199       // mantissa bits) is 3.
6200       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6201 
6202     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6203   }
6204 
6205   return SDValue();
6206 }
6207 
6208 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6209                                                SelectionDAG &DAG, int Enabled,
6210                                                int &ExtraSteps,
6211                                                bool &UseOneConst,
6212                                                bool Reciprocal) const {
6213   if (Enabled == ReciprocalEstimate::Enabled ||
6214       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6215     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6216                                        DAG, ExtraSteps)) {
6217       SDLoc DL(Operand);
6218       EVT VT = Operand.getValueType();
6219 
6220       SDNodeFlags Flags;
6221       Flags.setAllowReassociation(true);
6222 
6223       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6224       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6225       for (int i = ExtraSteps; i > 0; --i) {
6226         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6227                                    Flags);
6228         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6229         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6230       }
6231       if (!Reciprocal) {
6232         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6233                                       VT);
6234         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6235         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6236 
6237         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6238         // Correct the result if the operand is 0.0.
6239         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6240                                VT, Eq, Operand, Estimate);
6241       }
6242 
6243       ExtraSteps = 0;
6244       return Estimate;
6245     }
6246 
6247   return SDValue();
6248 }
6249 
6250 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6251                                                 SelectionDAG &DAG, int Enabled,
6252                                                 int &ExtraSteps) const {
6253   if (Enabled == ReciprocalEstimate::Enabled)
6254     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6255                                        DAG, ExtraSteps)) {
6256       SDLoc DL(Operand);
6257       EVT VT = Operand.getValueType();
6258 
6259       SDNodeFlags Flags;
6260       Flags.setAllowReassociation(true);
6261 
6262       // Newton reciprocal iteration: E * (2 - X * E)
6263       // AArch64 reciprocal iteration instruction: (2 - M * N)
6264       for (int i = ExtraSteps; i > 0; --i) {
6265         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6266                                    Estimate, Flags);
6267         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6268       }
6269 
6270       ExtraSteps = 0;
6271       return Estimate;
6272     }
6273 
6274   return SDValue();
6275 }
6276 
6277 //===----------------------------------------------------------------------===//
6278 //                          AArch64 Inline Assembly Support
6279 //===----------------------------------------------------------------------===//
6280 
6281 // Table of Constraints
6282 // TODO: This is the current set of constraints supported by ARM for the
6283 // compiler, not all of them may make sense.
6284 //
6285 // r - A general register
6286 // w - An FP/SIMD register of some size in the range v0-v31
6287 // x - An FP/SIMD register of some size in the range v0-v15
6288 // I - Constant that can be used with an ADD instruction
6289 // J - Constant that can be used with a SUB instruction
6290 // K - Constant that can be used with a 32-bit logical instruction
6291 // L - Constant that can be used with a 64-bit logical instruction
6292 // M - Constant that can be used as a 32-bit MOV immediate
6293 // N - Constant that can be used as a 64-bit MOV immediate
6294 // Q - A memory reference with base register and no offset
6295 // S - A symbolic address
6296 // Y - Floating point constant zero
6297 // Z - Integer constant zero
6298 //
6299 //   Note that general register operands will be output using their 64-bit x
6300 // register name, whatever the size of the variable, unless the asm operand
6301 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6302 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6303 // %q modifier.
6304 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6305   // At this point, we have to lower this constraint to something else, so we
6306   // lower it to an "r" or "w". However, by doing this we will force the result
6307   // to be in register, while the X constraint is much more permissive.
6308   //
6309   // Although we are correct (we are free to emit anything, without
6310   // constraints), we might break use cases that would expect us to be more
6311   // efficient and emit something else.
6312   if (!Subtarget->hasFPARMv8())
6313     return "r";
6314 
6315   if (ConstraintVT.isFloatingPoint())
6316     return "w";
6317 
6318   if (ConstraintVT.isVector() &&
6319      (ConstraintVT.getSizeInBits() == 64 ||
6320       ConstraintVT.getSizeInBits() == 128))
6321     return "w";
6322 
6323   return "r";
6324 }
6325 
6326 enum PredicateConstraint {
6327   Upl,
6328   Upa,
6329   Invalid
6330 };
6331 
6332 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6333   PredicateConstraint P = PredicateConstraint::Invalid;
6334   if (Constraint == "Upa")
6335     P = PredicateConstraint::Upa;
6336   if (Constraint == "Upl")
6337     P = PredicateConstraint::Upl;
6338   return P;
6339 }
6340 
6341 /// getConstraintType - Given a constraint letter, return the type of
6342 /// constraint it is for this target.
6343 AArch64TargetLowering::ConstraintType
6344 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6345   if (Constraint.size() == 1) {
6346     switch (Constraint[0]) {
6347     default:
6348       break;
6349     case 'x':
6350     case 'w':
6351     case 'y':
6352       return C_RegisterClass;
6353     // An address with a single base register. Due to the way we
6354     // currently handle addresses it is the same as 'r'.
6355     case 'Q':
6356       return C_Memory;
6357     case 'I':
6358     case 'J':
6359     case 'K':
6360     case 'L':
6361     case 'M':
6362     case 'N':
6363     case 'Y':
6364     case 'Z':
6365       return C_Immediate;
6366     case 'z':
6367     case 'S': // A symbolic address
6368       return C_Other;
6369     }
6370   } else if (parsePredicateConstraint(Constraint) !=
6371              PredicateConstraint::Invalid)
6372       return C_RegisterClass;
6373   return TargetLowering::getConstraintType(Constraint);
6374 }
6375 
6376 /// Examine constraint type and operand type and determine a weight value.
6377 /// This object must already have been set up with the operand type
6378 /// and the current alternative constraint selected.
6379 TargetLowering::ConstraintWeight
6380 AArch64TargetLowering::getSingleConstraintMatchWeight(
6381     AsmOperandInfo &info, const char *constraint) const {
6382   ConstraintWeight weight = CW_Invalid;
6383   Value *CallOperandVal = info.CallOperandVal;
6384   // If we don't have a value, we can't do a match,
6385   // but allow it at the lowest weight.
6386   if (!CallOperandVal)
6387     return CW_Default;
6388   Type *type = CallOperandVal->getType();
6389   // Look at the constraint type.
6390   switch (*constraint) {
6391   default:
6392     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6393     break;
6394   case 'x':
6395   case 'w':
6396   case 'y':
6397     if (type->isFloatingPointTy() || type->isVectorTy())
6398       weight = CW_Register;
6399     break;
6400   case 'z':
6401     weight = CW_Constant;
6402     break;
6403   case 'U':
6404     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6405       weight = CW_Register;
6406     break;
6407   }
6408   return weight;
6409 }
6410 
6411 std::pair<unsigned, const TargetRegisterClass *>
6412 AArch64TargetLowering::getRegForInlineAsmConstraint(
6413     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6414   if (Constraint.size() == 1) {
6415     switch (Constraint[0]) {
6416     case 'r':
6417       if (VT.getSizeInBits() == 64)
6418         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6419       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6420     case 'w':
6421       if (!Subtarget->hasFPARMv8())
6422         break;
6423       if (VT.isScalableVector())
6424         return std::make_pair(0U, &AArch64::ZPRRegClass);
6425       if (VT.getSizeInBits() == 16)
6426         return std::make_pair(0U, &AArch64::FPR16RegClass);
6427       if (VT.getSizeInBits() == 32)
6428         return std::make_pair(0U, &AArch64::FPR32RegClass);
6429       if (VT.getSizeInBits() == 64)
6430         return std::make_pair(0U, &AArch64::FPR64RegClass);
6431       if (VT.getSizeInBits() == 128)
6432         return std::make_pair(0U, &AArch64::FPR128RegClass);
6433       break;
6434     // The instructions that this constraint is designed for can
6435     // only take 128-bit registers so just use that regclass.
6436     case 'x':
6437       if (!Subtarget->hasFPARMv8())
6438         break;
6439       if (VT.isScalableVector())
6440         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6441       if (VT.getSizeInBits() == 128)
6442         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6443       break;
6444     case 'y':
6445       if (!Subtarget->hasFPARMv8())
6446         break;
6447       if (VT.isScalableVector())
6448         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6449       break;
6450     }
6451   } else {
6452     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6453     if (PC != PredicateConstraint::Invalid) {
6454       assert(VT.isScalableVector());
6455       bool restricted = (PC == PredicateConstraint::Upl);
6456       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6457                           : std::make_pair(0U, &AArch64::PPRRegClass);
6458     }
6459   }
6460   if (StringRef("{cc}").equals_lower(Constraint))
6461     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6462 
6463   // Use the default implementation in TargetLowering to convert the register
6464   // constraint into a member of a register class.
6465   std::pair<unsigned, const TargetRegisterClass *> Res;
6466   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6467 
6468   // Not found as a standard register?
6469   if (!Res.second) {
6470     unsigned Size = Constraint.size();
6471     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6472         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6473       int RegNo;
6474       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6475       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6476         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6477         // By default we'll emit v0-v31 for this unless there's a modifier where
6478         // we'll emit the correct register as well.
6479         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6480           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6481           Res.second = &AArch64::FPR64RegClass;
6482         } else {
6483           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6484           Res.second = &AArch64::FPR128RegClass;
6485         }
6486       }
6487     }
6488   }
6489 
6490   if (Res.second && !Subtarget->hasFPARMv8() &&
6491       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6492       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6493     return std::make_pair(0U, nullptr);
6494 
6495   return Res;
6496 }
6497 
6498 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6499 /// vector.  If it is invalid, don't add anything to Ops.
6500 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6501     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6502     SelectionDAG &DAG) const {
6503   SDValue Result;
6504 
6505   // Currently only support length 1 constraints.
6506   if (Constraint.length() != 1)
6507     return;
6508 
6509   char ConstraintLetter = Constraint[0];
6510   switch (ConstraintLetter) {
6511   default:
6512     break;
6513 
6514   // This set of constraints deal with valid constants for various instructions.
6515   // Validate and return a target constant for them if we can.
6516   case 'z': {
6517     // 'z' maps to xzr or wzr so it needs an input of 0.
6518     if (!isNullConstant(Op))
6519       return;
6520 
6521     if (Op.getValueType() == MVT::i64)
6522       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6523     else
6524       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6525     break;
6526   }
6527   case 'S': {
6528     // An absolute symbolic address or label reference.
6529     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6530       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6531                                           GA->getValueType(0));
6532     } else if (const BlockAddressSDNode *BA =
6533                    dyn_cast<BlockAddressSDNode>(Op)) {
6534       Result =
6535           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6536     } else if (const ExternalSymbolSDNode *ES =
6537                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6538       Result =
6539           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6540     } else
6541       return;
6542     break;
6543   }
6544 
6545   case 'I':
6546   case 'J':
6547   case 'K':
6548   case 'L':
6549   case 'M':
6550   case 'N':
6551     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6552     if (!C)
6553       return;
6554 
6555     // Grab the value and do some validation.
6556     uint64_t CVal = C->getZExtValue();
6557     switch (ConstraintLetter) {
6558     // The I constraint applies only to simple ADD or SUB immediate operands:
6559     // i.e. 0 to 4095 with optional shift by 12
6560     // The J constraint applies only to ADD or SUB immediates that would be
6561     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6562     // instruction [or vice versa], in other words -1 to -4095 with optional
6563     // left shift by 12.
6564     case 'I':
6565       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6566         break;
6567       return;
6568     case 'J': {
6569       uint64_t NVal = -C->getSExtValue();
6570       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6571         CVal = C->getSExtValue();
6572         break;
6573       }
6574       return;
6575     }
6576     // The K and L constraints apply *only* to logical immediates, including
6577     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6578     // been removed and MOV should be used). So these constraints have to
6579     // distinguish between bit patterns that are valid 32-bit or 64-bit
6580     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6581     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6582     // versa.
6583     case 'K':
6584       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6585         break;
6586       return;
6587     case 'L':
6588       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6589         break;
6590       return;
6591     // The M and N constraints are a superset of K and L respectively, for use
6592     // with the MOV (immediate) alias. As well as the logical immediates they
6593     // also match 32 or 64-bit immediates that can be loaded either using a
6594     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6595     // (M) or 64-bit 0x1234000000000000 (N) etc.
6596     // As a note some of this code is liberally stolen from the asm parser.
6597     case 'M': {
6598       if (!isUInt<32>(CVal))
6599         return;
6600       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6601         break;
6602       if ((CVal & 0xFFFF) == CVal)
6603         break;
6604       if ((CVal & 0xFFFF0000ULL) == CVal)
6605         break;
6606       uint64_t NCVal = ~(uint32_t)CVal;
6607       if ((NCVal & 0xFFFFULL) == NCVal)
6608         break;
6609       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6610         break;
6611       return;
6612     }
6613     case 'N': {
6614       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6615         break;
6616       if ((CVal & 0xFFFFULL) == CVal)
6617         break;
6618       if ((CVal & 0xFFFF0000ULL) == CVal)
6619         break;
6620       if ((CVal & 0xFFFF00000000ULL) == CVal)
6621         break;
6622       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6623         break;
6624       uint64_t NCVal = ~CVal;
6625       if ((NCVal & 0xFFFFULL) == NCVal)
6626         break;
6627       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6628         break;
6629       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6630         break;
6631       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6632         break;
6633       return;
6634     }
6635     default:
6636       return;
6637     }
6638 
6639     // All assembler immediates are 64-bit integers.
6640     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6641     break;
6642   }
6643 
6644   if (Result.getNode()) {
6645     Ops.push_back(Result);
6646     return;
6647   }
6648 
6649   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6650 }
6651 
6652 //===----------------------------------------------------------------------===//
6653 //                     AArch64 Advanced SIMD Support
6654 //===----------------------------------------------------------------------===//
6655 
6656 /// WidenVector - Given a value in the V64 register class, produce the
6657 /// equivalent value in the V128 register class.
6658 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6659   EVT VT = V64Reg.getValueType();
6660   unsigned NarrowSize = VT.getVectorNumElements();
6661   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6662   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6663   SDLoc DL(V64Reg);
6664 
6665   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6666                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6667 }
6668 
6669 /// getExtFactor - Determine the adjustment factor for the position when
6670 /// generating an "extract from vector registers" instruction.
6671 static unsigned getExtFactor(SDValue &V) {
6672   EVT EltType = V.getValueType().getVectorElementType();
6673   return EltType.getSizeInBits() / 8;
6674 }
6675 
6676 /// NarrowVector - Given a value in the V128 register class, produce the
6677 /// equivalent value in the V64 register class.
6678 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6679   EVT VT = V128Reg.getValueType();
6680   unsigned WideSize = VT.getVectorNumElements();
6681   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6682   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6683   SDLoc DL(V128Reg);
6684 
6685   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6686 }
6687 
6688 // Gather data to see if the operation can be modelled as a
6689 // shuffle in combination with VEXTs.
6690 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6691                                                   SelectionDAG &DAG) const {
6692   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6693   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6694   SDLoc dl(Op);
6695   EVT VT = Op.getValueType();
6696   unsigned NumElts = VT.getVectorNumElements();
6697 
6698   struct ShuffleSourceInfo {
6699     SDValue Vec;
6700     unsigned MinElt;
6701     unsigned MaxElt;
6702 
6703     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6704     // be compatible with the shuffle we intend to construct. As a result
6705     // ShuffleVec will be some sliding window into the original Vec.
6706     SDValue ShuffleVec;
6707 
6708     // Code should guarantee that element i in Vec starts at element "WindowBase
6709     // + i * WindowScale in ShuffleVec".
6710     int WindowBase;
6711     int WindowScale;
6712 
6713     ShuffleSourceInfo(SDValue Vec)
6714       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6715           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6716 
6717     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6718   };
6719 
6720   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6721   // node.
6722   SmallVector<ShuffleSourceInfo, 2> Sources;
6723   for (unsigned i = 0; i < NumElts; ++i) {
6724     SDValue V = Op.getOperand(i);
6725     if (V.isUndef())
6726       continue;
6727     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6728              !isa<ConstantSDNode>(V.getOperand(1))) {
6729       LLVM_DEBUG(
6730           dbgs() << "Reshuffle failed: "
6731                     "a shuffle can only come from building a vector from "
6732                     "various elements of other vectors, provided their "
6733                     "indices are constant\n");
6734       return SDValue();
6735     }
6736 
6737     // Add this element source to the list if it's not already there.
6738     SDValue SourceVec = V.getOperand(0);
6739     auto Source = find(Sources, SourceVec);
6740     if (Source == Sources.end())
6741       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6742 
6743     // Update the minimum and maximum lane number seen.
6744     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6745     Source->MinElt = std::min(Source->MinElt, EltNo);
6746     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6747   }
6748 
6749   if (Sources.size() > 2) {
6750     LLVM_DEBUG(
6751         dbgs() << "Reshuffle failed: currently only do something sane when at "
6752                   "most two source vectors are involved\n");
6753     return SDValue();
6754   }
6755 
6756   // Find out the smallest element size among result and two sources, and use
6757   // it as element size to build the shuffle_vector.
6758   EVT SmallestEltTy = VT.getVectorElementType();
6759   for (auto &Source : Sources) {
6760     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6761     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6762       SmallestEltTy = SrcEltTy;
6763     }
6764   }
6765   unsigned ResMultiplier =
6766       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6767   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6768   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6769 
6770   // If the source vector is too wide or too narrow, we may nevertheless be able
6771   // to construct a compatible shuffle either by concatenating it with UNDEF or
6772   // extracting a suitable range of elements.
6773   for (auto &Src : Sources) {
6774     EVT SrcVT = Src.ShuffleVec.getValueType();
6775 
6776     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6777       continue;
6778 
6779     // This stage of the search produces a source with the same element type as
6780     // the original, but with a total width matching the BUILD_VECTOR output.
6781     EVT EltVT = SrcVT.getVectorElementType();
6782     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6783     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6784 
6785     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6786       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6787       // We can pad out the smaller vector for free, so if it's part of a
6788       // shuffle...
6789       Src.ShuffleVec =
6790           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6791                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6792       continue;
6793     }
6794 
6795     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6796 
6797     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6798       LLVM_DEBUG(
6799           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6800       return SDValue();
6801     }
6802 
6803     if (Src.MinElt >= NumSrcElts) {
6804       // The extraction can just take the second half
6805       Src.ShuffleVec =
6806           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6807                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6808       Src.WindowBase = -NumSrcElts;
6809     } else if (Src.MaxElt < NumSrcElts) {
6810       // The extraction can just take the first half
6811       Src.ShuffleVec =
6812           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6813                       DAG.getConstant(0, dl, MVT::i64));
6814     } else {
6815       // An actual VEXT is needed
6816       SDValue VEXTSrc1 =
6817           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6818                       DAG.getConstant(0, dl, MVT::i64));
6819       SDValue VEXTSrc2 =
6820           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6821                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6822       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6823 
6824       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6825                                    VEXTSrc2,
6826                                    DAG.getConstant(Imm, dl, MVT::i32));
6827       Src.WindowBase = -Src.MinElt;
6828     }
6829   }
6830 
6831   // Another possible incompatibility occurs from the vector element types. We
6832   // can fix this by bitcasting the source vectors to the same type we intend
6833   // for the shuffle.
6834   for (auto &Src : Sources) {
6835     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6836     if (SrcEltTy == SmallestEltTy)
6837       continue;
6838     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6839     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6840     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6841     Src.WindowBase *= Src.WindowScale;
6842   }
6843 
6844   // Final sanity check before we try to actually produce a shuffle.
6845   LLVM_DEBUG(for (auto Src
6846                   : Sources)
6847                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6848 
6849   // The stars all align, our next step is to produce the mask for the shuffle.
6850   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6851   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6852   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6853     SDValue Entry = Op.getOperand(i);
6854     if (Entry.isUndef())
6855       continue;
6856 
6857     auto Src = find(Sources, Entry.getOperand(0));
6858     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6859 
6860     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6861     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6862     // segment.
6863     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6864     int BitsDefined =
6865         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6866     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6867 
6868     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6869     // starting at the appropriate offset.
6870     int *LaneMask = &Mask[i * ResMultiplier];
6871 
6872     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6873     ExtractBase += NumElts * (Src - Sources.begin());
6874     for (int j = 0; j < LanesDefined; ++j)
6875       LaneMask[j] = ExtractBase + j;
6876   }
6877 
6878   // Final check before we try to produce nonsense...
6879   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6880     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6881     return SDValue();
6882   }
6883 
6884   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6885   for (unsigned i = 0; i < Sources.size(); ++i)
6886     ShuffleOps[i] = Sources[i].ShuffleVec;
6887 
6888   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6889                                          ShuffleOps[1], Mask);
6890   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6891 
6892   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6893              dbgs() << "Reshuffle, creating node: "; V.dump(););
6894 
6895   return V;
6896 }
6897 
6898 // check if an EXT instruction can handle the shuffle mask when the
6899 // vector sources of the shuffle are the same.
6900 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6901   unsigned NumElts = VT.getVectorNumElements();
6902 
6903   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6904   if (M[0] < 0)
6905     return false;
6906 
6907   Imm = M[0];
6908 
6909   // If this is a VEXT shuffle, the immediate value is the index of the first
6910   // element.  The other shuffle indices must be the successive elements after
6911   // the first one.
6912   unsigned ExpectedElt = Imm;
6913   for (unsigned i = 1; i < NumElts; ++i) {
6914     // Increment the expected index.  If it wraps around, just follow it
6915     // back to index zero and keep going.
6916     ++ExpectedElt;
6917     if (ExpectedElt == NumElts)
6918       ExpectedElt = 0;
6919 
6920     if (M[i] < 0)
6921       continue; // ignore UNDEF indices
6922     if (ExpectedElt != static_cast<unsigned>(M[i]))
6923       return false;
6924   }
6925 
6926   return true;
6927 }
6928 
6929 // check if an EXT instruction can handle the shuffle mask when the
6930 // vector sources of the shuffle are different.
6931 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6932                       unsigned &Imm) {
6933   // Look for the first non-undef element.
6934   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6935 
6936   // Benefit form APInt to handle overflow when calculating expected element.
6937   unsigned NumElts = VT.getVectorNumElements();
6938   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6939   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6940   // The following shuffle indices must be the successive elements after the
6941   // first real element.
6942   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6943       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6944   if (FirstWrongElt != M.end())
6945     return false;
6946 
6947   // The index of an EXT is the first element if it is not UNDEF.
6948   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6949   // value of the first element.  E.g.
6950   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6951   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6952   // ExpectedElt is the last mask index plus 1.
6953   Imm = ExpectedElt.getZExtValue();
6954 
6955   // There are two difference cases requiring to reverse input vectors.
6956   // For example, for vector <4 x i32> we have the following cases,
6957   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6958   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6959   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6960   // to reverse two input vectors.
6961   if (Imm < NumElts)
6962     ReverseEXT = true;
6963   else
6964     Imm -= NumElts;
6965 
6966   return true;
6967 }
6968 
6969 /// isREVMask - Check if a vector shuffle corresponds to a REV
6970 /// instruction with the specified blocksize.  (The order of the elements
6971 /// within each block of the vector is reversed.)
6972 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6973   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6974          "Only possible block sizes for REV are: 16, 32, 64");
6975 
6976   unsigned EltSz = VT.getScalarSizeInBits();
6977   if (EltSz == 64)
6978     return false;
6979 
6980   unsigned NumElts = VT.getVectorNumElements();
6981   unsigned BlockElts = M[0] + 1;
6982   // If the first shuffle index is UNDEF, be optimistic.
6983   if (M[0] < 0)
6984     BlockElts = BlockSize / EltSz;
6985 
6986   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6987     return false;
6988 
6989   for (unsigned i = 0; i < NumElts; ++i) {
6990     if (M[i] < 0)
6991       continue; // ignore UNDEF indices
6992     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6993       return false;
6994   }
6995 
6996   return true;
6997 }
6998 
6999 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7000   unsigned NumElts = VT.getVectorNumElements();
7001   if (NumElts % 2 != 0)
7002     return false;
7003   WhichResult = (M[0] == 0 ? 0 : 1);
7004   unsigned Idx = WhichResult * NumElts / 2;
7005   for (unsigned i = 0; i != NumElts; i += 2) {
7006     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7007         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7008       return false;
7009     Idx += 1;
7010   }
7011 
7012   return true;
7013 }
7014 
7015 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7016   unsigned NumElts = VT.getVectorNumElements();
7017   WhichResult = (M[0] == 0 ? 0 : 1);
7018   for (unsigned i = 0; i != NumElts; ++i) {
7019     if (M[i] < 0)
7020       continue; // ignore UNDEF indices
7021     if ((unsigned)M[i] != 2 * i + WhichResult)
7022       return false;
7023   }
7024 
7025   return true;
7026 }
7027 
7028 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7029   unsigned NumElts = VT.getVectorNumElements();
7030   if (NumElts % 2 != 0)
7031     return false;
7032   WhichResult = (M[0] == 0 ? 0 : 1);
7033   for (unsigned i = 0; i < NumElts; i += 2) {
7034     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7035         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7036       return false;
7037   }
7038   return true;
7039 }
7040 
7041 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7042 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7043 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7044 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7045   unsigned NumElts = VT.getVectorNumElements();
7046   if (NumElts % 2 != 0)
7047     return false;
7048   WhichResult = (M[0] == 0 ? 0 : 1);
7049   unsigned Idx = WhichResult * NumElts / 2;
7050   for (unsigned i = 0; i != NumElts; i += 2) {
7051     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7052         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7053       return false;
7054     Idx += 1;
7055   }
7056 
7057   return true;
7058 }
7059 
7060 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7062 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7063 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7064   unsigned Half = VT.getVectorNumElements() / 2;
7065   WhichResult = (M[0] == 0 ? 0 : 1);
7066   for (unsigned j = 0; j != 2; ++j) {
7067     unsigned Idx = WhichResult;
7068     for (unsigned i = 0; i != Half; ++i) {
7069       int MIdx = M[i + j * Half];
7070       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7071         return false;
7072       Idx += 2;
7073     }
7074   }
7075 
7076   return true;
7077 }
7078 
7079 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7080 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7081 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7082 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7083   unsigned NumElts = VT.getVectorNumElements();
7084   if (NumElts % 2 != 0)
7085     return false;
7086   WhichResult = (M[0] == 0 ? 0 : 1);
7087   for (unsigned i = 0; i < NumElts; i += 2) {
7088     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7089         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7090       return false;
7091   }
7092   return true;
7093 }
7094 
7095 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7096                       bool &DstIsLeft, int &Anomaly) {
7097   if (M.size() != static_cast<size_t>(NumInputElements))
7098     return false;
7099 
7100   int NumLHSMatch = 0, NumRHSMatch = 0;
7101   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7102 
7103   for (int i = 0; i < NumInputElements; ++i) {
7104     if (M[i] == -1) {
7105       ++NumLHSMatch;
7106       ++NumRHSMatch;
7107       continue;
7108     }
7109 
7110     if (M[i] == i)
7111       ++NumLHSMatch;
7112     else
7113       LastLHSMismatch = i;
7114 
7115     if (M[i] == i + NumInputElements)
7116       ++NumRHSMatch;
7117     else
7118       LastRHSMismatch = i;
7119   }
7120 
7121   if (NumLHSMatch == NumInputElements - 1) {
7122     DstIsLeft = true;
7123     Anomaly = LastLHSMismatch;
7124     return true;
7125   } else if (NumRHSMatch == NumInputElements - 1) {
7126     DstIsLeft = false;
7127     Anomaly = LastRHSMismatch;
7128     return true;
7129   }
7130 
7131   return false;
7132 }
7133 
7134 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7135   if (VT.getSizeInBits() != 128)
7136     return false;
7137 
7138   unsigned NumElts = VT.getVectorNumElements();
7139 
7140   for (int I = 0, E = NumElts / 2; I != E; I++) {
7141     if (Mask[I] != I)
7142       return false;
7143   }
7144 
7145   int Offset = NumElts / 2;
7146   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7147     if (Mask[I] != I + SplitLHS * Offset)
7148       return false;
7149   }
7150 
7151   return true;
7152 }
7153 
7154 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7155   SDLoc DL(Op);
7156   EVT VT = Op.getValueType();
7157   SDValue V0 = Op.getOperand(0);
7158   SDValue V1 = Op.getOperand(1);
7159   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7160 
7161   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7162       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7163     return SDValue();
7164 
7165   bool SplitV0 = V0.getValueSizeInBits() == 128;
7166 
7167   if (!isConcatMask(Mask, VT, SplitV0))
7168     return SDValue();
7169 
7170   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7171   if (SplitV0) {
7172     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7173                      DAG.getConstant(0, DL, MVT::i64));
7174   }
7175   if (V1.getValueSizeInBits() == 128) {
7176     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7177                      DAG.getConstant(0, DL, MVT::i64));
7178   }
7179   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7180 }
7181 
7182 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7183 /// the specified operations to build the shuffle.
7184 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7185                                       SDValue RHS, SelectionDAG &DAG,
7186                                       const SDLoc &dl) {
7187   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7188   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7189   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7190 
7191   enum {
7192     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7193     OP_VREV,
7194     OP_VDUP0,
7195     OP_VDUP1,
7196     OP_VDUP2,
7197     OP_VDUP3,
7198     OP_VEXT1,
7199     OP_VEXT2,
7200     OP_VEXT3,
7201     OP_VUZPL, // VUZP, left result
7202     OP_VUZPR, // VUZP, right result
7203     OP_VZIPL, // VZIP, left result
7204     OP_VZIPR, // VZIP, right result
7205     OP_VTRNL, // VTRN, left result
7206     OP_VTRNR  // VTRN, right result
7207   };
7208 
7209   if (OpNum == OP_COPY) {
7210     if (LHSID == (1 * 9 + 2) * 9 + 3)
7211       return LHS;
7212     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7213     return RHS;
7214   }
7215 
7216   SDValue OpLHS, OpRHS;
7217   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7218   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7219   EVT VT = OpLHS.getValueType();
7220 
7221   switch (OpNum) {
7222   default:
7223     llvm_unreachable("Unknown shuffle opcode!");
7224   case OP_VREV:
7225     // VREV divides the vector in half and swaps within the half.
7226     if (VT.getVectorElementType() == MVT::i32 ||
7227         VT.getVectorElementType() == MVT::f32)
7228       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7229     // vrev <4 x i16> -> REV32
7230     if (VT.getVectorElementType() == MVT::i16 ||
7231         VT.getVectorElementType() == MVT::f16)
7232       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7233     // vrev <4 x i8> -> REV16
7234     assert(VT.getVectorElementType() == MVT::i8);
7235     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7236   case OP_VDUP0:
7237   case OP_VDUP1:
7238   case OP_VDUP2:
7239   case OP_VDUP3: {
7240     EVT EltTy = VT.getVectorElementType();
7241     unsigned Opcode;
7242     if (EltTy == MVT::i8)
7243       Opcode = AArch64ISD::DUPLANE8;
7244     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7245       Opcode = AArch64ISD::DUPLANE16;
7246     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7247       Opcode = AArch64ISD::DUPLANE32;
7248     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7249       Opcode = AArch64ISD::DUPLANE64;
7250     else
7251       llvm_unreachable("Invalid vector element type?");
7252 
7253     if (VT.getSizeInBits() == 64)
7254       OpLHS = WidenVector(OpLHS, DAG);
7255     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7256     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7257   }
7258   case OP_VEXT1:
7259   case OP_VEXT2:
7260   case OP_VEXT3: {
7261     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7262     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7263                        DAG.getConstant(Imm, dl, MVT::i32));
7264   }
7265   case OP_VUZPL:
7266     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7267                        OpRHS);
7268   case OP_VUZPR:
7269     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7270                        OpRHS);
7271   case OP_VZIPL:
7272     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7273                        OpRHS);
7274   case OP_VZIPR:
7275     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7276                        OpRHS);
7277   case OP_VTRNL:
7278     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7279                        OpRHS);
7280   case OP_VTRNR:
7281     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7282                        OpRHS);
7283   }
7284 }
7285 
7286 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7287                            SelectionDAG &DAG) {
7288   // Check to see if we can use the TBL instruction.
7289   SDValue V1 = Op.getOperand(0);
7290   SDValue V2 = Op.getOperand(1);
7291   SDLoc DL(Op);
7292 
7293   EVT EltVT = Op.getValueType().getVectorElementType();
7294   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7295 
7296   SmallVector<SDValue, 8> TBLMask;
7297   for (int Val : ShuffleMask) {
7298     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7299       unsigned Offset = Byte + Val * BytesPerElt;
7300       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7301     }
7302   }
7303 
7304   MVT IndexVT = MVT::v8i8;
7305   unsigned IndexLen = 8;
7306   if (Op.getValueSizeInBits() == 128) {
7307     IndexVT = MVT::v16i8;
7308     IndexLen = 16;
7309   }
7310 
7311   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7312   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7313 
7314   SDValue Shuffle;
7315   if (V2.getNode()->isUndef()) {
7316     if (IndexLen == 8)
7317       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7318     Shuffle = DAG.getNode(
7319         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7320         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7321         DAG.getBuildVector(IndexVT, DL,
7322                            makeArrayRef(TBLMask.data(), IndexLen)));
7323   } else {
7324     if (IndexLen == 8) {
7325       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7326       Shuffle = DAG.getNode(
7327           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7328           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7329           DAG.getBuildVector(IndexVT, DL,
7330                              makeArrayRef(TBLMask.data(), IndexLen)));
7331     } else {
7332       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7333       // cannot currently represent the register constraints on the input
7334       // table registers.
7335       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7336       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7337       //                   IndexLen));
7338       Shuffle = DAG.getNode(
7339           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7340           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7341           V2Cst, DAG.getBuildVector(IndexVT, DL,
7342                                     makeArrayRef(TBLMask.data(), IndexLen)));
7343     }
7344   }
7345   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7346 }
7347 
7348 static unsigned getDUPLANEOp(EVT EltType) {
7349   if (EltType == MVT::i8)
7350     return AArch64ISD::DUPLANE8;
7351   if (EltType == MVT::i16 || EltType == MVT::f16)
7352     return AArch64ISD::DUPLANE16;
7353   if (EltType == MVT::i32 || EltType == MVT::f32)
7354     return AArch64ISD::DUPLANE32;
7355   if (EltType == MVT::i64 || EltType == MVT::f64)
7356     return AArch64ISD::DUPLANE64;
7357 
7358   llvm_unreachable("Invalid vector element type?");
7359 }
7360 
7361 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7362                                                    SelectionDAG &DAG) const {
7363   SDLoc dl(Op);
7364   EVT VT = Op.getValueType();
7365 
7366   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7367 
7368   // Convert shuffles that are directly supported on NEON to target-specific
7369   // DAG nodes, instead of keeping them as shuffles and matching them again
7370   // during code selection.  This is more efficient and avoids the possibility
7371   // of inconsistencies between legalization and selection.
7372   ArrayRef<int> ShuffleMask = SVN->getMask();
7373 
7374   SDValue V1 = Op.getOperand(0);
7375   SDValue V2 = Op.getOperand(1);
7376 
7377   if (SVN->isSplat()) {
7378     int Lane = SVN->getSplatIndex();
7379     // If this is undef splat, generate it via "just" vdup, if possible.
7380     if (Lane == -1)
7381       Lane = 0;
7382 
7383     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7384       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7385                          V1.getOperand(0));
7386     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7387     // constant. If so, we can just reference the lane's definition directly.
7388     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7389         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7390       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7391 
7392     // Otherwise, duplicate from the lane of the input vector.
7393     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7394 
7395     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7396     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7397       // Match: dup (bitcast (extract_subv X, C)), LaneC
7398       if (BitCast.getOpcode() != ISD::BITCAST ||
7399           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7400         return false;
7401 
7402       // The extract index must align in the destination type. That may not
7403       // happen if the bitcast is from narrow to wide type.
7404       SDValue Extract = BitCast.getOperand(0);
7405       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7406       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7407       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7408       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7409       if (ExtIdxInBits % CastedEltBitWidth != 0)
7410         return false;
7411 
7412       // Update the lane value by offsetting with the scaled extract index.
7413       LaneC += ExtIdxInBits / CastedEltBitWidth;
7414 
7415       // Determine the casted vector type of the wide vector input.
7416       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7417       // Examples:
7418       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7419       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7420       unsigned SrcVecNumElts =
7421           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7422       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7423                                 SrcVecNumElts);
7424       return true;
7425     };
7426     MVT CastVT;
7427     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7428       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7429     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7430       // The lane is incremented by the index of the extract.
7431       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7432       Lane += V1.getConstantOperandVal(1);
7433       V1 = V1.getOperand(0);
7434     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7435       // The lane is decremented if we are splatting from the 2nd operand.
7436       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7437       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7438       Lane -= Idx * VT.getVectorNumElements() / 2;
7439       V1 = WidenVector(V1.getOperand(Idx), DAG);
7440     } else if (VT.getSizeInBits() == 64) {
7441       // Widen the operand to 128-bit register with undef.
7442       V1 = WidenVector(V1, DAG);
7443     }
7444     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7445   }
7446 
7447   if (isREVMask(ShuffleMask, VT, 64))
7448     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7449   if (isREVMask(ShuffleMask, VT, 32))
7450     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7451   if (isREVMask(ShuffleMask, VT, 16))
7452     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7453 
7454   bool ReverseEXT = false;
7455   unsigned Imm;
7456   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7457     if (ReverseEXT)
7458       std::swap(V1, V2);
7459     Imm *= getExtFactor(V1);
7460     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7461                        DAG.getConstant(Imm, dl, MVT::i32));
7462   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7463     Imm *= getExtFactor(V1);
7464     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7465                        DAG.getConstant(Imm, dl, MVT::i32));
7466   }
7467 
7468   unsigned WhichResult;
7469   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7470     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7471     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7472   }
7473   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7474     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7475     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7476   }
7477   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7478     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7479     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7480   }
7481 
7482   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7483     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7484     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7485   }
7486   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7487     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7488     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7489   }
7490   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7491     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7492     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7493   }
7494 
7495   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7496     return Concat;
7497 
7498   bool DstIsLeft;
7499   int Anomaly;
7500   int NumInputElements = V1.getValueType().getVectorNumElements();
7501   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7502     SDValue DstVec = DstIsLeft ? V1 : V2;
7503     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7504 
7505     SDValue SrcVec = V1;
7506     int SrcLane = ShuffleMask[Anomaly];
7507     if (SrcLane >= NumInputElements) {
7508       SrcVec = V2;
7509       SrcLane -= VT.getVectorNumElements();
7510     }
7511     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7512 
7513     EVT ScalarVT = VT.getVectorElementType();
7514 
7515     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7516       ScalarVT = MVT::i32;
7517 
7518     return DAG.getNode(
7519         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7520         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7521         DstLaneV);
7522   }
7523 
7524   // If the shuffle is not directly supported and it has 4 elements, use
7525   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7526   unsigned NumElts = VT.getVectorNumElements();
7527   if (NumElts == 4) {
7528     unsigned PFIndexes[4];
7529     for (unsigned i = 0; i != 4; ++i) {
7530       if (ShuffleMask[i] < 0)
7531         PFIndexes[i] = 8;
7532       else
7533         PFIndexes[i] = ShuffleMask[i];
7534     }
7535 
7536     // Compute the index in the perfect shuffle table.
7537     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7538                             PFIndexes[2] * 9 + PFIndexes[3];
7539     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7540     unsigned Cost = (PFEntry >> 30);
7541 
7542     if (Cost <= 4)
7543       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7544   }
7545 
7546   return GenerateTBL(Op, ShuffleMask, DAG);
7547 }
7548 
7549 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7550                                                  SelectionDAG &DAG) const {
7551   SDLoc dl(Op);
7552   EVT VT = Op.getValueType();
7553   EVT ElemVT = VT.getScalarType();
7554 
7555   SDValue SplatVal = Op.getOperand(0);
7556 
7557   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7558   // FPRs don't have this restriction.
7559   switch (ElemVT.getSimpleVT().SimpleTy) {
7560   case MVT::i1: {
7561     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
7562     // lowering code.
7563     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
7564       if (ConstVal->isOne())
7565         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
7566       // TODO: Add special case for constant false
7567     }
7568     // The general case of i1.  There isn't any natural way to do this,
7569     // so we use some trickery with whilelo.
7570     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7571     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7572                            DAG.getValueType(MVT::i1));
7573     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7574                                        MVT::i64);
7575     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7576                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7577   }
7578   case MVT::i8:
7579   case MVT::i16:
7580   case MVT::i32:
7581     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7582     break;
7583   case MVT::i64:
7584     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7585     break;
7586   case MVT::f16:
7587   case MVT::f32:
7588   case MVT::f64:
7589     // Fine as is
7590     break;
7591   default:
7592     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7593   }
7594 
7595   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7596 }
7597 
7598 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
7599                                              SelectionDAG &DAG) const {
7600   SDLoc DL(Op);
7601 
7602   EVT VT = Op.getValueType();
7603   if (!isTypeLegal(VT) || !VT.isScalableVector())
7604     return SDValue();
7605 
7606   // Current lowering only supports the SVE-ACLE types.
7607   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
7608     return SDValue();
7609 
7610   // The DUPQ operation is indepedent of element type so normalise to i64s.
7611   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
7612   SDValue Idx128 = Op.getOperand(2);
7613 
7614   // DUPQ can be used when idx is in range.
7615   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
7616   if (CIdx && (CIdx->getZExtValue() <= 3)) {
7617     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
7618     SDNode *DUPQ =
7619         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
7620     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
7621   }
7622 
7623   // The ACLE says this must produce the same result as:
7624   //   svtbl(data, svadd_x(svptrue_b64(),
7625   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
7626   //                       index * 2))
7627   SDValue One = DAG.getConstant(1, DL, MVT::i64);
7628   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
7629 
7630   // create the vector 0,1,0,1,...
7631   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
7632   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
7633                            DL, MVT::nxv2i64, Zero, One);
7634   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
7635 
7636   // create the vector idx64,idx64+1,idx64,idx64+1,...
7637   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
7638   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
7639   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
7640 
7641   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
7642   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
7643   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
7644 }
7645 
7646 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7647                                APInt &UndefBits) {
7648   EVT VT = BVN->getValueType(0);
7649   APInt SplatBits, SplatUndef;
7650   unsigned SplatBitSize;
7651   bool HasAnyUndefs;
7652   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7653     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7654 
7655     for (unsigned i = 0; i < NumSplats; ++i) {
7656       CnstBits <<= SplatBitSize;
7657       UndefBits <<= SplatBitSize;
7658       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7659       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7660     }
7661 
7662     return true;
7663   }
7664 
7665   return false;
7666 }
7667 
7668 // Try 64-bit splatted SIMD immediate.
7669 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7670                                  const APInt &Bits) {
7671   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7672     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7673     EVT VT = Op.getValueType();
7674     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7675 
7676     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7677       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7678 
7679       SDLoc dl(Op);
7680       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7681                                 DAG.getConstant(Value, dl, MVT::i32));
7682       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7683     }
7684   }
7685 
7686   return SDValue();
7687 }
7688 
7689 // Try 32-bit splatted SIMD immediate.
7690 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7691                                   const APInt &Bits,
7692                                   const SDValue *LHS = nullptr) {
7693   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7694     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7695     EVT VT = Op.getValueType();
7696     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7697     bool isAdvSIMDModImm = false;
7698     uint64_t Shift;
7699 
7700     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7701       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7702       Shift = 0;
7703     }
7704     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7705       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7706       Shift = 8;
7707     }
7708     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7709       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7710       Shift = 16;
7711     }
7712     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7713       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7714       Shift = 24;
7715     }
7716 
7717     if (isAdvSIMDModImm) {
7718       SDLoc dl(Op);
7719       SDValue Mov;
7720 
7721       if (LHS)
7722         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7723                           DAG.getConstant(Value, dl, MVT::i32),
7724                           DAG.getConstant(Shift, dl, MVT::i32));
7725       else
7726         Mov = DAG.getNode(NewOp, dl, MovTy,
7727                           DAG.getConstant(Value, dl, MVT::i32),
7728                           DAG.getConstant(Shift, dl, MVT::i32));
7729 
7730       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7731     }
7732   }
7733 
7734   return SDValue();
7735 }
7736 
7737 // Try 16-bit splatted SIMD immediate.
7738 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7739                                   const APInt &Bits,
7740                                   const SDValue *LHS = nullptr) {
7741   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7742     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7743     EVT VT = Op.getValueType();
7744     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7745     bool isAdvSIMDModImm = false;
7746     uint64_t Shift;
7747 
7748     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7749       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7750       Shift = 0;
7751     }
7752     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7753       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7754       Shift = 8;
7755     }
7756 
7757     if (isAdvSIMDModImm) {
7758       SDLoc dl(Op);
7759       SDValue Mov;
7760 
7761       if (LHS)
7762         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7763                           DAG.getConstant(Value, dl, MVT::i32),
7764                           DAG.getConstant(Shift, dl, MVT::i32));
7765       else
7766         Mov = DAG.getNode(NewOp, dl, MovTy,
7767                           DAG.getConstant(Value, dl, MVT::i32),
7768                           DAG.getConstant(Shift, dl, MVT::i32));
7769 
7770       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7771     }
7772   }
7773 
7774   return SDValue();
7775 }
7776 
7777 // Try 32-bit splatted SIMD immediate with shifted ones.
7778 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7779                                     SelectionDAG &DAG, const APInt &Bits) {
7780   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7781     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7782     EVT VT = Op.getValueType();
7783     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7784     bool isAdvSIMDModImm = false;
7785     uint64_t Shift;
7786 
7787     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7788       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7789       Shift = 264;
7790     }
7791     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7792       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7793       Shift = 272;
7794     }
7795 
7796     if (isAdvSIMDModImm) {
7797       SDLoc dl(Op);
7798       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7799                                 DAG.getConstant(Value, dl, MVT::i32),
7800                                 DAG.getConstant(Shift, dl, MVT::i32));
7801       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7802     }
7803   }
7804 
7805   return SDValue();
7806 }
7807 
7808 // Try 8-bit splatted SIMD immediate.
7809 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7810                                  const APInt &Bits) {
7811   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7812     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7813     EVT VT = Op.getValueType();
7814     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7815 
7816     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7817       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7818 
7819       SDLoc dl(Op);
7820       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7821                                 DAG.getConstant(Value, dl, MVT::i32));
7822       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7823     }
7824   }
7825 
7826   return SDValue();
7827 }
7828 
7829 // Try FP splatted SIMD immediate.
7830 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7831                                   const APInt &Bits) {
7832   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7833     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7834     EVT VT = Op.getValueType();
7835     bool isWide = (VT.getSizeInBits() == 128);
7836     MVT MovTy;
7837     bool isAdvSIMDModImm = false;
7838 
7839     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7840       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7841       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7842     }
7843     else if (isWide &&
7844              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7845       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7846       MovTy = MVT::v2f64;
7847     }
7848 
7849     if (isAdvSIMDModImm) {
7850       SDLoc dl(Op);
7851       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7852                                 DAG.getConstant(Value, dl, MVT::i32));
7853       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7854     }
7855   }
7856 
7857   return SDValue();
7858 }
7859 
7860 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7861 // consists of only the same constant int value, returned in reference arg
7862 // ConstVal
7863 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7864                                      uint64_t &ConstVal) {
7865   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7866   if (!Bvec)
7867     return false;
7868   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7869   if (!FirstElt)
7870     return false;
7871   EVT VT = Bvec->getValueType(0);
7872   unsigned NumElts = VT.getVectorNumElements();
7873   for (unsigned i = 1; i < NumElts; ++i)
7874     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7875       return false;
7876   ConstVal = FirstElt->getZExtValue();
7877   return true;
7878 }
7879 
7880 static unsigned getIntrinsicID(const SDNode *N) {
7881   unsigned Opcode = N->getOpcode();
7882   switch (Opcode) {
7883   default:
7884     return Intrinsic::not_intrinsic;
7885   case ISD::INTRINSIC_WO_CHAIN: {
7886     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7887     if (IID < Intrinsic::num_intrinsics)
7888       return IID;
7889     return Intrinsic::not_intrinsic;
7890   }
7891   }
7892 }
7893 
7894 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7895 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7896 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7897 // Also, logical shift right -> sri, with the same structure.
7898 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7899   EVT VT = N->getValueType(0);
7900 
7901   if (!VT.isVector())
7902     return SDValue();
7903 
7904   SDLoc DL(N);
7905 
7906   // Is the first op an AND?
7907   const SDValue And = N->getOperand(0);
7908   if (And.getOpcode() != ISD::AND)
7909     return SDValue();
7910 
7911   // Is the second op an shl or lshr?
7912   SDValue Shift = N->getOperand(1);
7913   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7914   // or AArch64ISD::VLSHR vector, #shift
7915   unsigned ShiftOpc = Shift.getOpcode();
7916   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7917     return SDValue();
7918   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7919 
7920   // Is the shift amount constant?
7921   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7922   if (!C2node)
7923     return SDValue();
7924 
7925   // Is the and mask vector all constant?
7926   uint64_t C1;
7927   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7928     return SDValue();
7929 
7930   // Is C1 == ~C2, taking into account how much one can shift elements of a
7931   // particular size?
7932   uint64_t C2 = C2node->getZExtValue();
7933   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7934   if (C2 > ElemSizeInBits)
7935     return SDValue();
7936   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7937   if ((C1 & ElemMask) != (~C2 & ElemMask))
7938     return SDValue();
7939 
7940   SDValue X = And.getOperand(0);
7941   SDValue Y = Shift.getOperand(0);
7942 
7943   unsigned Intrin =
7944       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7945   SDValue ResultSLI =
7946       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7947                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7948                   Shift.getOperand(1));
7949 
7950   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7951   LLVM_DEBUG(N->dump(&DAG));
7952   LLVM_DEBUG(dbgs() << "into: \n");
7953   LLVM_DEBUG(ResultSLI->dump(&DAG));
7954 
7955   ++NumShiftInserts;
7956   return ResultSLI;
7957 }
7958 
7959 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7960                                              SelectionDAG &DAG) const {
7961   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7962   if (EnableAArch64SlrGeneration) {
7963     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7964       return Res;
7965   }
7966 
7967   EVT VT = Op.getValueType();
7968 
7969   SDValue LHS = Op.getOperand(0);
7970   BuildVectorSDNode *BVN =
7971       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7972   if (!BVN) {
7973     // OR commutes, so try swapping the operands.
7974     LHS = Op.getOperand(1);
7975     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7976   }
7977   if (!BVN)
7978     return Op;
7979 
7980   APInt DefBits(VT.getSizeInBits(), 0);
7981   APInt UndefBits(VT.getSizeInBits(), 0);
7982   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7983     SDValue NewOp;
7984 
7985     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7986                                     DefBits, &LHS)) ||
7987         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7988                                     DefBits, &LHS)))
7989       return NewOp;
7990 
7991     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7992                                     UndefBits, &LHS)) ||
7993         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7994                                     UndefBits, &LHS)))
7995       return NewOp;
7996   }
7997 
7998   // We can always fall back to a non-immediate OR.
7999   return Op;
8000 }
8001 
8002 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8003 // be truncated to fit element width.
8004 static SDValue NormalizeBuildVector(SDValue Op,
8005                                     SelectionDAG &DAG) {
8006   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8007   SDLoc dl(Op);
8008   EVT VT = Op.getValueType();
8009   EVT EltTy= VT.getVectorElementType();
8010 
8011   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8012     return Op;
8013 
8014   SmallVector<SDValue, 16> Ops;
8015   for (SDValue Lane : Op->ops()) {
8016     // For integer vectors, type legalization would have promoted the
8017     // operands already. Otherwise, if Op is a floating-point splat
8018     // (with operands cast to integers), then the only possibilities
8019     // are constants and UNDEFs.
8020     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8021       APInt LowBits(EltTy.getSizeInBits(),
8022                     CstLane->getZExtValue());
8023       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8024     } else if (Lane.getNode()->isUndef()) {
8025       Lane = DAG.getUNDEF(MVT::i32);
8026     } else {
8027       assert(Lane.getValueType() == MVT::i32 &&
8028              "Unexpected BUILD_VECTOR operand type");
8029     }
8030     Ops.push_back(Lane);
8031   }
8032   return DAG.getBuildVector(VT, dl, Ops);
8033 }
8034 
8035 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8036   EVT VT = Op.getValueType();
8037 
8038   APInt DefBits(VT.getSizeInBits(), 0);
8039   APInt UndefBits(VT.getSizeInBits(), 0);
8040   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8041   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8042     SDValue NewOp;
8043     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8044         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8045         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8046         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8047         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8048         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8049       return NewOp;
8050 
8051     DefBits = ~DefBits;
8052     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8053         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8054         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8055       return NewOp;
8056 
8057     DefBits = UndefBits;
8058     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8059         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8060         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8061         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8062         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8063         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8064       return NewOp;
8065 
8066     DefBits = ~UndefBits;
8067     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8068         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8069         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8070       return NewOp;
8071   }
8072 
8073   return SDValue();
8074 }
8075 
8076 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8077                                                  SelectionDAG &DAG) const {
8078   EVT VT = Op.getValueType();
8079 
8080   // Try to build a simple constant vector.
8081   Op = NormalizeBuildVector(Op, DAG);
8082   if (VT.isInteger()) {
8083     // Certain vector constants, used to express things like logical NOT and
8084     // arithmetic NEG, are passed through unmodified.  This allows special
8085     // patterns for these operations to match, which will lower these constants
8086     // to whatever is proven necessary.
8087     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8088     if (BVN->isConstant())
8089       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8090         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8091         APInt Val(BitSize,
8092                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8093         if (Val.isNullValue() || Val.isAllOnesValue())
8094           return Op;
8095       }
8096   }
8097 
8098   if (SDValue V = ConstantBuildVector(Op, DAG))
8099     return V;
8100 
8101   // Scan through the operands to find some interesting properties we can
8102   // exploit:
8103   //   1) If only one value is used, we can use a DUP, or
8104   //   2) if only the low element is not undef, we can just insert that, or
8105   //   3) if only one constant value is used (w/ some non-constant lanes),
8106   //      we can splat the constant value into the whole vector then fill
8107   //      in the non-constant lanes.
8108   //   4) FIXME: If different constant values are used, but we can intelligently
8109   //             select the values we'll be overwriting for the non-constant
8110   //             lanes such that we can directly materialize the vector
8111   //             some other way (MOVI, e.g.), we can be sneaky.
8112   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8113   SDLoc dl(Op);
8114   unsigned NumElts = VT.getVectorNumElements();
8115   bool isOnlyLowElement = true;
8116   bool usesOnlyOneValue = true;
8117   bool usesOnlyOneConstantValue = true;
8118   bool isConstant = true;
8119   bool AllLanesExtractElt = true;
8120   unsigned NumConstantLanes = 0;
8121   SDValue Value;
8122   SDValue ConstantValue;
8123   for (unsigned i = 0; i < NumElts; ++i) {
8124     SDValue V = Op.getOperand(i);
8125     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8126       AllLanesExtractElt = false;
8127     if (V.isUndef())
8128       continue;
8129     if (i > 0)
8130       isOnlyLowElement = false;
8131     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8132       isConstant = false;
8133 
8134     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8135       ++NumConstantLanes;
8136       if (!ConstantValue.getNode())
8137         ConstantValue = V;
8138       else if (ConstantValue != V)
8139         usesOnlyOneConstantValue = false;
8140     }
8141 
8142     if (!Value.getNode())
8143       Value = V;
8144     else if (V != Value)
8145       usesOnlyOneValue = false;
8146   }
8147 
8148   if (!Value.getNode()) {
8149     LLVM_DEBUG(
8150         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8151     return DAG.getUNDEF(VT);
8152   }
8153 
8154   // Convert BUILD_VECTOR where all elements but the lowest are undef into
8155   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8156   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8157   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8158     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8159                          "SCALAR_TO_VECTOR node\n");
8160     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8161   }
8162 
8163   if (AllLanesExtractElt) {
8164     SDNode *Vector = nullptr;
8165     bool Even = false;
8166     bool Odd = false;
8167     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8168     // the Odd pattern <1,3,5,...>.
8169     for (unsigned i = 0; i < NumElts; ++i) {
8170       SDValue V = Op.getOperand(i);
8171       const SDNode *N = V.getNode();
8172       if (!isa<ConstantSDNode>(N->getOperand(1)))
8173         break;
8174       SDValue N0 = N->getOperand(0);
8175 
8176       // All elements are extracted from the same vector.
8177       if (!Vector) {
8178         Vector = N0.getNode();
8179         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8180         // BUILD_VECTOR.
8181         if (VT.getVectorElementType() !=
8182             N0.getValueType().getVectorElementType())
8183           break;
8184       } else if (Vector != N0.getNode()) {
8185         Odd = false;
8186         Even = false;
8187         break;
8188       }
8189 
8190       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8191       // indices <1,3,5,...>.
8192       uint64_t Val = N->getConstantOperandVal(1);
8193       if (Val == 2 * i) {
8194         Even = true;
8195         continue;
8196       }
8197       if (Val - 1 == 2 * i) {
8198         Odd = true;
8199         continue;
8200       }
8201 
8202       // Something does not match: abort.
8203       Odd = false;
8204       Even = false;
8205       break;
8206     }
8207     if (Even || Odd) {
8208       SDValue LHS =
8209           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8210                       DAG.getConstant(0, dl, MVT::i64));
8211       SDValue RHS =
8212           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8213                       DAG.getConstant(NumElts, dl, MVT::i64));
8214 
8215       if (Even && !Odd)
8216         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8217                            RHS);
8218       if (Odd && !Even)
8219         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8220                            RHS);
8221     }
8222   }
8223 
8224   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8225   // i32 and try again.
8226   if (usesOnlyOneValue) {
8227     if (!isConstant) {
8228       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8229           Value.getValueType() != VT) {
8230         LLVM_DEBUG(
8231             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8232         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8233       }
8234 
8235       // This is actually a DUPLANExx operation, which keeps everything vectory.
8236 
8237       SDValue Lane = Value.getOperand(1);
8238       Value = Value.getOperand(0);
8239       if (Value.getValueSizeInBits() == 64) {
8240         LLVM_DEBUG(
8241             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8242                       "widening it\n");
8243         Value = WidenVector(Value, DAG);
8244       }
8245 
8246       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8247       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8248     }
8249 
8250     if (VT.getVectorElementType().isFloatingPoint()) {
8251       SmallVector<SDValue, 8> Ops;
8252       EVT EltTy = VT.getVectorElementType();
8253       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
8254               "Unsupported floating-point vector type");
8255       LLVM_DEBUG(
8256           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8257                     "BITCASTS, and try again\n");
8258       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8259       for (unsigned i = 0; i < NumElts; ++i)
8260         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8261       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8262       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8263       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8264                  Val.dump(););
8265       Val = LowerBUILD_VECTOR(Val, DAG);
8266       if (Val.getNode())
8267         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8268     }
8269   }
8270 
8271   // If there was only one constant value used and for more than one lane,
8272   // start by splatting that value, then replace the non-constant lanes. This
8273   // is better than the default, which will perform a separate initialization
8274   // for each lane.
8275   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8276     // Firstly, try to materialize the splat constant.
8277     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8278             Val = ConstantBuildVector(Vec, DAG);
8279     if (!Val) {
8280       // Otherwise, materialize the constant and splat it.
8281       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8282       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8283     }
8284 
8285     // Now insert the non-constant lanes.
8286     for (unsigned i = 0; i < NumElts; ++i) {
8287       SDValue V = Op.getOperand(i);
8288       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8289       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8290         // Note that type legalization likely mucked about with the VT of the
8291         // source operand, so we may have to convert it here before inserting.
8292         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8293     }
8294     return Val;
8295   }
8296 
8297   // This will generate a load from the constant pool.
8298   if (isConstant) {
8299     LLVM_DEBUG(
8300         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8301                   "expansion\n");
8302     return SDValue();
8303   }
8304 
8305   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8306   if (NumElts >= 4) {
8307     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8308       return shuffle;
8309   }
8310 
8311   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8312   // know the default expansion would otherwise fall back on something even
8313   // worse. For a vector with one or two non-undef values, that's
8314   // scalar_to_vector for the elements followed by a shuffle (provided the
8315   // shuffle is valid for the target) and materialization element by element
8316   // on the stack followed by a load for everything else.
8317   if (!isConstant && !usesOnlyOneValue) {
8318     LLVM_DEBUG(
8319         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8320                   "of INSERT_VECTOR_ELT\n");
8321 
8322     SDValue Vec = DAG.getUNDEF(VT);
8323     SDValue Op0 = Op.getOperand(0);
8324     unsigned i = 0;
8325 
8326     // Use SCALAR_TO_VECTOR for lane zero to
8327     // a) Avoid a RMW dependency on the full vector register, and
8328     // b) Allow the register coalescer to fold away the copy if the
8329     //    value is already in an S or D register, and we're forced to emit an
8330     //    INSERT_SUBREG that we can't fold anywhere.
8331     //
8332     // We also allow types like i8 and i16 which are illegal scalar but legal
8333     // vector element types. After type-legalization the inserted value is
8334     // extended (i32) and it is safe to cast them to the vector type by ignoring
8335     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8336     if (!Op0.isUndef()) {
8337       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8338       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8339       ++i;
8340     }
8341     LLVM_DEBUG(if (i < NumElts) dbgs()
8342                    << "Creating nodes for the other vector elements:\n";);
8343     for (; i < NumElts; ++i) {
8344       SDValue V = Op.getOperand(i);
8345       if (V.isUndef())
8346         continue;
8347       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8348       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8349     }
8350     return Vec;
8351   }
8352 
8353   LLVM_DEBUG(
8354       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8355                 "better alternative\n");
8356   return SDValue();
8357 }
8358 
8359 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8360                                                       SelectionDAG &DAG) const {
8361   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8362 
8363   // Check for non-constant or out of range lane.
8364   EVT VT = Op.getOperand(0).getValueType();
8365   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8366   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8367     return SDValue();
8368 
8369 
8370   // Insertion/extraction are legal for V128 types.
8371   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8372       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8373       VT == MVT::v8f16)
8374     return Op;
8375 
8376   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8377       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8378     return SDValue();
8379 
8380   // For V64 types, we perform insertion by expanding the value
8381   // to a V128 type and perform the insertion on that.
8382   SDLoc DL(Op);
8383   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8384   EVT WideTy = WideVec.getValueType();
8385 
8386   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8387                              Op.getOperand(1), Op.getOperand(2));
8388   // Re-narrow the resultant vector.
8389   return NarrowVector(Node, DAG);
8390 }
8391 
8392 SDValue
8393 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8394                                                SelectionDAG &DAG) const {
8395   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8396 
8397   // Check for non-constant or out of range lane.
8398   EVT VT = Op.getOperand(0).getValueType();
8399   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8400   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8401     return SDValue();
8402 
8403 
8404   // Insertion/extraction are legal for V128 types.
8405   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8406       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8407       VT == MVT::v8f16)
8408     return Op;
8409 
8410   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8411       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8412     return SDValue();
8413 
8414   // For V64 types, we perform extraction by expanding the value
8415   // to a V128 type and perform the extraction on that.
8416   SDLoc DL(Op);
8417   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8418   EVT WideTy = WideVec.getValueType();
8419 
8420   EVT ExtrTy = WideTy.getVectorElementType();
8421   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8422     ExtrTy = MVT::i32;
8423 
8424   // For extractions, we just return the result directly.
8425   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8426                      Op.getOperand(1));
8427 }
8428 
8429 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8430                                                       SelectionDAG &DAG) const {
8431   EVT VT = Op.getOperand(0).getValueType();
8432   SDLoc dl(Op);
8433   // Just in case...
8434   if (!VT.isVector())
8435     return SDValue();
8436 
8437   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8438   if (!Cst)
8439     return SDValue();
8440   unsigned Val = Cst->getZExtValue();
8441 
8442   unsigned Size = Op.getValueSizeInBits();
8443 
8444   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8445   if (Val == 0)
8446     return Op;
8447 
8448   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8449   // that directly.
8450   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8451     return Op;
8452 
8453   return SDValue();
8454 }
8455 
8456 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8457   if (VT.getVectorNumElements() == 4 &&
8458       (VT.is128BitVector() || VT.is64BitVector())) {
8459     unsigned PFIndexes[4];
8460     for (unsigned i = 0; i != 4; ++i) {
8461       if (M[i] < 0)
8462         PFIndexes[i] = 8;
8463       else
8464         PFIndexes[i] = M[i];
8465     }
8466 
8467     // Compute the index in the perfect shuffle table.
8468     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8469                             PFIndexes[2] * 9 + PFIndexes[3];
8470     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8471     unsigned Cost = (PFEntry >> 30);
8472 
8473     if (Cost <= 4)
8474       return true;
8475   }
8476 
8477   bool DummyBool;
8478   int DummyInt;
8479   unsigned DummyUnsigned;
8480 
8481   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8482           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8483           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8484           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8485           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8486           isZIPMask(M, VT, DummyUnsigned) ||
8487           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8488           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8489           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8490           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8491           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8492 }
8493 
8494 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8495 /// operand of a vector shift operation, where all the elements of the
8496 /// build_vector must have the same constant integer value.
8497 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8498   // Ignore bit_converts.
8499   while (Op.getOpcode() == ISD::BITCAST)
8500     Op = Op.getOperand(0);
8501   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8502   APInt SplatBits, SplatUndef;
8503   unsigned SplatBitSize;
8504   bool HasAnyUndefs;
8505   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8506                                     HasAnyUndefs, ElementBits) ||
8507       SplatBitSize > ElementBits)
8508     return false;
8509   Cnt = SplatBits.getSExtValue();
8510   return true;
8511 }
8512 
8513 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8514 /// operand of a vector shift left operation.  That value must be in the range:
8515 ///   0 <= Value < ElementBits for a left shift; or
8516 ///   0 <= Value <= ElementBits for a long left shift.
8517 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8518   assert(VT.isVector() && "vector shift count is not a vector type");
8519   int64_t ElementBits = VT.getScalarSizeInBits();
8520   if (!getVShiftImm(Op, ElementBits, Cnt))
8521     return false;
8522   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8523 }
8524 
8525 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8526 /// operand of a vector shift right operation. The value must be in the range:
8527 ///   1 <= Value <= ElementBits for a right shift; or
8528 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8529   assert(VT.isVector() && "vector shift count is not a vector type");
8530   int64_t ElementBits = VT.getScalarSizeInBits();
8531   if (!getVShiftImm(Op, ElementBits, Cnt))
8532     return false;
8533   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8534 }
8535 
8536 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8537                                                       SelectionDAG &DAG) const {
8538   EVT VT = Op.getValueType();
8539   SDLoc DL(Op);
8540   int64_t Cnt;
8541 
8542   if (!Op.getOperand(1).getValueType().isVector())
8543     return Op;
8544   unsigned EltSize = VT.getScalarSizeInBits();
8545 
8546   switch (Op.getOpcode()) {
8547   default:
8548     llvm_unreachable("unexpected shift opcode");
8549 
8550   case ISD::SHL:
8551     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8552       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8553                          DAG.getConstant(Cnt, DL, MVT::i32));
8554     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8555                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8556                                        MVT::i32),
8557                        Op.getOperand(0), Op.getOperand(1));
8558   case ISD::SRA:
8559   case ISD::SRL:
8560     // Right shift immediate
8561     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8562       unsigned Opc =
8563           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8564       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8565                          DAG.getConstant(Cnt, DL, MVT::i32));
8566     }
8567 
8568     // Right shift register.  Note, there is not a shift right register
8569     // instruction, but the shift left register instruction takes a signed
8570     // value, where negative numbers specify a right shift.
8571     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8572                                                 : Intrinsic::aarch64_neon_ushl;
8573     // negate the shift amount
8574     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8575     SDValue NegShiftLeft =
8576         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8577                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8578                     NegShift);
8579     return NegShiftLeft;
8580   }
8581 
8582   return SDValue();
8583 }
8584 
8585 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8586                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8587                                     const SDLoc &dl, SelectionDAG &DAG) {
8588   EVT SrcVT = LHS.getValueType();
8589   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8590          "function only supposed to emit natural comparisons");
8591 
8592   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8593   APInt CnstBits(VT.getSizeInBits(), 0);
8594   APInt UndefBits(VT.getSizeInBits(), 0);
8595   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8596   bool IsZero = IsCnst && (CnstBits == 0);
8597 
8598   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8599     switch (CC) {
8600     default:
8601       return SDValue();
8602     case AArch64CC::NE: {
8603       SDValue Fcmeq;
8604       if (IsZero)
8605         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8606       else
8607         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8608       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8609     }
8610     case AArch64CC::EQ:
8611       if (IsZero)
8612         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8613       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8614     case AArch64CC::GE:
8615       if (IsZero)
8616         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8617       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8618     case AArch64CC::GT:
8619       if (IsZero)
8620         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8621       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8622     case AArch64CC::LS:
8623       if (IsZero)
8624         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8625       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8626     case AArch64CC::LT:
8627       if (!NoNans)
8628         return SDValue();
8629       // If we ignore NaNs then we can use to the MI implementation.
8630       LLVM_FALLTHROUGH;
8631     case AArch64CC::MI:
8632       if (IsZero)
8633         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8634       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8635     }
8636   }
8637 
8638   switch (CC) {
8639   default:
8640     return SDValue();
8641   case AArch64CC::NE: {
8642     SDValue Cmeq;
8643     if (IsZero)
8644       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8645     else
8646       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8647     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8648   }
8649   case AArch64CC::EQ:
8650     if (IsZero)
8651       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8652     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8653   case AArch64CC::GE:
8654     if (IsZero)
8655       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8656     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8657   case AArch64CC::GT:
8658     if (IsZero)
8659       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8660     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8661   case AArch64CC::LE:
8662     if (IsZero)
8663       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8664     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8665   case AArch64CC::LS:
8666     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8667   case AArch64CC::LO:
8668     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8669   case AArch64CC::LT:
8670     if (IsZero)
8671       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8672     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8673   case AArch64CC::HI:
8674     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8675   case AArch64CC::HS:
8676     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8677   }
8678 }
8679 
8680 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8681                                            SelectionDAG &DAG) const {
8682   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8683   SDValue LHS = Op.getOperand(0);
8684   SDValue RHS = Op.getOperand(1);
8685   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8686   SDLoc dl(Op);
8687 
8688   if (LHS.getValueType().getVectorElementType().isInteger()) {
8689     assert(LHS.getValueType() == RHS.getValueType());
8690     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8691     SDValue Cmp =
8692         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8693     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8694   }
8695 
8696   const bool FullFP16 =
8697     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8698 
8699   // Make v4f16 (only) fcmp operations utilise vector instructions
8700   // v8f16 support will be a litle more complicated
8701   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8702     if (LHS.getValueType().getVectorNumElements() == 4) {
8703       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8704       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8705       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8706       DAG.ReplaceAllUsesWith(Op, NewSetcc);
8707       CmpVT = MVT::v4i32;
8708     } else
8709       return SDValue();
8710   }
8711 
8712   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8713           LHS.getValueType().getVectorElementType() != MVT::f128);
8714 
8715   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8716   // clean.  Some of them require two branches to implement.
8717   AArch64CC::CondCode CC1, CC2;
8718   bool ShouldInvert;
8719   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8720 
8721   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8722   SDValue Cmp =
8723       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8724   if (!Cmp.getNode())
8725     return SDValue();
8726 
8727   if (CC2 != AArch64CC::AL) {
8728     SDValue Cmp2 =
8729         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8730     if (!Cmp2.getNode())
8731       return SDValue();
8732 
8733     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8734   }
8735 
8736   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8737 
8738   if (ShouldInvert)
8739     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8740 
8741   return Cmp;
8742 }
8743 
8744 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8745                                   SelectionDAG &DAG) {
8746   SDValue VecOp = ScalarOp.getOperand(0);
8747   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8748   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8749                      DAG.getConstant(0, DL, MVT::i64));
8750 }
8751 
8752 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8753                                               SelectionDAG &DAG) const {
8754   SDLoc dl(Op);
8755   switch (Op.getOpcode()) {
8756   case ISD::VECREDUCE_ADD:
8757     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8758   case ISD::VECREDUCE_SMAX:
8759     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8760   case ISD::VECREDUCE_SMIN:
8761     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8762   case ISD::VECREDUCE_UMAX:
8763     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8764   case ISD::VECREDUCE_UMIN:
8765     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8766   case ISD::VECREDUCE_FMAX: {
8767     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8768     return DAG.getNode(
8769         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8770         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8771         Op.getOperand(0));
8772   }
8773   case ISD::VECREDUCE_FMIN: {
8774     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8775     return DAG.getNode(
8776         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8777         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8778         Op.getOperand(0));
8779   }
8780   default:
8781     llvm_unreachable("Unhandled reduction");
8782   }
8783 }
8784 
8785 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8786                                                     SelectionDAG &DAG) const {
8787   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8788   if (!Subtarget.hasLSE())
8789     return SDValue();
8790 
8791   // LSE has an atomic load-add instruction, but not a load-sub.
8792   SDLoc dl(Op);
8793   MVT VT = Op.getSimpleValueType();
8794   SDValue RHS = Op.getOperand(2);
8795   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8796   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8797   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8798                        Op.getOperand(0), Op.getOperand(1), RHS,
8799                        AN->getMemOperand());
8800 }
8801 
8802 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8803                                                     SelectionDAG &DAG) const {
8804   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8805   if (!Subtarget.hasLSE())
8806     return SDValue();
8807 
8808   // LSE has an atomic load-clear instruction, but not a load-and.
8809   SDLoc dl(Op);
8810   MVT VT = Op.getSimpleValueType();
8811   SDValue RHS = Op.getOperand(2);
8812   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8813   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8814   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8815                        Op.getOperand(0), Op.getOperand(1), RHS,
8816                        AN->getMemOperand());
8817 }
8818 
8819 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8820     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8821   SDLoc dl(Op);
8822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8823   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8824 
8825   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8826   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8827   if (Subtarget->hasCustomCallingConv())
8828     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8829 
8830   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8831                      DAG.getConstant(4, dl, MVT::i64));
8832   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8833   Chain =
8834       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8835                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8836                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8837   // To match the actual intent better, we should read the output from X15 here
8838   // again (instead of potentially spilling it to the stack), but rereading Size
8839   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8840   // here.
8841 
8842   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8843                      DAG.getConstant(4, dl, MVT::i64));
8844   return Chain;
8845 }
8846 
8847 SDValue
8848 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8849                                                SelectionDAG &DAG) const {
8850   assert(Subtarget->isTargetWindows() &&
8851          "Only Windows alloca probing supported");
8852   SDLoc dl(Op);
8853   // Get the inputs.
8854   SDNode *Node = Op.getNode();
8855   SDValue Chain = Op.getOperand(0);
8856   SDValue Size = Op.getOperand(1);
8857   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8858   EVT VT = Node->getValueType(0);
8859 
8860   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8861           "no-stack-arg-probe")) {
8862     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8863     Chain = SP.getValue(1);
8864     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8865     if (Align)
8866       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8867                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8868     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8869     SDValue Ops[2] = {SP, Chain};
8870     return DAG.getMergeValues(Ops, dl);
8871   }
8872 
8873   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8874 
8875   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8876 
8877   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8878   Chain = SP.getValue(1);
8879   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8880   if (Align)
8881     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8882                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8883   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8884 
8885   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8886                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8887 
8888   SDValue Ops[2] = {SP, Chain};
8889   return DAG.getMergeValues(Ops, dl);
8890 }
8891 
8892 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
8893                                            SelectionDAG &DAG) const {
8894   EVT VT = Op.getValueType();
8895   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
8896 
8897   SDLoc DL(Op);
8898   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
8899   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
8900                             DL, VT);
8901 }
8902 
8903 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8904 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8905 /// specified in the intrinsic calls.
8906 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8907                                                const CallInst &I,
8908                                                MachineFunction &MF,
8909                                                unsigned Intrinsic) const {
8910   auto &DL = I.getModule()->getDataLayout();
8911   switch (Intrinsic) {
8912   case Intrinsic::aarch64_neon_ld2:
8913   case Intrinsic::aarch64_neon_ld3:
8914   case Intrinsic::aarch64_neon_ld4:
8915   case Intrinsic::aarch64_neon_ld1x2:
8916   case Intrinsic::aarch64_neon_ld1x3:
8917   case Intrinsic::aarch64_neon_ld1x4:
8918   case Intrinsic::aarch64_neon_ld2lane:
8919   case Intrinsic::aarch64_neon_ld3lane:
8920   case Intrinsic::aarch64_neon_ld4lane:
8921   case Intrinsic::aarch64_neon_ld2r:
8922   case Intrinsic::aarch64_neon_ld3r:
8923   case Intrinsic::aarch64_neon_ld4r: {
8924     Info.opc = ISD::INTRINSIC_W_CHAIN;
8925     // Conservatively set memVT to the entire set of vectors loaded.
8926     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8927     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8928     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8929     Info.offset = 0;
8930     Info.align.reset();
8931     // volatile loads with NEON intrinsics not supported
8932     Info.flags = MachineMemOperand::MOLoad;
8933     return true;
8934   }
8935   case Intrinsic::aarch64_neon_st2:
8936   case Intrinsic::aarch64_neon_st3:
8937   case Intrinsic::aarch64_neon_st4:
8938   case Intrinsic::aarch64_neon_st1x2:
8939   case Intrinsic::aarch64_neon_st1x3:
8940   case Intrinsic::aarch64_neon_st1x4:
8941   case Intrinsic::aarch64_neon_st2lane:
8942   case Intrinsic::aarch64_neon_st3lane:
8943   case Intrinsic::aarch64_neon_st4lane: {
8944     Info.opc = ISD::INTRINSIC_VOID;
8945     // Conservatively set memVT to the entire set of vectors stored.
8946     unsigned NumElts = 0;
8947     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8948       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8949       if (!ArgTy->isVectorTy())
8950         break;
8951       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8952     }
8953     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8954     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8955     Info.offset = 0;
8956     Info.align.reset();
8957     // volatile stores with NEON intrinsics not supported
8958     Info.flags = MachineMemOperand::MOStore;
8959     return true;
8960   }
8961   case Intrinsic::aarch64_ldaxr:
8962   case Intrinsic::aarch64_ldxr: {
8963     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8964     Info.opc = ISD::INTRINSIC_W_CHAIN;
8965     Info.memVT = MVT::getVT(PtrTy->getElementType());
8966     Info.ptrVal = I.getArgOperand(0);
8967     Info.offset = 0;
8968     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8969     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8970     return true;
8971   }
8972   case Intrinsic::aarch64_stlxr:
8973   case Intrinsic::aarch64_stxr: {
8974     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8975     Info.opc = ISD::INTRINSIC_W_CHAIN;
8976     Info.memVT = MVT::getVT(PtrTy->getElementType());
8977     Info.ptrVal = I.getArgOperand(1);
8978     Info.offset = 0;
8979     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8980     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8981     return true;
8982   }
8983   case Intrinsic::aarch64_ldaxp:
8984   case Intrinsic::aarch64_ldxp:
8985     Info.opc = ISD::INTRINSIC_W_CHAIN;
8986     Info.memVT = MVT::i128;
8987     Info.ptrVal = I.getArgOperand(0);
8988     Info.offset = 0;
8989     Info.align = Align(16);
8990     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8991     return true;
8992   case Intrinsic::aarch64_stlxp:
8993   case Intrinsic::aarch64_stxp:
8994     Info.opc = ISD::INTRINSIC_W_CHAIN;
8995     Info.memVT = MVT::i128;
8996     Info.ptrVal = I.getArgOperand(2);
8997     Info.offset = 0;
8998     Info.align = Align(16);
8999     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9000     return true;
9001   case Intrinsic::aarch64_sve_ld1:
9002   case Intrinsic::aarch64_sve_ldnt1: {
9003     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9004     Info.opc = ISD::INTRINSIC_W_CHAIN;
9005     Info.memVT = MVT::getVT(I.getType());
9006     Info.ptrVal = I.getArgOperand(1);
9007     Info.offset = 0;
9008     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
9009     Info.flags = MachineMemOperand::MOLoad;
9010     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9011       Info.flags |= MachineMemOperand::MONonTemporal;
9012     return true;
9013   }
9014   case Intrinsic::aarch64_sve_st1:
9015   case Intrinsic::aarch64_sve_stnt1: {
9016     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9017     Info.opc = ISD::INTRINSIC_W_CHAIN;
9018     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9019     Info.ptrVal = I.getArgOperand(2);
9020     Info.offset = 0;
9021     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
9022     Info.flags = MachineMemOperand::MOStore;
9023     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9024       Info.flags |= MachineMemOperand::MONonTemporal;
9025     return true;
9026   }
9027   default:
9028     break;
9029   }
9030 
9031   return false;
9032 }
9033 
9034 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9035                                                   ISD::LoadExtType ExtTy,
9036                                                   EVT NewVT) const {
9037   // TODO: This may be worth removing. Check regression tests for diffs.
9038   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9039     return false;
9040 
9041   // If we're reducing the load width in order to avoid having to use an extra
9042   // instruction to do extension then it's probably a good idea.
9043   if (ExtTy != ISD::NON_EXTLOAD)
9044     return true;
9045   // Don't reduce load width if it would prevent us from combining a shift into
9046   // the offset.
9047   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9048   assert(Mem);
9049   const SDValue &Base = Mem->getBasePtr();
9050   if (Base.getOpcode() == ISD::ADD &&
9051       Base.getOperand(1).getOpcode() == ISD::SHL &&
9052       Base.getOperand(1).hasOneUse() &&
9053       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9054     // The shift can be combined if it matches the size of the value being
9055     // loaded (and so reducing the width would make it not match).
9056     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9057     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9058     if (ShiftAmount == Log2_32(LoadBytes))
9059       return false;
9060   }
9061   // We have no reason to disallow reducing the load width, so allow it.
9062   return true;
9063 }
9064 
9065 // Truncations from 64-bit GPR to 32-bit GPR is free.
9066 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9067   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9068     return false;
9069   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9070   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9071   return NumBits1 > NumBits2;
9072 }
9073 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9074   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9075     return false;
9076   unsigned NumBits1 = VT1.getSizeInBits();
9077   unsigned NumBits2 = VT2.getSizeInBits();
9078   return NumBits1 > NumBits2;
9079 }
9080 
9081 /// Check if it is profitable to hoist instruction in then/else to if.
9082 /// Not profitable if I and it's user can form a FMA instruction
9083 /// because we prefer FMSUB/FMADD.
9084 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9085   if (I->getOpcode() != Instruction::FMul)
9086     return true;
9087 
9088   if (!I->hasOneUse())
9089     return true;
9090 
9091   Instruction *User = I->user_back();
9092 
9093   if (User &&
9094       !(User->getOpcode() == Instruction::FSub ||
9095         User->getOpcode() == Instruction::FAdd))
9096     return true;
9097 
9098   const TargetOptions &Options = getTargetMachine().Options;
9099   const Function *F = I->getFunction();
9100   const DataLayout &DL = F->getParent()->getDataLayout();
9101   Type *Ty = User->getOperand(0)->getType();
9102 
9103   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9104            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9105            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9106             Options.UnsafeFPMath));
9107 }
9108 
9109 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9110 // 64-bit GPR.
9111 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9112   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9113     return false;
9114   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9115   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9116   return NumBits1 == 32 && NumBits2 == 64;
9117 }
9118 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9119   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9120     return false;
9121   unsigned NumBits1 = VT1.getSizeInBits();
9122   unsigned NumBits2 = VT2.getSizeInBits();
9123   return NumBits1 == 32 && NumBits2 == 64;
9124 }
9125 
9126 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9127   EVT VT1 = Val.getValueType();
9128   if (isZExtFree(VT1, VT2)) {
9129     return true;
9130   }
9131 
9132   if (Val.getOpcode() != ISD::LOAD)
9133     return false;
9134 
9135   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9136   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9137           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9138           VT1.getSizeInBits() <= 32);
9139 }
9140 
9141 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9142   if (isa<FPExtInst>(Ext))
9143     return false;
9144 
9145   // Vector types are not free.
9146   if (Ext->getType()->isVectorTy())
9147     return false;
9148 
9149   for (const Use &U : Ext->uses()) {
9150     // The extension is free if we can fold it with a left shift in an
9151     // addressing mode or an arithmetic operation: add, sub, and cmp.
9152 
9153     // Is there a shift?
9154     const Instruction *Instr = cast<Instruction>(U.getUser());
9155 
9156     // Is this a constant shift?
9157     switch (Instr->getOpcode()) {
9158     case Instruction::Shl:
9159       if (!isa<ConstantInt>(Instr->getOperand(1)))
9160         return false;
9161       break;
9162     case Instruction::GetElementPtr: {
9163       gep_type_iterator GTI = gep_type_begin(Instr);
9164       auto &DL = Ext->getModule()->getDataLayout();
9165       std::advance(GTI, U.getOperandNo()-1);
9166       Type *IdxTy = GTI.getIndexedType();
9167       // This extension will end up with a shift because of the scaling factor.
9168       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9169       // Get the shift amount based on the scaling factor:
9170       // log2(sizeof(IdxTy)) - log2(8).
9171       uint64_t ShiftAmt =
9172         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9173       // Is the constant foldable in the shift of the addressing mode?
9174       // I.e., shift amount is between 1 and 4 inclusive.
9175       if (ShiftAmt == 0 || ShiftAmt > 4)
9176         return false;
9177       break;
9178     }
9179     case Instruction::Trunc:
9180       // Check if this is a noop.
9181       // trunc(sext ty1 to ty2) to ty1.
9182       if (Instr->getType() == Ext->getOperand(0)->getType())
9183         continue;
9184       LLVM_FALLTHROUGH;
9185     default:
9186       return false;
9187     }
9188 
9189     // At this point we can use the bfm family, so this extension is free
9190     // for that use.
9191   }
9192   return true;
9193 }
9194 
9195 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9196 /// or upper half of the vector elements.
9197 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9198   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9199     auto *FullVT = cast<VectorType>(FullV->getType());
9200     auto *HalfVT = cast<VectorType>(HalfV->getType());
9201     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
9202   };
9203 
9204   auto extractHalf = [](Value *FullV, Value *HalfV) {
9205     auto *FullVT = cast<VectorType>(FullV->getType());
9206     auto *HalfVT = cast<VectorType>(HalfV->getType());
9207     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9208   };
9209 
9210   ArrayRef<int> M1, M2;
9211   Value *S1Op1, *S2Op1;
9212   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9213       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9214     return false;
9215 
9216   // Check that the operands are half as wide as the result and we extract
9217   // half of the elements of the input vectors.
9218   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9219       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9220     return false;
9221 
9222   // Check the mask extracts either the lower or upper half of vector
9223   // elements.
9224   int M1Start = -1;
9225   int M2Start = -1;
9226   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
9227   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9228       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9229       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9230     return false;
9231 
9232   return true;
9233 }
9234 
9235 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9236 /// of the vector elements.
9237 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9238   auto areExtDoubled = [](Instruction *Ext) {
9239     return Ext->getType()->getScalarSizeInBits() ==
9240            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9241   };
9242 
9243   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9244       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9245       !areExtDoubled(cast<Instruction>(Ext1)) ||
9246       !areExtDoubled(cast<Instruction>(Ext2)))
9247     return false;
9248 
9249   return true;
9250 }
9251 
9252 /// Check if sinking \p I's operands to I's basic block is profitable, because
9253 /// the operands can be folded into a target instruction, e.g.
9254 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9255 bool AArch64TargetLowering::shouldSinkOperands(
9256     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9257   if (!I->getType()->isVectorTy())
9258     return false;
9259 
9260   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9261     switch (II->getIntrinsicID()) {
9262     case Intrinsic::aarch64_neon_umull:
9263       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9264         return false;
9265       Ops.push_back(&II->getOperandUse(0));
9266       Ops.push_back(&II->getOperandUse(1));
9267       return true;
9268     default:
9269       return false;
9270     }
9271   }
9272 
9273   switch (I->getOpcode()) {
9274   case Instruction::Sub:
9275   case Instruction::Add: {
9276     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9277       return false;
9278 
9279     // If the exts' operands extract either the lower or upper elements, we
9280     // can sink them too.
9281     auto Ext1 = cast<Instruction>(I->getOperand(0));
9282     auto Ext2 = cast<Instruction>(I->getOperand(1));
9283     if (areExtractShuffleVectors(Ext1, Ext2)) {
9284       Ops.push_back(&Ext1->getOperandUse(0));
9285       Ops.push_back(&Ext2->getOperandUse(0));
9286     }
9287 
9288     Ops.push_back(&I->getOperandUse(0));
9289     Ops.push_back(&I->getOperandUse(1));
9290 
9291     return true;
9292   }
9293   default:
9294     return false;
9295   }
9296   return false;
9297 }
9298 
9299 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9300                                           unsigned &RequiredAligment) const {
9301   if (!LoadedType.isSimple() ||
9302       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9303     return false;
9304   // Cyclone supports unaligned accesses.
9305   RequiredAligment = 0;
9306   unsigned NumBits = LoadedType.getSizeInBits();
9307   return NumBits == 32 || NumBits == 64;
9308 }
9309 
9310 /// A helper function for determining the number of interleaved accesses we
9311 /// will generate when lowering accesses of the given type.
9312 unsigned
9313 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9314                                                  const DataLayout &DL) const {
9315   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9316 }
9317 
9318 MachineMemOperand::Flags
9319 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9320   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9321       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9322     return MOStridedAccess;
9323   return MachineMemOperand::MONone;
9324 }
9325 
9326 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9327     VectorType *VecTy, const DataLayout &DL) const {
9328 
9329   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9330   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9331 
9332   // Ensure the number of vector elements is greater than 1.
9333   if (VecTy->getNumElements() < 2)
9334     return false;
9335 
9336   // Ensure the element type is legal.
9337   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9338     return false;
9339 
9340   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9341   // 128 will be split into multiple interleaved accesses.
9342   return VecSize == 64 || VecSize % 128 == 0;
9343 }
9344 
9345 /// Lower an interleaved load into a ldN intrinsic.
9346 ///
9347 /// E.g. Lower an interleaved load (Factor = 2):
9348 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9349 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9350 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9351 ///
9352 ///      Into:
9353 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9354 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9355 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9356 bool AArch64TargetLowering::lowerInterleavedLoad(
9357     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9358     ArrayRef<unsigned> Indices, unsigned Factor) const {
9359   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9360          "Invalid interleave factor");
9361   assert(!Shuffles.empty() && "Empty shufflevector input");
9362   assert(Shuffles.size() == Indices.size() &&
9363          "Unmatched number of shufflevectors and indices");
9364 
9365   const DataLayout &DL = LI->getModule()->getDataLayout();
9366 
9367   VectorType *VecTy = Shuffles[0]->getType();
9368 
9369   // Skip if we do not have NEON and skip illegal vector types. We can
9370   // "legalize" wide vector types into multiple interleaved accesses as long as
9371   // the vector types are divisible by 128.
9372   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9373     return false;
9374 
9375   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9376 
9377   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9378   // load integer vectors first and then convert to pointer vectors.
9379   Type *EltTy = VecTy->getVectorElementType();
9380   if (EltTy->isPointerTy())
9381     VecTy =
9382         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
9383 
9384   IRBuilder<> Builder(LI);
9385 
9386   // The base address of the load.
9387   Value *BaseAddr = LI->getPointerOperand();
9388 
9389   if (NumLoads > 1) {
9390     // If we're going to generate more than one load, reset the sub-vector type
9391     // to something legal.
9392     VecTy = VectorType::get(VecTy->getVectorElementType(),
9393                             VecTy->getVectorNumElements() / NumLoads);
9394 
9395     // We will compute the pointer operand of each load from the original base
9396     // address using GEPs. Cast the base address to a pointer to the scalar
9397     // element type.
9398     BaseAddr = Builder.CreateBitCast(
9399         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
9400                       LI->getPointerAddressSpace()));
9401   }
9402 
9403   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9404   Type *Tys[2] = {VecTy, PtrTy};
9405   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9406                                             Intrinsic::aarch64_neon_ld3,
9407                                             Intrinsic::aarch64_neon_ld4};
9408   Function *LdNFunc =
9409       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9410 
9411   // Holds sub-vectors extracted from the load intrinsic return values. The
9412   // sub-vectors are associated with the shufflevector instructions they will
9413   // replace.
9414   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9415 
9416   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9417 
9418     // If we're generating more than one load, compute the base address of
9419     // subsequent loads as an offset from the previous.
9420     if (LoadCount > 0)
9421       BaseAddr =
9422           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
9423                                      VecTy->getVectorNumElements() * Factor);
9424 
9425     CallInst *LdN = Builder.CreateCall(
9426         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9427 
9428     // Extract and store the sub-vectors returned by the load intrinsic.
9429     for (unsigned i = 0; i < Shuffles.size(); i++) {
9430       ShuffleVectorInst *SVI = Shuffles[i];
9431       unsigned Index = Indices[i];
9432 
9433       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9434 
9435       // Convert the integer vector to pointer vector if the element is pointer.
9436       if (EltTy->isPointerTy())
9437         SubVec = Builder.CreateIntToPtr(
9438             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
9439                                     VecTy->getVectorNumElements()));
9440       SubVecs[SVI].push_back(SubVec);
9441     }
9442   }
9443 
9444   // Replace uses of the shufflevector instructions with the sub-vectors
9445   // returned by the load intrinsic. If a shufflevector instruction is
9446   // associated with more than one sub-vector, those sub-vectors will be
9447   // concatenated into a single wide vector.
9448   for (ShuffleVectorInst *SVI : Shuffles) {
9449     auto &SubVec = SubVecs[SVI];
9450     auto *WideVec =
9451         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9452     SVI->replaceAllUsesWith(WideVec);
9453   }
9454 
9455   return true;
9456 }
9457 
9458 /// Lower an interleaved store into a stN intrinsic.
9459 ///
9460 /// E.g. Lower an interleaved store (Factor = 3):
9461 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9462 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9463 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9464 ///
9465 ///      Into:
9466 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9467 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9468 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9469 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9470 ///
9471 /// Note that the new shufflevectors will be removed and we'll only generate one
9472 /// st3 instruction in CodeGen.
9473 ///
9474 /// Example for a more general valid mask (Factor 3). Lower:
9475 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9476 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9477 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9478 ///
9479 ///      Into:
9480 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9481 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9482 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9483 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9484 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9485                                                   ShuffleVectorInst *SVI,
9486                                                   unsigned Factor) const {
9487   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9488          "Invalid interleave factor");
9489 
9490   VectorType *VecTy = SVI->getType();
9491   assert(VecTy->getVectorNumElements() % Factor == 0 &&
9492          "Invalid interleaved store");
9493 
9494   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
9495   Type *EltTy = VecTy->getVectorElementType();
9496   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9497 
9498   const DataLayout &DL = SI->getModule()->getDataLayout();
9499 
9500   // Skip if we do not have NEON and skip illegal vector types. We can
9501   // "legalize" wide vector types into multiple interleaved accesses as long as
9502   // the vector types are divisible by 128.
9503   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9504     return false;
9505 
9506   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9507 
9508   Value *Op0 = SVI->getOperand(0);
9509   Value *Op1 = SVI->getOperand(1);
9510   IRBuilder<> Builder(SI);
9511 
9512   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9513   // vectors to integer vectors.
9514   if (EltTy->isPointerTy()) {
9515     Type *IntTy = DL.getIntPtrType(EltTy);
9516     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
9517 
9518     // Convert to the corresponding integer vector.
9519     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9520     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9521     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9522 
9523     SubVecTy = VectorType::get(IntTy, LaneLen);
9524   }
9525 
9526   // The base address of the store.
9527   Value *BaseAddr = SI->getPointerOperand();
9528 
9529   if (NumStores > 1) {
9530     // If we're going to generate more than one store, reset the lane length
9531     // and sub-vector type to something legal.
9532     LaneLen /= NumStores;
9533     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
9534 
9535     // We will compute the pointer operand of each store from the original base
9536     // address using GEPs. Cast the base address to a pointer to the scalar
9537     // element type.
9538     BaseAddr = Builder.CreateBitCast(
9539         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
9540                       SI->getPointerAddressSpace()));
9541   }
9542 
9543   auto Mask = SVI->getShuffleMask();
9544 
9545   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9546   Type *Tys[2] = {SubVecTy, PtrTy};
9547   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9548                                              Intrinsic::aarch64_neon_st3,
9549                                              Intrinsic::aarch64_neon_st4};
9550   Function *StNFunc =
9551       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9552 
9553   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9554 
9555     SmallVector<Value *, 5> Ops;
9556 
9557     // Split the shufflevector operands into sub vectors for the new stN call.
9558     for (unsigned i = 0; i < Factor; i++) {
9559       unsigned IdxI = StoreCount * LaneLen * Factor + i;
9560       if (Mask[IdxI] >= 0) {
9561         Ops.push_back(Builder.CreateShuffleVector(
9562             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9563       } else {
9564         unsigned StartMask = 0;
9565         for (unsigned j = 1; j < LaneLen; j++) {
9566           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9567           if (Mask[IdxJ * Factor + IdxI] >= 0) {
9568             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9569             break;
9570           }
9571         }
9572         // Note: Filling undef gaps with random elements is ok, since
9573         // those elements were being written anyway (with undefs).
9574         // In the case of all undefs we're defaulting to using elems from 0
9575         // Note: StartMask cannot be negative, it's checked in
9576         // isReInterleaveMask
9577         Ops.push_back(Builder.CreateShuffleVector(
9578             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9579       }
9580     }
9581 
9582     // If we generating more than one store, we compute the base address of
9583     // subsequent stores as an offset from the previous.
9584     if (StoreCount > 0)
9585       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9586                                             BaseAddr, LaneLen * Factor);
9587 
9588     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9589     Builder.CreateCall(StNFunc, Ops);
9590   }
9591   return true;
9592 }
9593 
9594 
9595 EVT AArch64TargetLowering::getOptimalMemOpType(
9596     const MemOp &Op, const AttributeList &FuncAttributes) const {
9597   bool CanImplicitFloat =
9598       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9599   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9600   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9601   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9602   // taken one instruction to materialize the v2i64 zero and one store (with
9603   // restrictive addressing mode). Just do i64 stores.
9604   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9605   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
9606     if (Op.isAligned(AlignCheck))
9607       return true;
9608     bool Fast;
9609     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9610                                           &Fast) &&
9611            Fast;
9612   };
9613 
9614   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9615       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
9616     return MVT::v2i64;
9617   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
9618     return MVT::f128;
9619   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
9620     return MVT::i64;
9621   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
9622     return MVT::i32;
9623   return MVT::Other;
9624 }
9625 
9626 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9627     const MemOp &Op, const AttributeList &FuncAttributes) const {
9628   bool CanImplicitFloat =
9629       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9630   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9631   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9632   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9633   // taken one instruction to materialize the v2i64 zero and one store (with
9634   // restrictive addressing mode). Just do i64 stores.
9635   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9636   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
9637     if (Op.isAligned(AlignCheck))
9638       return true;
9639     bool Fast;
9640     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9641                                           &Fast) &&
9642            Fast;
9643   };
9644 
9645   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9646       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
9647     return LLT::vector(2, 64);
9648   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
9649     return LLT::scalar(128);
9650   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
9651     return LLT::scalar(64);
9652   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
9653     return LLT::scalar(32);
9654   return LLT();
9655 }
9656 
9657 // 12-bit optionally shifted immediates are legal for adds.
9658 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9659   if (Immed == std::numeric_limits<int64_t>::min()) {
9660     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9661                       << ": avoid UB for INT64_MIN\n");
9662     return false;
9663   }
9664   // Same encoding for add/sub, just flip the sign.
9665   Immed = std::abs(Immed);
9666   bool IsLegal = ((Immed >> 12) == 0 ||
9667                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9668   LLVM_DEBUG(dbgs() << "Is " << Immed
9669                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9670   return IsLegal;
9671 }
9672 
9673 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9674 // immediates is the same as for an add or a sub.
9675 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9676   return isLegalAddImmediate(Immed);
9677 }
9678 
9679 /// isLegalAddressingMode - Return true if the addressing mode represented
9680 /// by AM is legal for this target, for a load/store of the specified type.
9681 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9682                                                   const AddrMode &AM, Type *Ty,
9683                                                   unsigned AS, Instruction *I) const {
9684   // AArch64 has five basic addressing modes:
9685   //  reg
9686   //  reg + 9-bit signed offset
9687   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9688   //  reg1 + reg2
9689   //  reg + SIZE_IN_BYTES * reg
9690 
9691   // No global is ever allowed as a base.
9692   if (AM.BaseGV)
9693     return false;
9694 
9695   // No reg+reg+imm addressing.
9696   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9697     return false;
9698 
9699   // FIXME: Update this method to support scalable addressing modes.
9700   if (Ty->isVectorTy() && Ty->getVectorIsScalable())
9701     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
9702 
9703   // check reg + imm case:
9704   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9705   uint64_t NumBytes = 0;
9706   if (Ty->isSized()) {
9707     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9708     NumBytes = NumBits / 8;
9709     if (!isPowerOf2_64(NumBits))
9710       NumBytes = 0;
9711   }
9712 
9713   if (!AM.Scale) {
9714     int64_t Offset = AM.BaseOffs;
9715 
9716     // 9-bit signed offset
9717     if (isInt<9>(Offset))
9718       return true;
9719 
9720     // 12-bit unsigned offset
9721     unsigned shift = Log2_64(NumBytes);
9722     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9723         // Must be a multiple of NumBytes (NumBytes is a power of 2)
9724         (Offset >> shift) << shift == Offset)
9725       return true;
9726     return false;
9727   }
9728 
9729   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9730 
9731   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9732 }
9733 
9734 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9735   // Consider splitting large offset of struct or array.
9736   return true;
9737 }
9738 
9739 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9740                                                 const AddrMode &AM, Type *Ty,
9741                                                 unsigned AS) const {
9742   // Scaling factors are not free at all.
9743   // Operands                     | Rt Latency
9744   // -------------------------------------------
9745   // Rt, [Xn, Xm]                 | 4
9746   // -------------------------------------------
9747   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9748   // Rt, [Xn, Wm, <extend> #imm]  |
9749   if (isLegalAddressingMode(DL, AM, Ty, AS))
9750     // Scale represents reg2 * scale, thus account for 1 if
9751     // it is not equal to 0 or 1.
9752     return AM.Scale != 0 && AM.Scale != 1;
9753   return -1;
9754 }
9755 
9756 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9757     const MachineFunction &MF, EVT VT) const {
9758   VT = VT.getScalarType();
9759 
9760   if (!VT.isSimple())
9761     return false;
9762 
9763   switch (VT.getSimpleVT().SimpleTy) {
9764   case MVT::f32:
9765   case MVT::f64:
9766     return true;
9767   default:
9768     break;
9769   }
9770 
9771   return false;
9772 }
9773 
9774 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9775                                                        Type *Ty) const {
9776   switch (Ty->getScalarType()->getTypeID()) {
9777   case Type::FloatTyID:
9778   case Type::DoubleTyID:
9779     return true;
9780   default:
9781     return false;
9782   }
9783 }
9784 
9785 const MCPhysReg *
9786 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9787   // LR is a callee-save register, but we must treat it as clobbered by any call
9788   // site. Hence we include LR in the scratch registers, which are in turn added
9789   // as implicit-defs for stackmaps and patchpoints.
9790   static const MCPhysReg ScratchRegs[] = {
9791     AArch64::X16, AArch64::X17, AArch64::LR, 0
9792   };
9793   return ScratchRegs;
9794 }
9795 
9796 bool
9797 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9798                                                      CombineLevel Level) const {
9799   N = N->getOperand(0).getNode();
9800   EVT VT = N->getValueType(0);
9801     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9802     // it with shift to let it be lowered to UBFX.
9803   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9804       isa<ConstantSDNode>(N->getOperand(1))) {
9805     uint64_t TruncMask = N->getConstantOperandVal(1);
9806     if (isMask_64(TruncMask) &&
9807       N->getOperand(0).getOpcode() == ISD::SRL &&
9808       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9809       return false;
9810   }
9811   return true;
9812 }
9813 
9814 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9815                                                               Type *Ty) const {
9816   assert(Ty->isIntegerTy());
9817 
9818   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9819   if (BitSize == 0)
9820     return false;
9821 
9822   int64_t Val = Imm.getSExtValue();
9823   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9824     return true;
9825 
9826   if ((int64_t)Val < 0)
9827     Val = ~Val;
9828   if (BitSize == 32)
9829     Val &= (1LL << 32) - 1;
9830 
9831   unsigned LZ = countLeadingZeros((uint64_t)Val);
9832   unsigned Shift = (63 - LZ) / 16;
9833   // MOVZ is free so return true for one or fewer MOVK.
9834   return Shift < 3;
9835 }
9836 
9837 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9838                                                     unsigned Index) const {
9839   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9840     return false;
9841 
9842   return (Index == 0 || Index == ResVT.getVectorNumElements());
9843 }
9844 
9845 /// Turn vector tests of the signbit in the form of:
9846 ///   xor (sra X, elt_size(X)-1), -1
9847 /// into:
9848 ///   cmge X, X, #0
9849 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9850                                          const AArch64Subtarget *Subtarget) {
9851   EVT VT = N->getValueType(0);
9852   if (!Subtarget->hasNEON() || !VT.isVector())
9853     return SDValue();
9854 
9855   // There must be a shift right algebraic before the xor, and the xor must be a
9856   // 'not' operation.
9857   SDValue Shift = N->getOperand(0);
9858   SDValue Ones = N->getOperand(1);
9859   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9860       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9861     return SDValue();
9862 
9863   // The shift should be smearing the sign bit across each vector element.
9864   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9865   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9866   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9867     return SDValue();
9868 
9869   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9870 }
9871 
9872 // Generate SUBS and CSEL for integer abs.
9873 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9874   EVT VT = N->getValueType(0);
9875 
9876   SDValue N0 = N->getOperand(0);
9877   SDValue N1 = N->getOperand(1);
9878   SDLoc DL(N);
9879 
9880   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9881   // and change it to SUB and CSEL.
9882   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9883       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9884       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9885     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9886       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9887         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9888                                   N0.getOperand(0));
9889         // Generate SUBS & CSEL.
9890         SDValue Cmp =
9891             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9892                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9893         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9894                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9895                            SDValue(Cmp.getNode(), 1));
9896       }
9897   return SDValue();
9898 }
9899 
9900 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9901                                  TargetLowering::DAGCombinerInfo &DCI,
9902                                  const AArch64Subtarget *Subtarget) {
9903   if (DCI.isBeforeLegalizeOps())
9904     return SDValue();
9905 
9906   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9907     return Cmp;
9908 
9909   return performIntegerAbsCombine(N, DAG);
9910 }
9911 
9912 SDValue
9913 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9914                                      SelectionDAG &DAG,
9915                                      SmallVectorImpl<SDNode *> &Created) const {
9916   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9917   if (isIntDivCheap(N->getValueType(0), Attr))
9918     return SDValue(N,0); // Lower SDIV as SDIV
9919 
9920   // fold (sdiv X, pow2)
9921   EVT VT = N->getValueType(0);
9922   if ((VT != MVT::i32 && VT != MVT::i64) ||
9923       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9924     return SDValue();
9925 
9926   SDLoc DL(N);
9927   SDValue N0 = N->getOperand(0);
9928   unsigned Lg2 = Divisor.countTrailingZeros();
9929   SDValue Zero = DAG.getConstant(0, DL, VT);
9930   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9931 
9932   // Add (N0 < 0) ? Pow2 - 1 : 0;
9933   SDValue CCVal;
9934   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9935   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9936   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9937 
9938   Created.push_back(Cmp.getNode());
9939   Created.push_back(Add.getNode());
9940   Created.push_back(CSel.getNode());
9941 
9942   // Divide by pow2.
9943   SDValue SRA =
9944       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9945 
9946   // If we're dividing by a positive value, we're done.  Otherwise, we must
9947   // negate the result.
9948   if (Divisor.isNonNegative())
9949     return SRA;
9950 
9951   Created.push_back(SRA.getNode());
9952   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9953 }
9954 
9955 static bool IsSVECntIntrinsic(SDValue S) {
9956   switch(getIntrinsicID(S.getNode())) {
9957   default:
9958     break;
9959   case Intrinsic::aarch64_sve_cntb:
9960   case Intrinsic::aarch64_sve_cnth:
9961   case Intrinsic::aarch64_sve_cntw:
9962   case Intrinsic::aarch64_sve_cntd:
9963     return true;
9964   }
9965   return false;
9966 }
9967 
9968 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9969                                  TargetLowering::DAGCombinerInfo &DCI,
9970                                  const AArch64Subtarget *Subtarget) {
9971   if (DCI.isBeforeLegalizeOps())
9972     return SDValue();
9973 
9974   // The below optimizations require a constant RHS.
9975   if (!isa<ConstantSDNode>(N->getOperand(1)))
9976     return SDValue();
9977 
9978   SDValue N0 = N->getOperand(0);
9979   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9980   const APInt &ConstValue = C->getAPIntValue();
9981 
9982   // Allow the scaling to be folded into the `cnt` instruction by preventing
9983   // the scaling to be obscured here. This makes it easier to pattern match.
9984   if (IsSVECntIntrinsic(N0) ||
9985      (N0->getOpcode() == ISD::TRUNCATE &&
9986       (IsSVECntIntrinsic(N0->getOperand(0)))))
9987        if (ConstValue.sge(1) && ConstValue.sle(16))
9988          return SDValue();
9989 
9990   // Multiplication of a power of two plus/minus one can be done more
9991   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9992   // future CPUs have a cheaper MADD instruction, this may need to be
9993   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9994   // 64-bit is 5 cycles, so this is always a win.
9995   // More aggressively, some multiplications N0 * C can be lowered to
9996   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9997   // e.g. 6=3*2=(2+1)*2.
9998   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9999   // which equals to (1+2)*16-(1+2).
10000   // TrailingZeroes is used to test if the mul can be lowered to
10001   // shift+add+shift.
10002   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10003   if (TrailingZeroes) {
10004     // Conservatively do not lower to shift+add+shift if the mul might be
10005     // folded into smul or umul.
10006     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10007                             isZeroExtended(N0.getNode(), DAG)))
10008       return SDValue();
10009     // Conservatively do not lower to shift+add+shift if the mul might be
10010     // folded into madd or msub.
10011     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10012                            N->use_begin()->getOpcode() == ISD::SUB))
10013       return SDValue();
10014   }
10015   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10016   // and shift+add+shift.
10017   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10018 
10019   unsigned ShiftAmt, AddSubOpc;
10020   // Is the shifted value the LHS operand of the add/sub?
10021   bool ShiftValUseIsN0 = true;
10022   // Do we need to negate the result?
10023   bool NegateResult = false;
10024 
10025   if (ConstValue.isNonNegative()) {
10026     // (mul x, 2^N + 1) => (add (shl x, N), x)
10027     // (mul x, 2^N - 1) => (sub (shl x, N), x)
10028     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10029     APInt SCVMinus1 = ShiftedConstValue - 1;
10030     APInt CVPlus1 = ConstValue + 1;
10031     if (SCVMinus1.isPowerOf2()) {
10032       ShiftAmt = SCVMinus1.logBase2();
10033       AddSubOpc = ISD::ADD;
10034     } else if (CVPlus1.isPowerOf2()) {
10035       ShiftAmt = CVPlus1.logBase2();
10036       AddSubOpc = ISD::SUB;
10037     } else
10038       return SDValue();
10039   } else {
10040     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10041     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10042     APInt CVNegPlus1 = -ConstValue + 1;
10043     APInt CVNegMinus1 = -ConstValue - 1;
10044     if (CVNegPlus1.isPowerOf2()) {
10045       ShiftAmt = CVNegPlus1.logBase2();
10046       AddSubOpc = ISD::SUB;
10047       ShiftValUseIsN0 = false;
10048     } else if (CVNegMinus1.isPowerOf2()) {
10049       ShiftAmt = CVNegMinus1.logBase2();
10050       AddSubOpc = ISD::ADD;
10051       NegateResult = true;
10052     } else
10053       return SDValue();
10054   }
10055 
10056   SDLoc DL(N);
10057   EVT VT = N->getValueType(0);
10058   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10059                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
10060 
10061   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10062   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10063   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10064   assert(!(NegateResult && TrailingZeroes) &&
10065          "NegateResult and TrailingZeroes cannot both be true for now.");
10066   // Negate the result.
10067   if (NegateResult)
10068     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10069   // Shift the result.
10070   if (TrailingZeroes)
10071     return DAG.getNode(ISD::SHL, DL, VT, Res,
10072                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10073   return Res;
10074 }
10075 
10076 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10077                                                          SelectionDAG &DAG) {
10078   // Take advantage of vector comparisons producing 0 or -1 in each lane to
10079   // optimize away operation when it's from a constant.
10080   //
10081   // The general transformation is:
10082   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10083   //       AND(VECTOR_CMP(x,y), constant2)
10084   //    constant2 = UNARYOP(constant)
10085 
10086   // Early exit if this isn't a vector operation, the operand of the
10087   // unary operation isn't a bitwise AND, or if the sizes of the operations
10088   // aren't the same.
10089   EVT VT = N->getValueType(0);
10090   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10091       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10092       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10093     return SDValue();
10094 
10095   // Now check that the other operand of the AND is a constant. We could
10096   // make the transformation for non-constant splats as well, but it's unclear
10097   // that would be a benefit as it would not eliminate any operations, just
10098   // perform one more step in scalar code before moving to the vector unit.
10099   if (BuildVectorSDNode *BV =
10100           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10101     // Bail out if the vector isn't a constant.
10102     if (!BV->isConstant())
10103       return SDValue();
10104 
10105     // Everything checks out. Build up the new and improved node.
10106     SDLoc DL(N);
10107     EVT IntVT = BV->getValueType(0);
10108     // Create a new constant of the appropriate type for the transformed
10109     // DAG.
10110     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10111     // The AND node needs bitcasts to/from an integer vector type around it.
10112     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10113     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10114                                  N->getOperand(0)->getOperand(0), MaskConst);
10115     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10116     return Res;
10117   }
10118 
10119   return SDValue();
10120 }
10121 
10122 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10123                                      const AArch64Subtarget *Subtarget) {
10124   // First try to optimize away the conversion when it's conditionally from
10125   // a constant. Vectors only.
10126   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10127     return Res;
10128 
10129   EVT VT = N->getValueType(0);
10130   if (VT != MVT::f32 && VT != MVT::f64)
10131     return SDValue();
10132 
10133   // Only optimize when the source and destination types have the same width.
10134   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10135     return SDValue();
10136 
10137   // If the result of an integer load is only used by an integer-to-float
10138   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10139   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10140   SDValue N0 = N->getOperand(0);
10141   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10142       // Do not change the width of a volatile load.
10143       !cast<LoadSDNode>(N0)->isVolatile()) {
10144     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10145     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10146                                LN0->getPointerInfo(), LN0->getAlignment(),
10147                                LN0->getMemOperand()->getFlags());
10148 
10149     // Make sure successors of the original load stay after it by updating them
10150     // to use the new Chain.
10151     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10152 
10153     unsigned Opcode =
10154         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10155     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10156   }
10157 
10158   return SDValue();
10159 }
10160 
10161 /// Fold a floating-point multiply by power of two into floating-point to
10162 /// fixed-point conversion.
10163 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10164                                      TargetLowering::DAGCombinerInfo &DCI,
10165                                      const AArch64Subtarget *Subtarget) {
10166   if (!Subtarget->hasNEON())
10167     return SDValue();
10168 
10169   if (!N->getValueType(0).isSimple())
10170     return SDValue();
10171 
10172   SDValue Op = N->getOperand(0);
10173   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10174       Op.getOpcode() != ISD::FMUL)
10175     return SDValue();
10176 
10177   SDValue ConstVec = Op->getOperand(1);
10178   if (!isa<BuildVectorSDNode>(ConstVec))
10179     return SDValue();
10180 
10181   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10182   uint32_t FloatBits = FloatTy.getSizeInBits();
10183   if (FloatBits != 32 && FloatBits != 64)
10184     return SDValue();
10185 
10186   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10187   uint32_t IntBits = IntTy.getSizeInBits();
10188   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10189     return SDValue();
10190 
10191   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10192   if (IntBits > FloatBits)
10193     return SDValue();
10194 
10195   BitVector UndefElements;
10196   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10197   int32_t Bits = IntBits == 64 ? 64 : 32;
10198   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10199   if (C == -1 || C == 0 || C > Bits)
10200     return SDValue();
10201 
10202   MVT ResTy;
10203   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10204   switch (NumLanes) {
10205   default:
10206     return SDValue();
10207   case 2:
10208     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10209     break;
10210   case 4:
10211     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10212     break;
10213   }
10214 
10215   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10216     return SDValue();
10217 
10218   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10219          "Illegal vector type after legalization");
10220 
10221   SDLoc DL(N);
10222   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10223   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10224                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10225   SDValue FixConv =
10226       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10227                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10228                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10229   // We can handle smaller integers by generating an extra trunc.
10230   if (IntBits < FloatBits)
10231     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10232 
10233   return FixConv;
10234 }
10235 
10236 /// Fold a floating-point divide by power of two into fixed-point to
10237 /// floating-point conversion.
10238 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10239                                   TargetLowering::DAGCombinerInfo &DCI,
10240                                   const AArch64Subtarget *Subtarget) {
10241   if (!Subtarget->hasNEON())
10242     return SDValue();
10243 
10244   SDValue Op = N->getOperand(0);
10245   unsigned Opc = Op->getOpcode();
10246   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10247       !Op.getOperand(0).getValueType().isSimple() ||
10248       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10249     return SDValue();
10250 
10251   SDValue ConstVec = N->getOperand(1);
10252   if (!isa<BuildVectorSDNode>(ConstVec))
10253     return SDValue();
10254 
10255   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10256   int32_t IntBits = IntTy.getSizeInBits();
10257   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10258     return SDValue();
10259 
10260   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10261   int32_t FloatBits = FloatTy.getSizeInBits();
10262   if (FloatBits != 32 && FloatBits != 64)
10263     return SDValue();
10264 
10265   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10266   if (IntBits > FloatBits)
10267     return SDValue();
10268 
10269   BitVector UndefElements;
10270   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10271   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10272   if (C == -1 || C == 0 || C > FloatBits)
10273     return SDValue();
10274 
10275   MVT ResTy;
10276   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10277   switch (NumLanes) {
10278   default:
10279     return SDValue();
10280   case 2:
10281     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10282     break;
10283   case 4:
10284     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10285     break;
10286   }
10287 
10288   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10289     return SDValue();
10290 
10291   SDLoc DL(N);
10292   SDValue ConvInput = Op.getOperand(0);
10293   bool IsSigned = Opc == ISD::SINT_TO_FP;
10294   if (IntBits < FloatBits)
10295     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10296                             ResTy, ConvInput);
10297 
10298   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10299                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10300   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10301                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10302                      DAG.getConstant(C, DL, MVT::i32));
10303 }
10304 
10305 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10306 /// searches for and classifies those shifts.
10307 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10308                          bool &FromHi) {
10309   if (N.getOpcode() == ISD::SHL)
10310     FromHi = false;
10311   else if (N.getOpcode() == ISD::SRL)
10312     FromHi = true;
10313   else
10314     return false;
10315 
10316   if (!isa<ConstantSDNode>(N.getOperand(1)))
10317     return false;
10318 
10319   ShiftAmount = N->getConstantOperandVal(1);
10320   Src = N->getOperand(0);
10321   return true;
10322 }
10323 
10324 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10325 /// registers viewed as a high/low pair. This function looks for the pattern:
10326 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10327 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10328 /// aren't independent.
10329 static SDValue tryCombineToEXTR(SDNode *N,
10330                                 TargetLowering::DAGCombinerInfo &DCI) {
10331   SelectionDAG &DAG = DCI.DAG;
10332   SDLoc DL(N);
10333   EVT VT = N->getValueType(0);
10334 
10335   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10336 
10337   if (VT != MVT::i32 && VT != MVT::i64)
10338     return SDValue();
10339 
10340   SDValue LHS;
10341   uint32_t ShiftLHS = 0;
10342   bool LHSFromHi = false;
10343   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10344     return SDValue();
10345 
10346   SDValue RHS;
10347   uint32_t ShiftRHS = 0;
10348   bool RHSFromHi = false;
10349   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10350     return SDValue();
10351 
10352   // If they're both trying to come from the high part of the register, they're
10353   // not really an EXTR.
10354   if (LHSFromHi == RHSFromHi)
10355     return SDValue();
10356 
10357   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10358     return SDValue();
10359 
10360   if (LHSFromHi) {
10361     std::swap(LHS, RHS);
10362     std::swap(ShiftLHS, ShiftRHS);
10363   }
10364 
10365   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10366                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10367 }
10368 
10369 static SDValue tryCombineToBSL(SDNode *N,
10370                                 TargetLowering::DAGCombinerInfo &DCI) {
10371   EVT VT = N->getValueType(0);
10372   SelectionDAG &DAG = DCI.DAG;
10373   SDLoc DL(N);
10374 
10375   if (!VT.isVector())
10376     return SDValue();
10377 
10378   SDValue N0 = N->getOperand(0);
10379   if (N0.getOpcode() != ISD::AND)
10380     return SDValue();
10381 
10382   SDValue N1 = N->getOperand(1);
10383   if (N1.getOpcode() != ISD::AND)
10384     return SDValue();
10385 
10386   // We only have to look for constant vectors here since the general, variable
10387   // case can be handled in TableGen.
10388   unsigned Bits = VT.getScalarSizeInBits();
10389   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10390   for (int i = 1; i >= 0; --i)
10391     for (int j = 1; j >= 0; --j) {
10392       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10393       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10394       if (!BVN0 || !BVN1)
10395         continue;
10396 
10397       bool FoundMatch = true;
10398       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10399         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10400         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10401         if (!CN0 || !CN1 ||
10402             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10403           FoundMatch = false;
10404           break;
10405         }
10406       }
10407 
10408       if (FoundMatch)
10409         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
10410                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10411     }
10412 
10413   return SDValue();
10414 }
10415 
10416 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10417                                 const AArch64Subtarget *Subtarget) {
10418   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10419   SelectionDAG &DAG = DCI.DAG;
10420   EVT VT = N->getValueType(0);
10421 
10422   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10423     return SDValue();
10424 
10425   if (SDValue Res = tryCombineToEXTR(N, DCI))
10426     return Res;
10427 
10428   if (SDValue Res = tryCombineToBSL(N, DCI))
10429     return Res;
10430 
10431   return SDValue();
10432 }
10433 
10434 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10435   if (!MemVT.getVectorElementType().isSimple())
10436     return false;
10437 
10438   uint64_t MaskForTy = 0ull;
10439   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10440   case MVT::i8:
10441     MaskForTy = 0xffull;
10442     break;
10443   case MVT::i16:
10444     MaskForTy = 0xffffull;
10445     break;
10446   case MVT::i32:
10447     MaskForTy = 0xffffffffull;
10448     break;
10449   default:
10450     return false;
10451     break;
10452   }
10453 
10454   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10455     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10456       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10457 
10458   return false;
10459 }
10460 
10461 static SDValue performSVEAndCombine(SDNode *N,
10462                                     TargetLowering::DAGCombinerInfo &DCI) {
10463   if (DCI.isBeforeLegalizeOps())
10464     return SDValue();
10465 
10466   SDValue Src = N->getOperand(0);
10467   SDValue Mask = N->getOperand(1);
10468 
10469   if (!Src.hasOneUse())
10470     return SDValue();
10471 
10472   EVT MemVT;
10473 
10474   // SVE load instructions perform an implicit zero-extend, which makes them
10475   // perfect candidates for combining.
10476   switch (Src->getOpcode()) {
10477   case AArch64ISD::LDNF1:
10478   case AArch64ISD::LDFF1:
10479     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
10480     break;
10481   case AArch64ISD::GLD1:
10482   case AArch64ISD::GLD1_SCALED:
10483   case AArch64ISD::GLD1_SXTW:
10484   case AArch64ISD::GLD1_SXTW_SCALED:
10485   case AArch64ISD::GLD1_UXTW:
10486   case AArch64ISD::GLD1_UXTW_SCALED:
10487   case AArch64ISD::GLD1_IMM:
10488   case AArch64ISD::GLDFF1:
10489   case AArch64ISD::GLDFF1_SCALED:
10490   case AArch64ISD::GLDFF1_SXTW:
10491   case AArch64ISD::GLDFF1_SXTW_SCALED:
10492   case AArch64ISD::GLDFF1_UXTW:
10493   case AArch64ISD::GLDFF1_UXTW_SCALED:
10494   case AArch64ISD::GLDFF1_IMM:
10495   case AArch64ISD::GLDNT1:
10496     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10497     break;
10498   default:
10499     return SDValue();
10500   }
10501 
10502   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10503     return Src;
10504 
10505   return SDValue();
10506 }
10507 
10508 static SDValue performANDCombine(SDNode *N,
10509                                  TargetLowering::DAGCombinerInfo &DCI) {
10510   SelectionDAG &DAG = DCI.DAG;
10511   SDValue LHS = N->getOperand(0);
10512   EVT VT = N->getValueType(0);
10513   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10514     return SDValue();
10515 
10516   if (VT.isScalableVector())
10517     return performSVEAndCombine(N, DCI);
10518 
10519   BuildVectorSDNode *BVN =
10520       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10521   if (!BVN)
10522     return SDValue();
10523 
10524   // AND does not accept an immediate, so check if we can use a BIC immediate
10525   // instruction instead. We do this here instead of using a (and x, (mvni imm))
10526   // pattern in isel, because some immediates may be lowered to the preferred
10527   // (and x, (movi imm)) form, even though an mvni representation also exists.
10528   APInt DefBits(VT.getSizeInBits(), 0);
10529   APInt UndefBits(VT.getSizeInBits(), 0);
10530   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10531     SDValue NewOp;
10532 
10533     DefBits = ~DefBits;
10534     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10535                                     DefBits, &LHS)) ||
10536         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10537                                     DefBits, &LHS)))
10538       return NewOp;
10539 
10540     UndefBits = ~UndefBits;
10541     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10542                                     UndefBits, &LHS)) ||
10543         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10544                                     UndefBits, &LHS)))
10545       return NewOp;
10546   }
10547 
10548   return SDValue();
10549 }
10550 
10551 static SDValue performSRLCombine(SDNode *N,
10552                                  TargetLowering::DAGCombinerInfo &DCI) {
10553   SelectionDAG &DAG = DCI.DAG;
10554   EVT VT = N->getValueType(0);
10555   if (VT != MVT::i32 && VT != MVT::i64)
10556     return SDValue();
10557 
10558   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10559   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10560   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10561   SDValue N0 = N->getOperand(0);
10562   if (N0.getOpcode() == ISD::BSWAP) {
10563     SDLoc DL(N);
10564     SDValue N1 = N->getOperand(1);
10565     SDValue N00 = N0.getOperand(0);
10566     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10567       uint64_t ShiftAmt = C->getZExtValue();
10568       if (VT == MVT::i32 && ShiftAmt == 16 &&
10569           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10570         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10571       if (VT == MVT::i64 && ShiftAmt == 32 &&
10572           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10573         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10574     }
10575   }
10576   return SDValue();
10577 }
10578 
10579 static SDValue performConcatVectorsCombine(SDNode *N,
10580                                            TargetLowering::DAGCombinerInfo &DCI,
10581                                            SelectionDAG &DAG) {
10582   SDLoc dl(N);
10583   EVT VT = N->getValueType(0);
10584   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10585 
10586   // Optimize concat_vectors of truncated vectors, where the intermediate
10587   // type is illegal, to avoid said illegality,  e.g.,
10588   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10589   //                          (v2i16 (truncate (v2i64)))))
10590   // ->
10591   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10592   //                                    (v4i32 (bitcast (v2i64))),
10593   //                                    <0, 2, 4, 6>)))
10594   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10595   // on both input and result type, so we might generate worse code.
10596   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10597   if (N->getNumOperands() == 2 &&
10598       N0->getOpcode() == ISD::TRUNCATE &&
10599       N1->getOpcode() == ISD::TRUNCATE) {
10600     SDValue N00 = N0->getOperand(0);
10601     SDValue N10 = N1->getOperand(0);
10602     EVT N00VT = N00.getValueType();
10603 
10604     if (N00VT == N10.getValueType() &&
10605         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10606         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10607       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10608       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10609       for (size_t i = 0; i < Mask.size(); ++i)
10610         Mask[i] = i * 2;
10611       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10612                          DAG.getVectorShuffle(
10613                              MidVT, dl,
10614                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10615                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10616     }
10617   }
10618 
10619   // Wait 'til after everything is legalized to try this. That way we have
10620   // legal vector types and such.
10621   if (DCI.isBeforeLegalizeOps())
10622     return SDValue();
10623 
10624   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10625   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10626   // canonicalise to that.
10627   if (N0 == N1 && VT.getVectorNumElements() == 2) {
10628     assert(VT.getScalarSizeInBits() == 64);
10629     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10630                        DAG.getConstant(0, dl, MVT::i64));
10631   }
10632 
10633   // Canonicalise concat_vectors so that the right-hand vector has as few
10634   // bit-casts as possible before its real operation. The primary matching
10635   // destination for these operations will be the narrowing "2" instructions,
10636   // which depend on the operation being performed on this right-hand vector.
10637   // For example,
10638   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10639   // becomes
10640   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10641 
10642   if (N1->getOpcode() != ISD::BITCAST)
10643     return SDValue();
10644   SDValue RHS = N1->getOperand(0);
10645   MVT RHSTy = RHS.getValueType().getSimpleVT();
10646   // If the RHS is not a vector, this is not the pattern we're looking for.
10647   if (!RHSTy.isVector())
10648     return SDValue();
10649 
10650   LLVM_DEBUG(
10651       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10652 
10653   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10654                                   RHSTy.getVectorNumElements() * 2);
10655   return DAG.getNode(ISD::BITCAST, dl, VT,
10656                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10657                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10658                                  RHS));
10659 }
10660 
10661 static SDValue tryCombineFixedPointConvert(SDNode *N,
10662                                            TargetLowering::DAGCombinerInfo &DCI,
10663                                            SelectionDAG &DAG) {
10664   // Wait until after everything is legalized to try this. That way we have
10665   // legal vector types and such.
10666   if (DCI.isBeforeLegalizeOps())
10667     return SDValue();
10668   // Transform a scalar conversion of a value from a lane extract into a
10669   // lane extract of a vector conversion. E.g., from foo1 to foo2:
10670   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10671   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10672   //
10673   // The second form interacts better with instruction selection and the
10674   // register allocator to avoid cross-class register copies that aren't
10675   // coalescable due to a lane reference.
10676 
10677   // Check the operand and see if it originates from a lane extract.
10678   SDValue Op1 = N->getOperand(1);
10679   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10680     // Yep, no additional predication needed. Perform the transform.
10681     SDValue IID = N->getOperand(0);
10682     SDValue Shift = N->getOperand(2);
10683     SDValue Vec = Op1.getOperand(0);
10684     SDValue Lane = Op1.getOperand(1);
10685     EVT ResTy = N->getValueType(0);
10686     EVT VecResTy;
10687     SDLoc DL(N);
10688 
10689     // The vector width should be 128 bits by the time we get here, even
10690     // if it started as 64 bits (the extract_vector handling will have
10691     // done so).
10692     assert(Vec.getValueSizeInBits() == 128 &&
10693            "unexpected vector size on extract_vector_elt!");
10694     if (Vec.getValueType() == MVT::v4i32)
10695       VecResTy = MVT::v4f32;
10696     else if (Vec.getValueType() == MVT::v2i64)
10697       VecResTy = MVT::v2f64;
10698     else
10699       llvm_unreachable("unexpected vector type!");
10700 
10701     SDValue Convert =
10702         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10703     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10704   }
10705   return SDValue();
10706 }
10707 
10708 // AArch64 high-vector "long" operations are formed by performing the non-high
10709 // version on an extract_subvector of each operand which gets the high half:
10710 //
10711 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10712 //
10713 // However, there are cases which don't have an extract_high explicitly, but
10714 // have another operation that can be made compatible with one for free. For
10715 // example:
10716 //
10717 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
10718 //
10719 // This routine does the actual conversion of such DUPs, once outer routines
10720 // have determined that everything else is in order.
10721 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10722 // similarly here.
10723 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10724   switch (N.getOpcode()) {
10725   case AArch64ISD::DUP:
10726   case AArch64ISD::DUPLANE8:
10727   case AArch64ISD::DUPLANE16:
10728   case AArch64ISD::DUPLANE32:
10729   case AArch64ISD::DUPLANE64:
10730   case AArch64ISD::MOVI:
10731   case AArch64ISD::MOVIshift:
10732   case AArch64ISD::MOVIedit:
10733   case AArch64ISD::MOVImsl:
10734   case AArch64ISD::MVNIshift:
10735   case AArch64ISD::MVNImsl:
10736     break;
10737   default:
10738     // FMOV could be supported, but isn't very useful, as it would only occur
10739     // if you passed a bitcast' floating point immediate to an eligible long
10740     // integer op (addl, smull, ...).
10741     return SDValue();
10742   }
10743 
10744   MVT NarrowTy = N.getSimpleValueType();
10745   if (!NarrowTy.is64BitVector())
10746     return SDValue();
10747 
10748   MVT ElementTy = NarrowTy.getVectorElementType();
10749   unsigned NumElems = NarrowTy.getVectorNumElements();
10750   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10751 
10752   SDLoc dl(N);
10753   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10754                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10755                      DAG.getConstant(NumElems, dl, MVT::i64));
10756 }
10757 
10758 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10759   if (N.getOpcode() == ISD::BITCAST)
10760     N = N.getOperand(0);
10761   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10762     return false;
10763   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10764          N.getOperand(0).getValueType().getVectorNumElements() / 2;
10765 }
10766 
10767 /// Helper structure to keep track of ISD::SET_CC operands.
10768 struct GenericSetCCInfo {
10769   const SDValue *Opnd0;
10770   const SDValue *Opnd1;
10771   ISD::CondCode CC;
10772 };
10773 
10774 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10775 struct AArch64SetCCInfo {
10776   const SDValue *Cmp;
10777   AArch64CC::CondCode CC;
10778 };
10779 
10780 /// Helper structure to keep track of SetCC information.
10781 union SetCCInfo {
10782   GenericSetCCInfo Generic;
10783   AArch64SetCCInfo AArch64;
10784 };
10785 
10786 /// Helper structure to be able to read SetCC information.  If set to
10787 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10788 /// GenericSetCCInfo.
10789 struct SetCCInfoAndKind {
10790   SetCCInfo Info;
10791   bool IsAArch64;
10792 };
10793 
10794 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10795 /// an
10796 /// AArch64 lowered one.
10797 /// \p SetCCInfo is filled accordingly.
10798 /// \post SetCCInfo is meanginfull only when this function returns true.
10799 /// \return True when Op is a kind of SET_CC operation.
10800 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10801   // If this is a setcc, this is straight forward.
10802   if (Op.getOpcode() == ISD::SETCC) {
10803     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10804     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10805     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10806     SetCCInfo.IsAArch64 = false;
10807     return true;
10808   }
10809   // Otherwise, check if this is a matching csel instruction.
10810   // In other words:
10811   // - csel 1, 0, cc
10812   // - csel 0, 1, !cc
10813   if (Op.getOpcode() != AArch64ISD::CSEL)
10814     return false;
10815   // Set the information about the operands.
10816   // TODO: we want the operands of the Cmp not the csel
10817   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10818   SetCCInfo.IsAArch64 = true;
10819   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10820       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10821 
10822   // Check that the operands matches the constraints:
10823   // (1) Both operands must be constants.
10824   // (2) One must be 1 and the other must be 0.
10825   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10826   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10827 
10828   // Check (1).
10829   if (!TValue || !FValue)
10830     return false;
10831 
10832   // Check (2).
10833   if (!TValue->isOne()) {
10834     // Update the comparison when we are interested in !cc.
10835     std::swap(TValue, FValue);
10836     SetCCInfo.Info.AArch64.CC =
10837         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10838   }
10839   return TValue->isOne() && FValue->isNullValue();
10840 }
10841 
10842 // Returns true if Op is setcc or zext of setcc.
10843 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10844   if (isSetCC(Op, Info))
10845     return true;
10846   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10847     isSetCC(Op->getOperand(0), Info));
10848 }
10849 
10850 // The folding we want to perform is:
10851 // (add x, [zext] (setcc cc ...) )
10852 //   -->
10853 // (csel x, (add x, 1), !cc ...)
10854 //
10855 // The latter will get matched to a CSINC instruction.
10856 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10857   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10858   SDValue LHS = Op->getOperand(0);
10859   SDValue RHS = Op->getOperand(1);
10860   SetCCInfoAndKind InfoAndKind;
10861 
10862   // If neither operand is a SET_CC, give up.
10863   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10864     std::swap(LHS, RHS);
10865     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10866       return SDValue();
10867   }
10868 
10869   // FIXME: This could be generatized to work for FP comparisons.
10870   EVT CmpVT = InfoAndKind.IsAArch64
10871                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10872                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10873   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10874     return SDValue();
10875 
10876   SDValue CCVal;
10877   SDValue Cmp;
10878   SDLoc dl(Op);
10879   if (InfoAndKind.IsAArch64) {
10880     CCVal = DAG.getConstant(
10881         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10882         MVT::i32);
10883     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10884   } else
10885     Cmp = getAArch64Cmp(
10886         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10887         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10888         dl);
10889 
10890   EVT VT = Op->getValueType(0);
10891   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10892   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10893 }
10894 
10895 // The basic add/sub long vector instructions have variants with "2" on the end
10896 // which act on the high-half of their inputs. They are normally matched by
10897 // patterns like:
10898 //
10899 // (add (zeroext (extract_high LHS)),
10900 //      (zeroext (extract_high RHS)))
10901 // -> uaddl2 vD, vN, vM
10902 //
10903 // However, if one of the extracts is something like a duplicate, this
10904 // instruction can still be used profitably. This function puts the DAG into a
10905 // more appropriate form for those patterns to trigger.
10906 static SDValue performAddSubLongCombine(SDNode *N,
10907                                         TargetLowering::DAGCombinerInfo &DCI,
10908                                         SelectionDAG &DAG) {
10909   if (DCI.isBeforeLegalizeOps())
10910     return SDValue();
10911 
10912   MVT VT = N->getSimpleValueType(0);
10913   if (!VT.is128BitVector()) {
10914     if (N->getOpcode() == ISD::ADD)
10915       return performSetccAddFolding(N, DAG);
10916     return SDValue();
10917   }
10918 
10919   // Make sure both branches are extended in the same way.
10920   SDValue LHS = N->getOperand(0);
10921   SDValue RHS = N->getOperand(1);
10922   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10923        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10924       LHS.getOpcode() != RHS.getOpcode())
10925     return SDValue();
10926 
10927   unsigned ExtType = LHS.getOpcode();
10928 
10929   // It's not worth doing if at least one of the inputs isn't already an
10930   // extract, but we don't know which it'll be so we have to try both.
10931   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10932     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10933     if (!RHS.getNode())
10934       return SDValue();
10935 
10936     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10937   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10938     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10939     if (!LHS.getNode())
10940       return SDValue();
10941 
10942     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10943   }
10944 
10945   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10946 }
10947 
10948 // Massage DAGs which we can use the high-half "long" operations on into
10949 // something isel will recognize better. E.g.
10950 //
10951 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10952 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10953 //                     (extract_high (v2i64 (dup128 scalar)))))
10954 //
10955 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10956                                        TargetLowering::DAGCombinerInfo &DCI,
10957                                        SelectionDAG &DAG) {
10958   if (DCI.isBeforeLegalizeOps())
10959     return SDValue();
10960 
10961   SDValue LHS = N->getOperand(1);
10962   SDValue RHS = N->getOperand(2);
10963   assert(LHS.getValueType().is64BitVector() &&
10964          RHS.getValueType().is64BitVector() &&
10965          "unexpected shape for long operation");
10966 
10967   // Either node could be a DUP, but it's not worth doing both of them (you'd
10968   // just as well use the non-high version) so look for a corresponding extract
10969   // operation on the other "wing".
10970   if (isEssentiallyExtractHighSubvector(LHS)) {
10971     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10972     if (!RHS.getNode())
10973       return SDValue();
10974   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10975     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10976     if (!LHS.getNode())
10977       return SDValue();
10978   }
10979 
10980   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10981                      N->getOperand(0), LHS, RHS);
10982 }
10983 
10984 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10985   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10986   unsigned ElemBits = ElemTy.getSizeInBits();
10987 
10988   int64_t ShiftAmount;
10989   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10990     APInt SplatValue, SplatUndef;
10991     unsigned SplatBitSize;
10992     bool HasAnyUndefs;
10993     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10994                               HasAnyUndefs, ElemBits) ||
10995         SplatBitSize != ElemBits)
10996       return SDValue();
10997 
10998     ShiftAmount = SplatValue.getSExtValue();
10999   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
11000     ShiftAmount = CVN->getSExtValue();
11001   } else
11002     return SDValue();
11003 
11004   unsigned Opcode;
11005   bool IsRightShift;
11006   switch (IID) {
11007   default:
11008     llvm_unreachable("Unknown shift intrinsic");
11009   case Intrinsic::aarch64_neon_sqshl:
11010     Opcode = AArch64ISD::SQSHL_I;
11011     IsRightShift = false;
11012     break;
11013   case Intrinsic::aarch64_neon_uqshl:
11014     Opcode = AArch64ISD::UQSHL_I;
11015     IsRightShift = false;
11016     break;
11017   case Intrinsic::aarch64_neon_srshl:
11018     Opcode = AArch64ISD::SRSHR_I;
11019     IsRightShift = true;
11020     break;
11021   case Intrinsic::aarch64_neon_urshl:
11022     Opcode = AArch64ISD::URSHR_I;
11023     IsRightShift = true;
11024     break;
11025   case Intrinsic::aarch64_neon_sqshlu:
11026     Opcode = AArch64ISD::SQSHLU_I;
11027     IsRightShift = false;
11028     break;
11029   case Intrinsic::aarch64_neon_sshl:
11030   case Intrinsic::aarch64_neon_ushl:
11031     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11032     // left shift for positive shift amounts. Below, we only replace the current
11033     // node with VSHL, if this condition is met.
11034     Opcode = AArch64ISD::VSHL;
11035     IsRightShift = false;
11036     break;
11037   }
11038 
11039   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11040     SDLoc dl(N);
11041     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11042                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11043   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11044     SDLoc dl(N);
11045     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11046                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
11047   }
11048 
11049   return SDValue();
11050 }
11051 
11052 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11053 // the intrinsics must be legal and take an i32, this means there's almost
11054 // certainly going to be a zext in the DAG which we can eliminate.
11055 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11056   SDValue AndN = N->getOperand(2);
11057   if (AndN.getOpcode() != ISD::AND)
11058     return SDValue();
11059 
11060   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11061   if (!CMask || CMask->getZExtValue() != Mask)
11062     return SDValue();
11063 
11064   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11065                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11066 }
11067 
11068 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11069                                            SelectionDAG &DAG) {
11070   SDLoc dl(N);
11071   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11072                      DAG.getNode(Opc, dl,
11073                                  N->getOperand(1).getSimpleValueType(),
11074                                  N->getOperand(1)),
11075                      DAG.getConstant(0, dl, MVT::i64));
11076 }
11077 
11078 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11079                                     SelectionDAG &DAG) {
11080   SDLoc dl(N);
11081   LLVMContext &Ctx = *DAG.getContext();
11082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11083 
11084   EVT VT = N->getValueType(0);
11085   SDValue Pred = N->getOperand(1);
11086   SDValue Data = N->getOperand(2);
11087   EVT DataVT = Data.getValueType();
11088 
11089   if (DataVT.getVectorElementType().isScalarInteger() &&
11090       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11091     if (!TLI.isTypeLegal(DataVT))
11092       return SDValue();
11093 
11094     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11095       AArch64::NeonBitsPerVector / VT.getSizeInBits());
11096     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11097     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11098     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11099 
11100     return Result;
11101   }
11102 
11103   return SDValue();
11104 }
11105 
11106 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11107   SDLoc DL(N);
11108   SDValue Op1 = N->getOperand(1);
11109   SDValue Op2 = N->getOperand(2);
11110   EVT ScalarTy = Op1.getValueType();
11111 
11112   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11113     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11114     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11115   }
11116 
11117   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11118                      Op1, Op2);
11119 }
11120 
11121 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11122   SDLoc dl(N);
11123   SDValue Scalar = N->getOperand(3);
11124   EVT ScalarTy = Scalar.getValueType();
11125 
11126   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11127     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11128 
11129   return DAG.getNode(AArch64ISD::DUP_PRED, dl, N->getValueType(0),
11130                      N->getOperand(1), N->getOperand(2), Scalar);
11131 }
11132 
11133 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11134   SDLoc dl(N);
11135   LLVMContext &Ctx = *DAG.getContext();
11136   EVT VT = N->getValueType(0);
11137 
11138   assert(VT.isScalableVector() && "Expected a scalable vector.");
11139 
11140   // Current lowering only supports the SVE-ACLE types.
11141   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11142     return SDValue();
11143 
11144   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11145   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11146   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
11147 
11148   // Convert everything to the domain of EXT (i.e bytes).
11149   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
11150   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
11151   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
11152                             DAG.getConstant(ElemSize, dl, MVT::i32));
11153 
11154   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
11155   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
11156 }
11157 
11158 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
11159                                         bool Invert,
11160                                         TargetLowering::DAGCombinerInfo &DCI,
11161                                         SelectionDAG &DAG) {
11162   if (DCI.isBeforeLegalize())
11163     return SDValue();
11164 
11165   SDValue Comparator = N->getOperand(3);
11166   if (Comparator.getOpcode() == AArch64ISD::DUP ||
11167       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
11168     unsigned IID = getIntrinsicID(N);
11169     EVT VT = N->getValueType(0);
11170     EVT CmpVT = N->getOperand(2).getValueType();
11171     SDValue Pred = N->getOperand(1);
11172     SDValue Imm;
11173     SDLoc DL(N);
11174 
11175     switch (IID) {
11176     default:
11177       llvm_unreachable("Called with wrong intrinsic!");
11178       break;
11179 
11180     // Signed comparisons
11181     case Intrinsic::aarch64_sve_cmpeq_wide:
11182     case Intrinsic::aarch64_sve_cmpne_wide:
11183     case Intrinsic::aarch64_sve_cmpge_wide:
11184     case Intrinsic::aarch64_sve_cmpgt_wide:
11185     case Intrinsic::aarch64_sve_cmplt_wide:
11186     case Intrinsic::aarch64_sve_cmple_wide: {
11187       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11188         int64_t ImmVal = CN->getSExtValue();
11189         if (ImmVal >= -16 && ImmVal <= 15)
11190           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11191         else
11192           return SDValue();
11193       }
11194       break;
11195     }
11196     // Unsigned comparisons
11197     case Intrinsic::aarch64_sve_cmphs_wide:
11198     case Intrinsic::aarch64_sve_cmphi_wide:
11199     case Intrinsic::aarch64_sve_cmplo_wide:
11200     case Intrinsic::aarch64_sve_cmpls_wide:  {
11201       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11202         uint64_t ImmVal = CN->getZExtValue();
11203         if (ImmVal <= 127)
11204           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11205         else
11206           return SDValue();
11207       }
11208       break;
11209     }
11210     }
11211 
11212     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11213     SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
11214     SDValue Op0, Op1;
11215     if (Invert) {
11216       Op0 = Splat;
11217       Op1 = N->getOperand(2);
11218     } else {
11219       Op0 = N->getOperand(2);
11220       Op1 = Splat;
11221     }
11222     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11223                        ID, Pred, Op0, Op1);
11224   }
11225 
11226   return SDValue();
11227 }
11228 
11229 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11230                         AArch64CC::CondCode Cond) {
11231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11232 
11233   SDLoc DL(Op);
11234   assert(Op.getValueType().isScalableVector() &&
11235          TLI.isTypeLegal(Op.getValueType()) &&
11236          "Expected legal scalable vector type!");
11237 
11238   // Ensure target specific opcodes are using legal type.
11239   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11240   SDValue TVal = DAG.getConstant(1, DL, OutVT);
11241   SDValue FVal = DAG.getConstant(0, DL, OutVT);
11242 
11243   // Set condition code (CC) flags.
11244   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11245 
11246   // Convert CC to integer based on requested condition.
11247   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11248   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11249   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11250   return DAG.getZExtOrTrunc(Res, DL, VT);
11251 }
11252 
11253 static SDValue performIntrinsicCombine(SDNode *N,
11254                                        TargetLowering::DAGCombinerInfo &DCI,
11255                                        const AArch64Subtarget *Subtarget) {
11256   SelectionDAG &DAG = DCI.DAG;
11257   unsigned IID = getIntrinsicID(N);
11258   switch (IID) {
11259   default:
11260     break;
11261   case Intrinsic::aarch64_neon_vcvtfxs2fp:
11262   case Intrinsic::aarch64_neon_vcvtfxu2fp:
11263     return tryCombineFixedPointConvert(N, DCI, DAG);
11264   case Intrinsic::aarch64_neon_saddv:
11265     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11266   case Intrinsic::aarch64_neon_uaddv:
11267     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11268   case Intrinsic::aarch64_neon_sminv:
11269     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11270   case Intrinsic::aarch64_neon_uminv:
11271     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11272   case Intrinsic::aarch64_neon_smaxv:
11273     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11274   case Intrinsic::aarch64_neon_umaxv:
11275     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11276   case Intrinsic::aarch64_neon_fmax:
11277     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11278                        N->getOperand(1), N->getOperand(2));
11279   case Intrinsic::aarch64_neon_fmin:
11280     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11281                        N->getOperand(1), N->getOperand(2));
11282   case Intrinsic::aarch64_neon_fmaxnm:
11283     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11284                        N->getOperand(1), N->getOperand(2));
11285   case Intrinsic::aarch64_neon_fminnm:
11286     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11287                        N->getOperand(1), N->getOperand(2));
11288   case Intrinsic::aarch64_neon_smull:
11289   case Intrinsic::aarch64_neon_umull:
11290   case Intrinsic::aarch64_neon_pmull:
11291   case Intrinsic::aarch64_neon_sqdmull:
11292     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11293   case Intrinsic::aarch64_neon_sqshl:
11294   case Intrinsic::aarch64_neon_uqshl:
11295   case Intrinsic::aarch64_neon_sqshlu:
11296   case Intrinsic::aarch64_neon_srshl:
11297   case Intrinsic::aarch64_neon_urshl:
11298   case Intrinsic::aarch64_neon_sshl:
11299   case Intrinsic::aarch64_neon_ushl:
11300     return tryCombineShiftImm(IID, N, DAG);
11301   case Intrinsic::aarch64_crc32b:
11302   case Intrinsic::aarch64_crc32cb:
11303     return tryCombineCRC32(0xff, N, DAG);
11304   case Intrinsic::aarch64_crc32h:
11305   case Intrinsic::aarch64_crc32ch:
11306     return tryCombineCRC32(0xffff, N, DAG);
11307   case Intrinsic::aarch64_sve_smaxv:
11308     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11309   case Intrinsic::aarch64_sve_umaxv:
11310     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11311   case Intrinsic::aarch64_sve_sminv:
11312     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11313   case Intrinsic::aarch64_sve_uminv:
11314     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11315   case Intrinsic::aarch64_sve_orv:
11316     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11317   case Intrinsic::aarch64_sve_eorv:
11318     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11319   case Intrinsic::aarch64_sve_andv:
11320     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11321   case Intrinsic::aarch64_sve_index:
11322     return LowerSVEIntrinsicIndex(N, DAG);
11323   case Intrinsic::aarch64_sve_dup:
11324     return LowerSVEIntrinsicDUP(N, DAG);
11325   case Intrinsic::aarch64_sve_dup_x:
11326     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
11327                        N->getOperand(1));
11328   case Intrinsic::aarch64_sve_ext:
11329     return LowerSVEIntrinsicEXT(N, DAG);
11330   case Intrinsic::aarch64_sve_sel:
11331     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
11332                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11333   case Intrinsic::aarch64_sve_cmpeq_wide:
11334     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
11335                                     false, DCI, DAG);
11336   case Intrinsic::aarch64_sve_cmpne_wide:
11337     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
11338                                     false, DCI, DAG);
11339   case Intrinsic::aarch64_sve_cmpge_wide:
11340     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11341                                     false, DCI, DAG);
11342   case Intrinsic::aarch64_sve_cmpgt_wide:
11343     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11344                                     false, DCI, DAG);
11345   case Intrinsic::aarch64_sve_cmplt_wide:
11346     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11347                                     true, DCI, DAG);
11348   case Intrinsic::aarch64_sve_cmple_wide:
11349     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11350                                     true, DCI, DAG);
11351   case Intrinsic::aarch64_sve_cmphs_wide:
11352     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11353                                     false, DCI, DAG);
11354   case Intrinsic::aarch64_sve_cmphi_wide:
11355     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11356                                     false, DCI, DAG);
11357   case Intrinsic::aarch64_sve_cmplo_wide:
11358     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11359                                     DCI, DAG);
11360   case Intrinsic::aarch64_sve_cmpls_wide:
11361     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11362                                     DCI, DAG);
11363   case Intrinsic::aarch64_sve_ptest_any:
11364     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11365                     AArch64CC::ANY_ACTIVE);
11366   case Intrinsic::aarch64_sve_ptest_first:
11367     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11368                     AArch64CC::FIRST_ACTIVE);
11369   case Intrinsic::aarch64_sve_ptest_last:
11370     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11371                     AArch64CC::LAST_ACTIVE);
11372   }
11373   return SDValue();
11374 }
11375 
11376 static SDValue performExtendCombine(SDNode *N,
11377                                     TargetLowering::DAGCombinerInfo &DCI,
11378                                     SelectionDAG &DAG) {
11379   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11380   // we can convert that DUP into another extract_high (of a bigger DUP), which
11381   // helps the backend to decide that an sabdl2 would be useful, saving a real
11382   // extract_high operation.
11383   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11384       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11385     SDNode *ABDNode = N->getOperand(0).getNode();
11386     unsigned IID = getIntrinsicID(ABDNode);
11387     if (IID == Intrinsic::aarch64_neon_sabd ||
11388         IID == Intrinsic::aarch64_neon_uabd) {
11389       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11390       if (!NewABD.getNode())
11391         return SDValue();
11392 
11393       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11394                          NewABD);
11395     }
11396   }
11397 
11398   // This is effectively a custom type legalization for AArch64.
11399   //
11400   // Type legalization will split an extend of a small, legal, type to a larger
11401   // illegal type by first splitting the destination type, often creating
11402   // illegal source types, which then get legalized in isel-confusing ways,
11403   // leading to really terrible codegen. E.g.,
11404   //   %result = v8i32 sext v8i8 %value
11405   // becomes
11406   //   %losrc = extract_subreg %value, ...
11407   //   %hisrc = extract_subreg %value, ...
11408   //   %lo = v4i32 sext v4i8 %losrc
11409   //   %hi = v4i32 sext v4i8 %hisrc
11410   // Things go rapidly downhill from there.
11411   //
11412   // For AArch64, the [sz]ext vector instructions can only go up one element
11413   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11414   // take two instructions.
11415   //
11416   // This implies that the most efficient way to do the extend from v8i8
11417   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11418   // the normal splitting to happen for the v8i16->v8i32.
11419 
11420   // This is pre-legalization to catch some cases where the default
11421   // type legalization will create ill-tempered code.
11422   if (!DCI.isBeforeLegalizeOps())
11423     return SDValue();
11424 
11425   // We're only interested in cleaning things up for non-legal vector types
11426   // here. If both the source and destination are legal, things will just
11427   // work naturally without any fiddling.
11428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11429   EVT ResVT = N->getValueType(0);
11430   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11431     return SDValue();
11432   // If the vector type isn't a simple VT, it's beyond the scope of what
11433   // we're  worried about here. Let legalization do its thing and hope for
11434   // the best.
11435   SDValue Src = N->getOperand(0);
11436   EVT SrcVT = Src->getValueType(0);
11437   if (!ResVT.isSimple() || !SrcVT.isSimple())
11438     return SDValue();
11439 
11440   // If the source VT is a 64-bit vector, we can play games and get the
11441   // better results we want.
11442   if (SrcVT.getSizeInBits() != 64)
11443     return SDValue();
11444 
11445   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11446   unsigned ElementCount = SrcVT.getVectorNumElements();
11447   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11448   SDLoc DL(N);
11449   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11450 
11451   // Now split the rest of the operation into two halves, each with a 64
11452   // bit source.
11453   EVT LoVT, HiVT;
11454   SDValue Lo, Hi;
11455   unsigned NumElements = ResVT.getVectorNumElements();
11456   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11457   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11458                                  ResVT.getVectorElementType(), NumElements / 2);
11459 
11460   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11461                                LoVT.getVectorNumElements());
11462   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11463                    DAG.getConstant(0, DL, MVT::i64));
11464   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11465                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11466   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11467   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11468 
11469   // Now combine the parts back together so we still have a single result
11470   // like the combiner expects.
11471   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11472 }
11473 
11474 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11475                                SDValue SplatVal, unsigned NumVecElts) {
11476   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11477   unsigned OrigAlignment = St.getAlignment();
11478   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11479 
11480   // Create scalar stores. This is at least as good as the code sequence for a
11481   // split unaligned store which is a dup.s, ext.b, and two stores.
11482   // Most of the time the three stores should be replaced by store pair
11483   // instructions (stp).
11484   SDLoc DL(&St);
11485   SDValue BasePtr = St.getBasePtr();
11486   uint64_t BaseOffset = 0;
11487 
11488   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11489   SDValue NewST1 =
11490       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11491                    OrigAlignment, St.getMemOperand()->getFlags());
11492 
11493   // As this in ISel, we will not merge this add which may degrade results.
11494   if (BasePtr->getOpcode() == ISD::ADD &&
11495       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11496     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11497     BasePtr = BasePtr->getOperand(0);
11498   }
11499 
11500   unsigned Offset = EltOffset;
11501   while (--NumVecElts) {
11502     unsigned Alignment = MinAlign(OrigAlignment, Offset);
11503     SDValue OffsetPtr =
11504         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11505                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11506     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11507                           PtrInfo.getWithOffset(Offset), Alignment,
11508                           St.getMemOperand()->getFlags());
11509     Offset += EltOffset;
11510   }
11511   return NewST1;
11512 }
11513 
11514 // Returns an SVE type that ContentTy can be trivially sign or zero extended
11515 // into.
11516 static MVT getSVEContainerType(EVT ContentTy) {
11517   assert(ContentTy.isSimple() && "No SVE containers for extended types");
11518 
11519   switch (ContentTy.getSimpleVT().SimpleTy) {
11520   default:
11521     llvm_unreachable("No known SVE container for this MVT type");
11522   case MVT::nxv2i8:
11523   case MVT::nxv2i16:
11524   case MVT::nxv2i32:
11525   case MVT::nxv2i64:
11526   case MVT::nxv2f32:
11527   case MVT::nxv2f64:
11528     return MVT::nxv2i64;
11529   case MVT::nxv4i8:
11530   case MVT::nxv4i16:
11531   case MVT::nxv4i32:
11532   case MVT::nxv4f32:
11533     return MVT::nxv4i32;
11534   case MVT::nxv8i8:
11535   case MVT::nxv8i16:
11536   case MVT::nxv8f16:
11537     return MVT::nxv8i16;
11538   case MVT::nxv16i8:
11539     return MVT::nxv16i8;
11540   }
11541 }
11542 
11543 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG) {
11544   SDLoc DL(N);
11545   EVT VT = N->getValueType(0);
11546   EVT PtrTy = N->getOperand(3).getValueType();
11547 
11548   EVT LoadVT = VT;
11549   if (VT.isFloatingPoint())
11550     LoadVT = VT.changeTypeToInteger();
11551 
11552   auto *MINode = cast<MemIntrinsicSDNode>(N);
11553   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11554   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11555                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11556                                 MINode->getOperand(2), PassThru,
11557                                 MINode->getMemoryVT(), MINode->getMemOperand(),
11558                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11559 
11560    if (VT.isFloatingPoint()) {
11561      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11562      return DAG.getMergeValues(Ops, DL);
11563    }
11564 
11565   return L;
11566 }
11567 
11568 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
11569   SDLoc DL(N);
11570 
11571   SDValue Data = N->getOperand(2);
11572   EVT DataVT = Data.getValueType();
11573   EVT PtrTy = N->getOperand(4).getValueType();
11574 
11575   if (DataVT.isFloatingPoint())
11576     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11577 
11578   auto *MINode = cast<MemIntrinsicSDNode>(N);
11579   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11580                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11581                             MINode->getMemoryVT(), MINode->getMemOperand(),
11582                             ISD::UNINDEXED, false, false);
11583 }
11584 
11585 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
11586   SDLoc DL(N);
11587   EVT VT = N->getValueType(0);
11588 
11589   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
11590     return SDValue();
11591 
11592   EVT ContainerVT = VT;
11593   if (ContainerVT.isInteger())
11594     ContainerVT = getSVEContainerType(ContainerVT);
11595 
11596   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
11597   SDValue Ops[] = { N->getOperand(0), // Chain
11598                     N->getOperand(2), // Pg
11599                     N->getOperand(3), // Base
11600                     DAG.getValueType(VT) };
11601 
11602   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
11603   SDValue LoadChain = SDValue(Load.getNode(), 1);
11604 
11605   if (ContainerVT.isInteger() && (VT != ContainerVT))
11606     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
11607 
11608   return DAG.getMergeValues({ Load, LoadChain }, DL);
11609 }
11610 
11611 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
11612 /// load store optimizer pass will merge them to store pair stores.  This should
11613 /// be better than a movi to create the vector zero followed by a vector store
11614 /// if the zero constant is not re-used, since one instructions and one register
11615 /// live range will be removed.
11616 ///
11617 /// For example, the final generated code should be:
11618 ///
11619 ///   stp xzr, xzr, [x0]
11620 ///
11621 /// instead of:
11622 ///
11623 ///   movi v0.2d, #0
11624 ///   str q0, [x0]
11625 ///
11626 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11627   SDValue StVal = St.getValue();
11628   EVT VT = StVal.getValueType();
11629 
11630   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11631   // 2, 3 or 4 i32 elements.
11632   int NumVecElts = VT.getVectorNumElements();
11633   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11634          VT.getVectorElementType().getSizeInBits() == 64) ||
11635         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11636          VT.getVectorElementType().getSizeInBits() == 32)))
11637     return SDValue();
11638 
11639   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11640     return SDValue();
11641 
11642   // If the zero constant has more than one use then the vector store could be
11643   // better since the constant mov will be amortized and stp q instructions
11644   // should be able to be formed.
11645   if (!StVal.hasOneUse())
11646     return SDValue();
11647 
11648   // If the store is truncating then it's going down to i16 or smaller, which
11649   // means it can be implemented in a single store anyway.
11650   if (St.isTruncatingStore())
11651     return SDValue();
11652 
11653   // If the immediate offset of the address operand is too large for the stp
11654   // instruction, then bail out.
11655   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11656     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11657     if (Offset < -512 || Offset > 504)
11658       return SDValue();
11659   }
11660 
11661   for (int I = 0; I < NumVecElts; ++I) {
11662     SDValue EltVal = StVal.getOperand(I);
11663     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11664       return SDValue();
11665   }
11666 
11667   // Use a CopyFromReg WZR/XZR here to prevent
11668   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11669   SDLoc DL(&St);
11670   unsigned ZeroReg;
11671   EVT ZeroVT;
11672   if (VT.getVectorElementType().getSizeInBits() == 32) {
11673     ZeroReg = AArch64::WZR;
11674     ZeroVT = MVT::i32;
11675   } else {
11676     ZeroReg = AArch64::XZR;
11677     ZeroVT = MVT::i64;
11678   }
11679   SDValue SplatVal =
11680       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11681   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11682 }
11683 
11684 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11685 /// value. The load store optimizer pass will merge them to store pair stores.
11686 /// This has better performance than a splat of the scalar followed by a split
11687 /// vector store. Even if the stores are not merged it is four stores vs a dup,
11688 /// followed by an ext.b and two stores.
11689 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11690   SDValue StVal = St.getValue();
11691   EVT VT = StVal.getValueType();
11692 
11693   // Don't replace floating point stores, they possibly won't be transformed to
11694   // stp because of the store pair suppress pass.
11695   if (VT.isFloatingPoint())
11696     return SDValue();
11697 
11698   // We can express a splat as store pair(s) for 2 or 4 elements.
11699   unsigned NumVecElts = VT.getVectorNumElements();
11700   if (NumVecElts != 4 && NumVecElts != 2)
11701     return SDValue();
11702 
11703   // If the store is truncating then it's going down to i16 or smaller, which
11704   // means it can be implemented in a single store anyway.
11705   if (St.isTruncatingStore())
11706     return SDValue();
11707 
11708   // Check that this is a splat.
11709   // Make sure that each of the relevant vector element locations are inserted
11710   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11711   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11712   SDValue SplatVal;
11713   for (unsigned I = 0; I < NumVecElts; ++I) {
11714     // Check for insert vector elements.
11715     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11716       return SDValue();
11717 
11718     // Check that same value is inserted at each vector element.
11719     if (I == 0)
11720       SplatVal = StVal.getOperand(1);
11721     else if (StVal.getOperand(1) != SplatVal)
11722       return SDValue();
11723 
11724     // Check insert element index.
11725     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11726     if (!CIndex)
11727       return SDValue();
11728     uint64_t IndexVal = CIndex->getZExtValue();
11729     if (IndexVal >= NumVecElts)
11730       return SDValue();
11731     IndexNotInserted.reset(IndexVal);
11732 
11733     StVal = StVal.getOperand(0);
11734   }
11735   // Check that all vector element locations were inserted to.
11736   if (IndexNotInserted.any())
11737       return SDValue();
11738 
11739   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11740 }
11741 
11742 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11743                            SelectionDAG &DAG,
11744                            const AArch64Subtarget *Subtarget) {
11745 
11746   StoreSDNode *S = cast<StoreSDNode>(N);
11747   if (S->isVolatile() || S->isIndexed())
11748     return SDValue();
11749 
11750   SDValue StVal = S->getValue();
11751   EVT VT = StVal.getValueType();
11752   if (!VT.isVector())
11753     return SDValue();
11754 
11755   // If we get a splat of zeros, convert this vector store to a store of
11756   // scalars. They will be merged into store pairs of xzr thereby removing one
11757   // instruction and one register.
11758   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11759     return ReplacedZeroSplat;
11760 
11761   // FIXME: The logic for deciding if an unaligned store should be split should
11762   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11763   // a call to that function here.
11764 
11765   if (!Subtarget->isMisaligned128StoreSlow())
11766     return SDValue();
11767 
11768   // Don't split at -Oz.
11769   if (DAG.getMachineFunction().getFunction().hasMinSize())
11770     return SDValue();
11771 
11772   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11773   // those up regresses performance on micro-benchmarks and olden/bh.
11774   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11775     return SDValue();
11776 
11777   // Split unaligned 16B stores. They are terrible for performance.
11778   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11779   // extensions can use this to mark that it does not want splitting to happen
11780   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11781   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11782   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11783       S->getAlignment() <= 2)
11784     return SDValue();
11785 
11786   // If we get a splat of a scalar convert this vector store to a store of
11787   // scalars. They will be merged into store pairs thereby removing two
11788   // instructions.
11789   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11790     return ReplacedSplat;
11791 
11792   SDLoc DL(S);
11793 
11794   // Split VT into two.
11795   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11796   unsigned NumElts = HalfVT.getVectorNumElements();
11797   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11798                                    DAG.getConstant(0, DL, MVT::i64));
11799   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11800                                    DAG.getConstant(NumElts, DL, MVT::i64));
11801   SDValue BasePtr = S->getBasePtr();
11802   SDValue NewST1 =
11803       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11804                    S->getAlignment(), S->getMemOperand()->getFlags());
11805   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11806                                   DAG.getConstant(8, DL, MVT::i64));
11807   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11808                       S->getPointerInfo(), S->getAlignment(),
11809                       S->getMemOperand()->getFlags());
11810 }
11811 
11812 /// Target-specific DAG combine function for post-increment LD1 (lane) and
11813 /// post-increment LD1R.
11814 static SDValue performPostLD1Combine(SDNode *N,
11815                                      TargetLowering::DAGCombinerInfo &DCI,
11816                                      bool IsLaneOp) {
11817   if (DCI.isBeforeLegalizeOps())
11818     return SDValue();
11819 
11820   SelectionDAG &DAG = DCI.DAG;
11821   EVT VT = N->getValueType(0);
11822 
11823   unsigned LoadIdx = IsLaneOp ? 1 : 0;
11824   SDNode *LD = N->getOperand(LoadIdx).getNode();
11825   // If it is not LOAD, can not do such combine.
11826   if (LD->getOpcode() != ISD::LOAD)
11827     return SDValue();
11828 
11829   // The vector lane must be a constant in the LD1LANE opcode.
11830   SDValue Lane;
11831   if (IsLaneOp) {
11832     Lane = N->getOperand(2);
11833     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11834     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11835       return SDValue();
11836   }
11837 
11838   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11839   EVT MemVT = LoadSDN->getMemoryVT();
11840   // Check if memory operand is the same type as the vector element.
11841   if (MemVT != VT.getVectorElementType())
11842     return SDValue();
11843 
11844   // Check if there are other uses. If so, do not combine as it will introduce
11845   // an extra load.
11846   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11847        ++UI) {
11848     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11849       continue;
11850     if (*UI != N)
11851       return SDValue();
11852   }
11853 
11854   SDValue Addr = LD->getOperand(1);
11855   SDValue Vector = N->getOperand(0);
11856   // Search for a use of the address operand that is an increment.
11857   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11858        Addr.getNode()->use_end(); UI != UE; ++UI) {
11859     SDNode *User = *UI;
11860     if (User->getOpcode() != ISD::ADD
11861         || UI.getUse().getResNo() != Addr.getResNo())
11862       continue;
11863 
11864     // If the increment is a constant, it must match the memory ref size.
11865     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11866     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11867       uint32_t IncVal = CInc->getZExtValue();
11868       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11869       if (IncVal != NumBytes)
11870         continue;
11871       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11872     }
11873 
11874     // To avoid cycle construction make sure that neither the load nor the add
11875     // are predecessors to each other or the Vector.
11876     SmallPtrSet<const SDNode *, 32> Visited;
11877     SmallVector<const SDNode *, 16> Worklist;
11878     Visited.insert(Addr.getNode());
11879     Worklist.push_back(User);
11880     Worklist.push_back(LD);
11881     Worklist.push_back(Vector.getNode());
11882     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11883         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11884       continue;
11885 
11886     SmallVector<SDValue, 8> Ops;
11887     Ops.push_back(LD->getOperand(0));  // Chain
11888     if (IsLaneOp) {
11889       Ops.push_back(Vector);           // The vector to be inserted
11890       Ops.push_back(Lane);             // The lane to be inserted in the vector
11891     }
11892     Ops.push_back(Addr);
11893     Ops.push_back(Inc);
11894 
11895     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11896     SDVTList SDTys = DAG.getVTList(Tys);
11897     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11898     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11899                                            MemVT,
11900                                            LoadSDN->getMemOperand());
11901 
11902     // Update the uses.
11903     SDValue NewResults[] = {
11904         SDValue(LD, 0),            // The result of load
11905         SDValue(UpdN.getNode(), 2) // Chain
11906     };
11907     DCI.CombineTo(LD, NewResults);
11908     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
11909     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
11910 
11911     break;
11912   }
11913   return SDValue();
11914 }
11915 
11916 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11917 /// address translation.
11918 static bool performTBISimplification(SDValue Addr,
11919                                      TargetLowering::DAGCombinerInfo &DCI,
11920                                      SelectionDAG &DAG) {
11921   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11922   KnownBits Known;
11923   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11924                                         !DCI.isBeforeLegalizeOps());
11925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11926   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11927     DCI.CommitTargetLoweringOpt(TLO);
11928     return true;
11929   }
11930   return false;
11931 }
11932 
11933 static SDValue performSTORECombine(SDNode *N,
11934                                    TargetLowering::DAGCombinerInfo &DCI,
11935                                    SelectionDAG &DAG,
11936                                    const AArch64Subtarget *Subtarget) {
11937   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11938     return Split;
11939 
11940   if (Subtarget->supportsAddressTopByteIgnored() &&
11941       performTBISimplification(N->getOperand(2), DCI, DAG))
11942     return SDValue(N, 0);
11943 
11944   return SDValue();
11945 }
11946 
11947 
11948 /// Target-specific DAG combine function for NEON load/store intrinsics
11949 /// to merge base address updates.
11950 static SDValue performNEONPostLDSTCombine(SDNode *N,
11951                                           TargetLowering::DAGCombinerInfo &DCI,
11952                                           SelectionDAG &DAG) {
11953   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11954     return SDValue();
11955 
11956   unsigned AddrOpIdx = N->getNumOperands() - 1;
11957   SDValue Addr = N->getOperand(AddrOpIdx);
11958 
11959   // Search for a use of the address operand that is an increment.
11960   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11961        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11962     SDNode *User = *UI;
11963     if (User->getOpcode() != ISD::ADD ||
11964         UI.getUse().getResNo() != Addr.getResNo())
11965       continue;
11966 
11967     // Check that the add is independent of the load/store.  Otherwise, folding
11968     // it would create a cycle.
11969     SmallPtrSet<const SDNode *, 32> Visited;
11970     SmallVector<const SDNode *, 16> Worklist;
11971     Visited.insert(Addr.getNode());
11972     Worklist.push_back(N);
11973     Worklist.push_back(User);
11974     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11975         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11976       continue;
11977 
11978     // Find the new opcode for the updating load/store.
11979     bool IsStore = false;
11980     bool IsLaneOp = false;
11981     bool IsDupOp = false;
11982     unsigned NewOpc = 0;
11983     unsigned NumVecs = 0;
11984     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11985     switch (IntNo) {
11986     default: llvm_unreachable("unexpected intrinsic for Neon base update");
11987     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11988       NumVecs = 2; break;
11989     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11990       NumVecs = 3; break;
11991     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11992       NumVecs = 4; break;
11993     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11994       NumVecs = 2; IsStore = true; break;
11995     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11996       NumVecs = 3; IsStore = true; break;
11997     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11998       NumVecs = 4; IsStore = true; break;
11999     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
12000       NumVecs = 2; break;
12001     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
12002       NumVecs = 3; break;
12003     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
12004       NumVecs = 4; break;
12005     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
12006       NumVecs = 2; IsStore = true; break;
12007     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
12008       NumVecs = 3; IsStore = true; break;
12009     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
12010       NumVecs = 4; IsStore = true; break;
12011     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
12012       NumVecs = 2; IsDupOp = true; break;
12013     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
12014       NumVecs = 3; IsDupOp = true; break;
12015     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
12016       NumVecs = 4; IsDupOp = true; break;
12017     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
12018       NumVecs = 2; IsLaneOp = true; break;
12019     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
12020       NumVecs = 3; IsLaneOp = true; break;
12021     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
12022       NumVecs = 4; IsLaneOp = true; break;
12023     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
12024       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
12025     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
12026       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
12027     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
12028       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
12029     }
12030 
12031     EVT VecTy;
12032     if (IsStore)
12033       VecTy = N->getOperand(2).getValueType();
12034     else
12035       VecTy = N->getValueType(0);
12036 
12037     // If the increment is a constant, it must match the memory ref size.
12038     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12039     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12040       uint32_t IncVal = CInc->getZExtValue();
12041       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12042       if (IsLaneOp || IsDupOp)
12043         NumBytes /= VecTy.getVectorNumElements();
12044       if (IncVal != NumBytes)
12045         continue;
12046       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12047     }
12048     SmallVector<SDValue, 8> Ops;
12049     Ops.push_back(N->getOperand(0)); // Incoming chain
12050     // Load lane and store have vector list as input.
12051     if (IsLaneOp || IsStore)
12052       for (unsigned i = 2; i < AddrOpIdx; ++i)
12053         Ops.push_back(N->getOperand(i));
12054     Ops.push_back(Addr); // Base register
12055     Ops.push_back(Inc);
12056 
12057     // Return Types.
12058     EVT Tys[6];
12059     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
12060     unsigned n;
12061     for (n = 0; n < NumResultVecs; ++n)
12062       Tys[n] = VecTy;
12063     Tys[n++] = MVT::i64;  // Type of write back register
12064     Tys[n] = MVT::Other;  // Type of the chain
12065     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
12066 
12067     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
12068     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
12069                                            MemInt->getMemoryVT(),
12070                                            MemInt->getMemOperand());
12071 
12072     // Update the uses.
12073     std::vector<SDValue> NewResults;
12074     for (unsigned i = 0; i < NumResultVecs; ++i) {
12075       NewResults.push_back(SDValue(UpdN.getNode(), i));
12076     }
12077     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
12078     DCI.CombineTo(N, NewResults);
12079     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12080 
12081     break;
12082   }
12083   return SDValue();
12084 }
12085 
12086 // Checks to see if the value is the prescribed width and returns information
12087 // about its extension mode.
12088 static
12089 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
12090   ExtType = ISD::NON_EXTLOAD;
12091   switch(V.getNode()->getOpcode()) {
12092   default:
12093     return false;
12094   case ISD::LOAD: {
12095     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
12096     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
12097        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
12098       ExtType = LoadNode->getExtensionType();
12099       return true;
12100     }
12101     return false;
12102   }
12103   case ISD::AssertSext: {
12104     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12105     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12106        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12107       ExtType = ISD::SEXTLOAD;
12108       return true;
12109     }
12110     return false;
12111   }
12112   case ISD::AssertZext: {
12113     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12114     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12115        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12116       ExtType = ISD::ZEXTLOAD;
12117       return true;
12118     }
12119     return false;
12120   }
12121   case ISD::Constant:
12122   case ISD::TargetConstant: {
12123     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
12124            1LL << (width - 1);
12125   }
12126   }
12127 
12128   return true;
12129 }
12130 
12131 // This function does a whole lot of voodoo to determine if the tests are
12132 // equivalent without and with a mask. Essentially what happens is that given a
12133 // DAG resembling:
12134 //
12135 //  +-------------+ +-------------+ +-------------+ +-------------+
12136 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
12137 //  +-------------+ +-------------+ +-------------+ +-------------+
12138 //           |           |           |               |
12139 //           V           V           |    +----------+
12140 //          +-------------+  +----+  |    |
12141 //          |     ADD     |  |0xff|  |    |
12142 //          +-------------+  +----+  |    |
12143 //                  |           |    |    |
12144 //                  V           V    |    |
12145 //                 +-------------+   |    |
12146 //                 |     AND     |   |    |
12147 //                 +-------------+   |    |
12148 //                      |            |    |
12149 //                      +-----+      |    |
12150 //                            |      |    |
12151 //                            V      V    V
12152 //                           +-------------+
12153 //                           |     CMP     |
12154 //                           +-------------+
12155 //
12156 // The AND node may be safely removed for some combinations of inputs. In
12157 // particular we need to take into account the extension type of the Input,
12158 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
12159 // width of the input (this can work for any width inputs, the above graph is
12160 // specific to 8 bits.
12161 //
12162 // The specific equations were worked out by generating output tables for each
12163 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
12164 // problem was simplified by working with 4 bit inputs, which means we only
12165 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
12166 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
12167 // patterns present in both extensions (0,7). For every distinct set of
12168 // AddConstant and CompConstants bit patterns we can consider the masked and
12169 // unmasked versions to be equivalent if the result of this function is true for
12170 // all 16 distinct bit patterns of for the current extension type of Input (w0).
12171 //
12172 //   sub      w8, w0, w1
12173 //   and      w10, w8, #0x0f
12174 //   cmp      w8, w2
12175 //   cset     w9, AArch64CC
12176 //   cmp      w10, w2
12177 //   cset     w11, AArch64CC
12178 //   cmp      w9, w11
12179 //   cset     w0, eq
12180 //   ret
12181 //
12182 // Since the above function shows when the outputs are equivalent it defines
12183 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
12184 // would be expensive to run during compiles. The equations below were written
12185 // in a test harness that confirmed they gave equivalent outputs to the above
12186 // for all inputs function, so they can be used determine if the removal is
12187 // legal instead.
12188 //
12189 // isEquivalentMaskless() is the code for testing if the AND can be removed
12190 // factored out of the DAG recognition as the DAG can take several forms.
12191 
12192 static bool isEquivalentMaskless(unsigned CC, unsigned width,
12193                                  ISD::LoadExtType ExtType, int AddConstant,
12194                                  int CompConstant) {
12195   // By being careful about our equations and only writing the in term
12196   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
12197   // make them generally applicable to all bit widths.
12198   int MaxUInt = (1 << width);
12199 
12200   // For the purposes of these comparisons sign extending the type is
12201   // equivalent to zero extending the add and displacing it by half the integer
12202   // width. Provided we are careful and make sure our equations are valid over
12203   // the whole range we can just adjust the input and avoid writing equations
12204   // for sign extended inputs.
12205   if (ExtType == ISD::SEXTLOAD)
12206     AddConstant -= (1 << (width-1));
12207 
12208   switch(CC) {
12209   case AArch64CC::LE:
12210   case AArch64CC::GT:
12211     if ((AddConstant == 0) ||
12212         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
12213         (AddConstant >= 0 && CompConstant < 0) ||
12214         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
12215       return true;
12216     break;
12217   case AArch64CC::LT:
12218   case AArch64CC::GE:
12219     if ((AddConstant == 0) ||
12220         (AddConstant >= 0 && CompConstant <= 0) ||
12221         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
12222       return true;
12223     break;
12224   case AArch64CC::HI:
12225   case AArch64CC::LS:
12226     if ((AddConstant >= 0 && CompConstant < 0) ||
12227        (AddConstant <= 0 && CompConstant >= -1 &&
12228         CompConstant < AddConstant + MaxUInt))
12229       return true;
12230    break;
12231   case AArch64CC::PL:
12232   case AArch64CC::MI:
12233     if ((AddConstant == 0) ||
12234         (AddConstant > 0 && CompConstant <= 0) ||
12235         (AddConstant < 0 && CompConstant <= AddConstant))
12236       return true;
12237     break;
12238   case AArch64CC::LO:
12239   case AArch64CC::HS:
12240     if ((AddConstant >= 0 && CompConstant <= 0) ||
12241         (AddConstant <= 0 && CompConstant >= 0 &&
12242          CompConstant <= AddConstant + MaxUInt))
12243       return true;
12244     break;
12245   case AArch64CC::EQ:
12246   case AArch64CC::NE:
12247     if ((AddConstant > 0 && CompConstant < 0) ||
12248         (AddConstant < 0 && CompConstant >= 0 &&
12249          CompConstant < AddConstant + MaxUInt) ||
12250         (AddConstant >= 0 && CompConstant >= 0 &&
12251          CompConstant >= AddConstant) ||
12252         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
12253       return true;
12254     break;
12255   case AArch64CC::VS:
12256   case AArch64CC::VC:
12257   case AArch64CC::AL:
12258   case AArch64CC::NV:
12259     return true;
12260   case AArch64CC::Invalid:
12261     break;
12262   }
12263 
12264   return false;
12265 }
12266 
12267 static
12268 SDValue performCONDCombine(SDNode *N,
12269                            TargetLowering::DAGCombinerInfo &DCI,
12270                            SelectionDAG &DAG, unsigned CCIndex,
12271                            unsigned CmpIndex) {
12272   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
12273   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
12274   unsigned CondOpcode = SubsNode->getOpcode();
12275 
12276   if (CondOpcode != AArch64ISD::SUBS)
12277     return SDValue();
12278 
12279   // There is a SUBS feeding this condition. Is it fed by a mask we can
12280   // use?
12281 
12282   SDNode *AndNode = SubsNode->getOperand(0).getNode();
12283   unsigned MaskBits = 0;
12284 
12285   if (AndNode->getOpcode() != ISD::AND)
12286     return SDValue();
12287 
12288   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
12289     uint32_t CNV = CN->getZExtValue();
12290     if (CNV == 255)
12291       MaskBits = 8;
12292     else if (CNV == 65535)
12293       MaskBits = 16;
12294   }
12295 
12296   if (!MaskBits)
12297     return SDValue();
12298 
12299   SDValue AddValue = AndNode->getOperand(0);
12300 
12301   if (AddValue.getOpcode() != ISD::ADD)
12302     return SDValue();
12303 
12304   // The basic dag structure is correct, grab the inputs and validate them.
12305 
12306   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
12307   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
12308   SDValue SubsInputValue = SubsNode->getOperand(1);
12309 
12310   // The mask is present and the provenance of all the values is a smaller type,
12311   // lets see if the mask is superfluous.
12312 
12313   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
12314       !isa<ConstantSDNode>(SubsInputValue.getNode()))
12315     return SDValue();
12316 
12317   ISD::LoadExtType ExtType;
12318 
12319   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
12320       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
12321       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
12322     return SDValue();
12323 
12324   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
12325                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
12326                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
12327     return SDValue();
12328 
12329   // The AND is not necessary, remove it.
12330 
12331   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
12332                                SubsNode->getValueType(1));
12333   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
12334 
12335   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
12336   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
12337 
12338   return SDValue(N, 0);
12339 }
12340 
12341 // Optimize compare with zero and branch.
12342 static SDValue performBRCONDCombine(SDNode *N,
12343                                     TargetLowering::DAGCombinerInfo &DCI,
12344                                     SelectionDAG &DAG) {
12345   MachineFunction &MF = DAG.getMachineFunction();
12346   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
12347   // will not be produced, as they are conditional branch instructions that do
12348   // not set flags.
12349   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
12350     return SDValue();
12351 
12352   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
12353     N = NV.getNode();
12354   SDValue Chain = N->getOperand(0);
12355   SDValue Dest = N->getOperand(1);
12356   SDValue CCVal = N->getOperand(2);
12357   SDValue Cmp = N->getOperand(3);
12358 
12359   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
12360   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
12361   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
12362     return SDValue();
12363 
12364   unsigned CmpOpc = Cmp.getOpcode();
12365   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
12366     return SDValue();
12367 
12368   // Only attempt folding if there is only one use of the flag and no use of the
12369   // value.
12370   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
12371     return SDValue();
12372 
12373   SDValue LHS = Cmp.getOperand(0);
12374   SDValue RHS = Cmp.getOperand(1);
12375 
12376   assert(LHS.getValueType() == RHS.getValueType() &&
12377          "Expected the value type to be the same for both operands!");
12378   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
12379     return SDValue();
12380 
12381   if (isNullConstant(LHS))
12382     std::swap(LHS, RHS);
12383 
12384   if (!isNullConstant(RHS))
12385     return SDValue();
12386 
12387   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
12388       LHS.getOpcode() == ISD::SRL)
12389     return SDValue();
12390 
12391   // Fold the compare into the branch instruction.
12392   SDValue BR;
12393   if (CC == AArch64CC::EQ)
12394     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12395   else
12396     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12397 
12398   // Do not add new nodes to DAG combiner worklist.
12399   DCI.CombineTo(N, BR, false);
12400 
12401   return SDValue();
12402 }
12403 
12404 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
12405 // as well as whether the test should be inverted.  This code is required to
12406 // catch these cases (as opposed to standard dag combines) because
12407 // AArch64ISD::TBZ is matched during legalization.
12408 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12409                                  SelectionDAG &DAG) {
12410 
12411   if (!Op->hasOneUse())
12412     return Op;
12413 
12414   // We don't handle undef/constant-fold cases below, as they should have
12415   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12416   // etc.)
12417 
12418   // (tbz (trunc x), b) -> (tbz x, b)
12419   // This case is just here to enable more of the below cases to be caught.
12420   if (Op->getOpcode() == ISD::TRUNCATE &&
12421       Bit < Op->getValueType(0).getSizeInBits()) {
12422     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12423   }
12424 
12425   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12426   if (Op->getOpcode() == ISD::ANY_EXTEND &&
12427       Bit < Op->getOperand(0).getValueSizeInBits()) {
12428     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12429   }
12430 
12431   if (Op->getNumOperands() != 2)
12432     return Op;
12433 
12434   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12435   if (!C)
12436     return Op;
12437 
12438   switch (Op->getOpcode()) {
12439   default:
12440     return Op;
12441 
12442   // (tbz (and x, m), b) -> (tbz x, b)
12443   case ISD::AND:
12444     if ((C->getZExtValue() >> Bit) & 1)
12445       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12446     return Op;
12447 
12448   // (tbz (shl x, c), b) -> (tbz x, b-c)
12449   case ISD::SHL:
12450     if (C->getZExtValue() <= Bit &&
12451         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12452       Bit = Bit - C->getZExtValue();
12453       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12454     }
12455     return Op;
12456 
12457   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12458   case ISD::SRA:
12459     Bit = Bit + C->getZExtValue();
12460     if (Bit >= Op->getValueType(0).getSizeInBits())
12461       Bit = Op->getValueType(0).getSizeInBits() - 1;
12462     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12463 
12464   // (tbz (srl x, c), b) -> (tbz x, b+c)
12465   case ISD::SRL:
12466     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12467       Bit = Bit + C->getZExtValue();
12468       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12469     }
12470     return Op;
12471 
12472   // (tbz (xor x, -1), b) -> (tbnz x, b)
12473   case ISD::XOR:
12474     if ((C->getZExtValue() >> Bit) & 1)
12475       Invert = !Invert;
12476     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12477   }
12478 }
12479 
12480 // Optimize test single bit zero/non-zero and branch.
12481 static SDValue performTBZCombine(SDNode *N,
12482                                  TargetLowering::DAGCombinerInfo &DCI,
12483                                  SelectionDAG &DAG) {
12484   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12485   bool Invert = false;
12486   SDValue TestSrc = N->getOperand(1);
12487   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12488 
12489   if (TestSrc == NewTestSrc)
12490     return SDValue();
12491 
12492   unsigned NewOpc = N->getOpcode();
12493   if (Invert) {
12494     if (NewOpc == AArch64ISD::TBZ)
12495       NewOpc = AArch64ISD::TBNZ;
12496     else {
12497       assert(NewOpc == AArch64ISD::TBNZ);
12498       NewOpc = AArch64ISD::TBZ;
12499     }
12500   }
12501 
12502   SDLoc DL(N);
12503   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12504                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12505 }
12506 
12507 // vselect (v1i1 setcc) ->
12508 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
12509 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12510 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12511 // such VSELECT.
12512 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12513   SDValue N0 = N->getOperand(0);
12514   EVT CCVT = N0.getValueType();
12515 
12516   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12517       CCVT.getVectorElementType() != MVT::i1)
12518     return SDValue();
12519 
12520   EVT ResVT = N->getValueType(0);
12521   EVT CmpVT = N0.getOperand(0).getValueType();
12522   // Only combine when the result type is of the same size as the compared
12523   // operands.
12524   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12525     return SDValue();
12526 
12527   SDValue IfTrue = N->getOperand(1);
12528   SDValue IfFalse = N->getOperand(2);
12529   SDValue SetCC =
12530       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12531                    N0.getOperand(0), N0.getOperand(1),
12532                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
12533   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12534                      IfTrue, IfFalse);
12535 }
12536 
12537 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12538 /// the compare-mask instructions rather than going via NZCV, even if LHS and
12539 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
12540 /// with a vector one followed by a DUP shuffle on the result.
12541 static SDValue performSelectCombine(SDNode *N,
12542                                     TargetLowering::DAGCombinerInfo &DCI) {
12543   SelectionDAG &DAG = DCI.DAG;
12544   SDValue N0 = N->getOperand(0);
12545   EVT ResVT = N->getValueType(0);
12546 
12547   if (N0.getOpcode() != ISD::SETCC)
12548     return SDValue();
12549 
12550   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12551   // scalar SetCCResultType. We also don't expect vectors, because we assume
12552   // that selects fed by vector SETCCs are canonicalized to VSELECT.
12553   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12554          "Scalar-SETCC feeding SELECT has unexpected result type!");
12555 
12556   // If NumMaskElts == 0, the comparison is larger than select result. The
12557   // largest real NEON comparison is 64-bits per lane, which means the result is
12558   // at most 32-bits and an illegal vector. Just bail out for now.
12559   EVT SrcVT = N0.getOperand(0).getValueType();
12560 
12561   // Don't try to do this optimization when the setcc itself has i1 operands.
12562   // There are no legal vectors of i1, so this would be pointless.
12563   if (SrcVT == MVT::i1)
12564     return SDValue();
12565 
12566   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12567   if (!ResVT.isVector() || NumMaskElts == 0)
12568     return SDValue();
12569 
12570   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12571   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12572 
12573   // Also bail out if the vector CCVT isn't the same size as ResVT.
12574   // This can happen if the SETCC operand size doesn't divide the ResVT size
12575   // (e.g., f64 vs v3f32).
12576   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12577     return SDValue();
12578 
12579   // Make sure we didn't create illegal types, if we're not supposed to.
12580   assert(DCI.isBeforeLegalize() ||
12581          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12582 
12583   // First perform a vector comparison, where lane 0 is the one we're interested
12584   // in.
12585   SDLoc DL(N0);
12586   SDValue LHS =
12587       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12588   SDValue RHS =
12589       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12590   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12591 
12592   // Now duplicate the comparison mask we want across all other lanes.
12593   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12594   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12595   Mask = DAG.getNode(ISD::BITCAST, DL,
12596                      ResVT.changeVectorElementTypeToInteger(), Mask);
12597 
12598   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12599 }
12600 
12601 /// Get rid of unnecessary NVCASTs (that don't change the type).
12602 static SDValue performNVCASTCombine(SDNode *N) {
12603   if (N->getValueType(0) == N->getOperand(0).getValueType())
12604     return N->getOperand(0);
12605 
12606   return SDValue();
12607 }
12608 
12609 // If all users of the globaladdr are of the form (globaladdr + constant), find
12610 // the smallest constant, fold it into the globaladdr's offset and rewrite the
12611 // globaladdr as (globaladdr + constant) - constant.
12612 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12613                                            const AArch64Subtarget *Subtarget,
12614                                            const TargetMachine &TM) {
12615   auto *GN = cast<GlobalAddressSDNode>(N);
12616   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12617       AArch64II::MO_NO_FLAG)
12618     return SDValue();
12619 
12620   uint64_t MinOffset = -1ull;
12621   for (SDNode *N : GN->uses()) {
12622     if (N->getOpcode() != ISD::ADD)
12623       return SDValue();
12624     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12625     if (!C)
12626       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12627     if (!C)
12628       return SDValue();
12629     MinOffset = std::min(MinOffset, C->getZExtValue());
12630   }
12631   uint64_t Offset = MinOffset + GN->getOffset();
12632 
12633   // Require that the new offset is larger than the existing one. Otherwise, we
12634   // can end up oscillating between two possible DAGs, for example,
12635   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12636   if (Offset <= uint64_t(GN->getOffset()))
12637     return SDValue();
12638 
12639   // Check whether folding this offset is legal. It must not go out of bounds of
12640   // the referenced object to avoid violating the code model, and must be
12641   // smaller than 2^21 because this is the largest offset expressible in all
12642   // object formats.
12643   //
12644   // This check also prevents us from folding negative offsets, which will end
12645   // up being treated in the same way as large positive ones. They could also
12646   // cause code model violations, and aren't really common enough to matter.
12647   if (Offset >= (1 << 21))
12648     return SDValue();
12649 
12650   const GlobalValue *GV = GN->getGlobal();
12651   Type *T = GV->getValueType();
12652   if (!T->isSized() ||
12653       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12654     return SDValue();
12655 
12656   SDLoc DL(GN);
12657   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12658   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12659                      DAG.getConstant(MinOffset, DL, MVT::i64));
12660 }
12661 
12662 // Turns the vector of indices into a vector of byte offstes by scaling Offset
12663 // by (BitWidth / 8).
12664 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
12665                                           SDLoc DL, unsigned BitWidth) {
12666   assert(Offset.getValueType().isScalableVector() &&
12667          "This method is only for scalable vectors of offsets");
12668 
12669   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
12670   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
12671 
12672   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
12673 }
12674 
12675 /// Check if the value of \p OffsetInBytes can be used as an immediate for
12676 /// the gather load/prefetch and scatter store instructions with vector base and
12677 /// immediate offset addressing mode:
12678 ///
12679 ///      [<Zn>.[S|D]{, #<imm>}]
12680 ///
12681 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
12682 
12683 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
12684                                                   unsigned ScalarSizeInBytes) {
12685   // The immediate is not a multiple of the scalar size.
12686   if (OffsetInBytes % ScalarSizeInBytes)
12687     return false;
12688 
12689   // The immediate is out of range.
12690   if (OffsetInBytes / ScalarSizeInBytes > 31)
12691     return false;
12692 
12693   return true;
12694 }
12695 
12696 /// Check if the value of \p Offset represents a valid immediate for the SVE
12697 /// gather load/prefetch and scatter store instructiona with vector base and
12698 /// immediate offset addressing mode:
12699 ///
12700 ///      [<Zn>.[S|D]{, #<imm>}]
12701 ///
12702 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
12703 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
12704                                            unsigned ScalarSizeInBytes) {
12705   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12706   return OffsetConst && isValidImmForSVEVecImmAddrMode(
12707                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
12708 }
12709 
12710 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
12711                                           unsigned Opcode,
12712                                           bool OnlyPackedOffsets = true) {
12713   const SDValue Src = N->getOperand(2);
12714   const EVT SrcVT = Src->getValueType(0);
12715   assert(SrcVT.isScalableVector() &&
12716          "Scatter stores are only possible for SVE vectors");
12717 
12718   SDLoc DL(N);
12719   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12720 
12721   // Make sure that source data will fit into an SVE register
12722   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12723     return SDValue();
12724 
12725   // For FPs, ACLE only supports _packed_ single and double precision types.
12726   if (SrcElVT.isFloatingPoint())
12727     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12728       return SDValue();
12729 
12730   // Depending on the addressing mode, this is either a pointer or a vector of
12731   // pointers (that fits into one register)
12732   SDValue Base = N->getOperand(4);
12733   // Depending on the addressing mode, this is either a single offset or a
12734   // vector of offsets  (that fits into one register)
12735   SDValue Offset = N->getOperand(5);
12736 
12737   // For "scalar + vector of indices", just scale the indices. This only
12738   // applies to non-temporal scatters because there's no instruction that takes
12739   // indicies.
12740   if (Opcode == AArch64ISD::SSTNT1_INDEX) {
12741     Offset =
12742         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
12743     Opcode = AArch64ISD::SSTNT1;
12744   }
12745 
12746   // In the case of non-temporal gather loads there's only one SVE instruction
12747   // per data-size: "scalar + vector", i.e.
12748   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
12749   // Since we do have intrinsics that allow the arguments to be in a different
12750   // order, we may need to swap them to match the spec.
12751   if (Opcode == AArch64ISD::SSTNT1 && Offset.getValueType().isVector())
12752       std::swap(Base, Offset);
12753 
12754   // SST1_IMM requires that the offset is an immediate that is:
12755   //    * a multiple of #SizeInBytes,
12756   //    * in the range [0, 31 x #SizeInBytes],
12757   // where #SizeInBytes is the size in bytes of the stored items. For
12758   // immediates outside that range and non-immediate scalar offsets use SST1 or
12759   // SST1_UXTW instead.
12760   if (Opcode == AArch64ISD::SST1_IMM) {
12761     if (!isValidImmForSVEVecImmAddrMode(Offset,
12762                                         SrcVT.getScalarSizeInBits() / 8)) {
12763       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12764         Opcode = AArch64ISD::SST1_UXTW;
12765       else
12766         Opcode = AArch64ISD::SST1;
12767 
12768       std::swap(Base, Offset);
12769     }
12770   }
12771 
12772   auto &TLI = DAG.getTargetLoweringInfo();
12773   if (!TLI.isTypeLegal(Base.getValueType()))
12774     return SDValue();
12775 
12776   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12777   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12778   // nxv2i64. Legalize accordingly.
12779   if (!OnlyPackedOffsets &&
12780       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12781     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12782 
12783   if (!TLI.isTypeLegal(Offset.getValueType()))
12784     return SDValue();
12785 
12786   // Source value type that is representable in hardware
12787   EVT HwSrcVt = getSVEContainerType(SrcVT);
12788 
12789   // Keep the original type of the input data to store - this is needed to be
12790   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
12791   // FP values we want the integer equivalent, so just use HwSrcVt.
12792   SDValue InputVT = DAG.getValueType(SrcVT);
12793   if (SrcVT.isFloatingPoint())
12794     InputVT = DAG.getValueType(HwSrcVt);
12795 
12796   SDVTList VTs = DAG.getVTList(MVT::Other);
12797   SDValue SrcNew;
12798 
12799   if (Src.getValueType().isFloatingPoint())
12800     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12801   else
12802     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12803 
12804   SDValue Ops[] = {N->getOperand(0), // Chain
12805                    SrcNew,
12806                    N->getOperand(3), // Pg
12807                    Base,
12808                    Offset,
12809                    InputVT};
12810 
12811   return DAG.getNode(Opcode, DL, VTs, Ops);
12812 }
12813 
12814 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
12815                                         unsigned Opcode,
12816                                         bool OnlyPackedOffsets = true) {
12817   const EVT RetVT = N->getValueType(0);
12818   assert(RetVT.isScalableVector() &&
12819          "Gather loads are only possible for SVE vectors");
12820 
12821   SDLoc DL(N);
12822 
12823   // Make sure that the loaded data will fit into an SVE register
12824   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12825     return SDValue();
12826 
12827   // Depending on the addressing mode, this is either a pointer or a vector of
12828   // pointers (that fits into one register)
12829   SDValue Base = N->getOperand(3);
12830   // Depending on the addressing mode, this is either a single offset or a
12831   // vector of offsets  (that fits into one register)
12832   SDValue Offset = N->getOperand(4);
12833 
12834   // For "scalar + vector of indices", just scale the indices. This only
12835   // applies to non-temporal gathers because there's no instruction that takes
12836   // indicies.
12837   if (Opcode == AArch64ISD::GLDNT1_INDEX) {
12838     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
12839                                         RetVT.getScalarSizeInBits());
12840     Opcode = AArch64ISD::GLDNT1;
12841   }
12842 
12843   // In the case of non-temporal gather loads there's only one SVE instruction
12844   // per data-size: "scalar + vector", i.e.
12845   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
12846   // Since we do have intrinsics that allow the arguments to be in a different
12847   // order, we may need to swap them to match the spec.
12848   if (Opcode == AArch64ISD::GLDNT1 && Offset.getValueType().isVector())
12849       std::swap(Base, Offset);
12850 
12851   // GLD{FF}1_IMM requires that the offset is an immediate that is:
12852   //    * a multiple of #SizeInBytes,
12853   //    * in the range [0, 31 x #SizeInBytes],
12854   // where #SizeInBytes is the size in bytes of the loaded items. For
12855   // immediates outside that range and non-immediate scalar offsets use GLD1 or
12856   // GLD1_UXTW instead.
12857   if (Opcode == AArch64ISD::GLD1_IMM || Opcode == AArch64ISD::GLDFF1_IMM) {
12858     if (!isValidImmForSVEVecImmAddrMode(Offset,
12859                                         RetVT.getScalarSizeInBits() / 8)) {
12860       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12861         Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1_UXTW
12862                                                   : AArch64ISD::GLDFF1_UXTW;
12863       else
12864         Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1
12865                                                   : AArch64ISD::GLDFF1;
12866 
12867       std::swap(Base, Offset);
12868     }
12869   }
12870 
12871   auto &TLI = DAG.getTargetLoweringInfo();
12872   if (!TLI.isTypeLegal(Base.getValueType()))
12873     return SDValue();
12874 
12875   // Some gather load variants allow unpacked offsets, but only as nxv2i32
12876   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12877   // nxv2i64. Legalize accordingly.
12878   if (!OnlyPackedOffsets &&
12879       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12880     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12881 
12882   // Return value type that is representable in hardware
12883   EVT HwRetVt = getSVEContainerType(RetVT);
12884 
12885   // Keep the original output value type around - this is needed to be able to
12886   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
12887   // values we want the integer equivalent, so just use HwRetVT.
12888   SDValue OutVT = DAG.getValueType(RetVT);
12889   if (RetVT.isFloatingPoint())
12890     OutVT = DAG.getValueType(HwRetVt);
12891 
12892   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12893   SDValue Ops[] = {N->getOperand(0), // Chain
12894                    N->getOperand(2), // Pg
12895                    Base, Offset, OutVT};
12896 
12897   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12898   SDValue LoadChain = SDValue(Load.getNode(), 1);
12899 
12900   if (RetVT.isInteger() && (RetVT != HwRetVt))
12901     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12902 
12903   // If the original return value was FP, bitcast accordingly. Doing it here
12904   // means that we can avoid adding TableGen patterns for FPs.
12905   if (RetVT.isFloatingPoint())
12906     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12907 
12908   return DAG.getMergeValues({Load, LoadChain}, DL);
12909 }
12910 
12911 static SDValue
12912 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12913                               SelectionDAG &DAG) {
12914   if (DCI.isBeforeLegalizeOps())
12915     return SDValue();
12916 
12917   SDValue Src = N->getOperand(0);
12918   unsigned Opc = Src->getOpcode();
12919 
12920   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12921   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12922   unsigned NewOpc;
12923   unsigned MemVTOpNum = 4;
12924   switch (Opc) {
12925   case AArch64ISD::LDNF1:
12926     NewOpc = AArch64ISD::LDNF1S;
12927     MemVTOpNum = 3;
12928     break;
12929   case AArch64ISD::LDFF1:
12930     NewOpc = AArch64ISD::LDFF1S;
12931     MemVTOpNum = 3;
12932     break;
12933   case AArch64ISD::GLD1:
12934     NewOpc = AArch64ISD::GLD1S;
12935     break;
12936   case AArch64ISD::GLD1_SCALED:
12937     NewOpc = AArch64ISD::GLD1S_SCALED;
12938     break;
12939   case AArch64ISD::GLD1_SXTW:
12940     NewOpc = AArch64ISD::GLD1S_SXTW;
12941     break;
12942   case AArch64ISD::GLD1_SXTW_SCALED:
12943     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12944     break;
12945   case AArch64ISD::GLD1_UXTW:
12946     NewOpc = AArch64ISD::GLD1S_UXTW;
12947     break;
12948   case AArch64ISD::GLD1_UXTW_SCALED:
12949     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12950     break;
12951   case AArch64ISD::GLD1_IMM:
12952     NewOpc = AArch64ISD::GLD1S_IMM;
12953     break;
12954   case AArch64ISD::GLDFF1:
12955     NewOpc = AArch64ISD::GLDFF1S;
12956     break;
12957   case AArch64ISD::GLDFF1_SCALED:
12958     NewOpc = AArch64ISD::GLDFF1S_SCALED;
12959     break;
12960   case AArch64ISD::GLDFF1_SXTW:
12961     NewOpc = AArch64ISD::GLDFF1S_SXTW;
12962     break;
12963   case AArch64ISD::GLDFF1_SXTW_SCALED:
12964     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED;
12965     break;
12966   case AArch64ISD::GLDFF1_UXTW:
12967     NewOpc = AArch64ISD::GLDFF1S_UXTW;
12968     break;
12969   case AArch64ISD::GLDFF1_UXTW_SCALED:
12970     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED;
12971     break;
12972   case AArch64ISD::GLDFF1_IMM:
12973     NewOpc = AArch64ISD::GLDFF1S_IMM;
12974     break;
12975   case AArch64ISD::GLDNT1:
12976     NewOpc = AArch64ISD::GLDNT1S;
12977     break;
12978   default:
12979     return SDValue();
12980   }
12981 
12982   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12983   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
12984 
12985   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
12986     return SDValue();
12987 
12988   EVT DstVT = N->getValueType(0);
12989   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12990 
12991   SmallVector<SDValue, 5> Ops;
12992   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
12993     Ops.push_back(Src->getOperand(I));
12994 
12995   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12996   DCI.CombineTo(N, ExtLoad);
12997   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12998 
12999   // Return N so it doesn't get rechecked
13000   return SDValue(N, 0);
13001 }
13002 
13003 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
13004 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
13005 /// != nxv2i32) do not need legalization.
13006 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
13007   const unsigned OffsetPos = 4;
13008   SDValue Offset = N->getOperand(OffsetPos);
13009 
13010   // Not an unpacked vector, bail out.
13011   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
13012     return SDValue();
13013 
13014   // Extend the unpacked offset vector to 64-bit lanes.
13015   SDLoc DL(N);
13016   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
13017   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13018   // Replace the offset operand with the 64-bit one.
13019   Ops[OffsetPos] = Offset;
13020 
13021   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13022 }
13023 
13024 /// Combines a node carrying the intrinsic `aarch64_sve_prf_gather<T>` into a
13025 /// node that uses `aarch64_sve_prf_gather<T>_scaled_uxtw` when the scalar
13026 /// offset passed to `aarch64_sve_prf_gather<T>` is not a valid immediate for
13027 /// the sve gather prefetch instruction with vector plus immediate addressing
13028 /// mode.
13029 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
13030                                                unsigned NewIID,
13031                                                unsigned ScalarSizeInBytes) {
13032   const unsigned ImmPos = 4, OffsetPos = 3;
13033   // No need to combine the node if the immediate is valid...
13034   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
13035     return SDValue();
13036 
13037   // ...otherwise swap the offset base with the offset...
13038   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13039   std::swap(Ops[ImmPos], Ops[OffsetPos]);
13040   // ...and remap the intrinsic `aarch64_sve_prf_gather<T>` to
13041   // `aarch64_sve_prf_gather<T>_scaled_uxtw`.
13042   SDLoc DL(N);
13043   Ops[1] = DAG.getConstant(NewIID, DL, MVT::i64);
13044 
13045   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13046 }
13047 
13048 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
13049                                                  DAGCombinerInfo &DCI) const {
13050   SelectionDAG &DAG = DCI.DAG;
13051   switch (N->getOpcode()) {
13052   default:
13053     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
13054     break;
13055   case ISD::ADD:
13056   case ISD::SUB:
13057     return performAddSubLongCombine(N, DCI, DAG);
13058   case ISD::XOR:
13059     return performXorCombine(N, DAG, DCI, Subtarget);
13060   case ISD::MUL:
13061     return performMulCombine(N, DAG, DCI, Subtarget);
13062   case ISD::SINT_TO_FP:
13063   case ISD::UINT_TO_FP:
13064     return performIntToFpCombine(N, DAG, Subtarget);
13065   case ISD::FP_TO_SINT:
13066   case ISD::FP_TO_UINT:
13067     return performFpToIntCombine(N, DAG, DCI, Subtarget);
13068   case ISD::FDIV:
13069     return performFDivCombine(N, DAG, DCI, Subtarget);
13070   case ISD::OR:
13071     return performORCombine(N, DCI, Subtarget);
13072   case ISD::AND:
13073     return performANDCombine(N, DCI);
13074   case ISD::SRL:
13075     return performSRLCombine(N, DCI);
13076   case ISD::INTRINSIC_WO_CHAIN:
13077     return performIntrinsicCombine(N, DCI, Subtarget);
13078   case ISD::ANY_EXTEND:
13079   case ISD::ZERO_EXTEND:
13080   case ISD::SIGN_EXTEND:
13081     return performExtendCombine(N, DCI, DAG);
13082   case ISD::SIGN_EXTEND_INREG:
13083     return performSignExtendInRegCombine(N, DCI, DAG);
13084   case ISD::CONCAT_VECTORS:
13085     return performConcatVectorsCombine(N, DCI, DAG);
13086   case ISD::SELECT:
13087     return performSelectCombine(N, DCI);
13088   case ISD::VSELECT:
13089     return performVSelectCombine(N, DCI.DAG);
13090   case ISD::LOAD:
13091     if (performTBISimplification(N->getOperand(1), DCI, DAG))
13092       return SDValue(N, 0);
13093     break;
13094   case ISD::STORE:
13095     return performSTORECombine(N, DCI, DAG, Subtarget);
13096   case AArch64ISD::BRCOND:
13097     return performBRCONDCombine(N, DCI, DAG);
13098   case AArch64ISD::TBNZ:
13099   case AArch64ISD::TBZ:
13100     return performTBZCombine(N, DCI, DAG);
13101   case AArch64ISD::CSEL:
13102     return performCONDCombine(N, DCI, DAG, 2, 3);
13103   case AArch64ISD::DUP:
13104     return performPostLD1Combine(N, DCI, false);
13105   case AArch64ISD::NVCAST:
13106     return performNVCASTCombine(N);
13107   case ISD::INSERT_VECTOR_ELT:
13108     return performPostLD1Combine(N, DCI, true);
13109   case ISD::INTRINSIC_VOID:
13110   case ISD::INTRINSIC_W_CHAIN:
13111     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13112     case Intrinsic::aarch64_sve_prfb_gather:
13113       return combineSVEPrefetchVecBaseImmOff(
13114           N, DAG, Intrinsic::aarch64_sve_prfb_gather_scaled_uxtw,
13115           1 /*=ScalarSizeInBytes*/);
13116     case Intrinsic::aarch64_sve_prfh_gather:
13117       return combineSVEPrefetchVecBaseImmOff(
13118           N, DAG, Intrinsic::aarch64_sve_prfh_gather_scaled_uxtw,
13119           2 /*=ScalarSizeInBytes*/);
13120     case Intrinsic::aarch64_sve_prfw_gather:
13121       return combineSVEPrefetchVecBaseImmOff(
13122           N, DAG, Intrinsic::aarch64_sve_prfw_gather_scaled_uxtw,
13123           4 /*=ScalarSizeInBytes*/);
13124     case Intrinsic::aarch64_sve_prfd_gather:
13125       return combineSVEPrefetchVecBaseImmOff(
13126           N, DAG, Intrinsic::aarch64_sve_prfd_gather_scaled_uxtw,
13127           8 /*=ScalarSizeInBytes*/);
13128     case Intrinsic::aarch64_sve_prfb_gather_scaled_uxtw:
13129     case Intrinsic::aarch64_sve_prfb_gather_scaled_sxtw:
13130     case Intrinsic::aarch64_sve_prfh_gather_scaled_uxtw:
13131     case Intrinsic::aarch64_sve_prfh_gather_scaled_sxtw:
13132     case Intrinsic::aarch64_sve_prfw_gather_scaled_uxtw:
13133     case Intrinsic::aarch64_sve_prfw_gather_scaled_sxtw:
13134     case Intrinsic::aarch64_sve_prfd_gather_scaled_uxtw:
13135     case Intrinsic::aarch64_sve_prfd_gather_scaled_sxtw:
13136       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
13137     case Intrinsic::aarch64_neon_ld2:
13138     case Intrinsic::aarch64_neon_ld3:
13139     case Intrinsic::aarch64_neon_ld4:
13140     case Intrinsic::aarch64_neon_ld1x2:
13141     case Intrinsic::aarch64_neon_ld1x3:
13142     case Intrinsic::aarch64_neon_ld1x4:
13143     case Intrinsic::aarch64_neon_ld2lane:
13144     case Intrinsic::aarch64_neon_ld3lane:
13145     case Intrinsic::aarch64_neon_ld4lane:
13146     case Intrinsic::aarch64_neon_ld2r:
13147     case Intrinsic::aarch64_neon_ld3r:
13148     case Intrinsic::aarch64_neon_ld4r:
13149     case Intrinsic::aarch64_neon_st2:
13150     case Intrinsic::aarch64_neon_st3:
13151     case Intrinsic::aarch64_neon_st4:
13152     case Intrinsic::aarch64_neon_st1x2:
13153     case Intrinsic::aarch64_neon_st1x3:
13154     case Intrinsic::aarch64_neon_st1x4:
13155     case Intrinsic::aarch64_neon_st2lane:
13156     case Intrinsic::aarch64_neon_st3lane:
13157     case Intrinsic::aarch64_neon_st4lane:
13158       return performNEONPostLDSTCombine(N, DCI, DAG);
13159     case Intrinsic::aarch64_sve_ld1:
13160     case Intrinsic::aarch64_sve_ldnt1:
13161       return performLD1Combine(N, DAG);
13162     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
13163       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13164     case Intrinsic::aarch64_sve_ldnt1_gather:
13165       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13166     case Intrinsic::aarch64_sve_ldnt1_gather_index:
13167       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_INDEX);
13168     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
13169       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13170     case Intrinsic::aarch64_sve_ldnf1:
13171       return performLDNF1Combine(N, DAG, AArch64ISD::LDNF1);
13172     case Intrinsic::aarch64_sve_ldff1:
13173       return performLDNF1Combine(N, DAG, AArch64ISD::LDFF1);
13174     case Intrinsic::aarch64_sve_st1:
13175     case Intrinsic::aarch64_sve_stnt1:
13176       return performST1Combine(N, DAG);
13177     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
13178       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13179     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
13180       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13181     case Intrinsic::aarch64_sve_stnt1_scatter:
13182       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13183     case Intrinsic::aarch64_sve_stnt1_scatter_index:
13184       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX);
13185     case Intrinsic::aarch64_sve_ld1_gather:
13186       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1);
13187     case Intrinsic::aarch64_sve_ld1_gather_index:
13188       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SCALED);
13189     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
13190       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW,
13191                                       /*OnlyPackedOffsets=*/false);
13192     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
13193       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW,
13194                                       /*OnlyPackedOffsets=*/false);
13195     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
13196       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
13197                                       /*OnlyPackedOffsets=*/false);
13198     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
13199       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
13200                                       /*OnlyPackedOffsets=*/false);
13201     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
13202       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM);
13203     case Intrinsic::aarch64_sve_ldff1_gather:
13204       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1);
13205     case Intrinsic::aarch64_sve_ldff1_gather_index:
13206       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SCALED);
13207     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
13208       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW,
13209                                       /*OnlyPackedOffsets=*/false);
13210     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
13211       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW,
13212                                       /*OnlyPackedOffsets=*/false);
13213     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
13214       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW_SCALED,
13215                                       /*OnlyPackedOffsets=*/false);
13216     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
13217       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW_SCALED,
13218                                       /*OnlyPackedOffsets=*/false);
13219     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
13220       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_IMM);
13221     case Intrinsic::aarch64_sve_st1_scatter:
13222       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1);
13223     case Intrinsic::aarch64_sve_st1_scatter_index:
13224       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED);
13225     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
13226       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW,
13227                                         /*OnlyPackedOffsets=*/false);
13228     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
13229       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW,
13230                                         /*OnlyPackedOffsets=*/false);
13231     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
13232       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
13233                                         /*OnlyPackedOffsets=*/false);
13234     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
13235       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
13236                                         /*OnlyPackedOffsets=*/false);
13237     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
13238       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM);
13239     default:
13240       break;
13241     }
13242     break;
13243   case ISD::GlobalAddress:
13244     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
13245   }
13246   return SDValue();
13247 }
13248 
13249 // Check if the return value is used as only a return value, as otherwise
13250 // we can't perform a tail-call. In particular, we need to check for
13251 // target ISD nodes that are returns and any other "odd" constructs
13252 // that the generic analysis code won't necessarily catch.
13253 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
13254                                                SDValue &Chain) const {
13255   if (N->getNumValues() != 1)
13256     return false;
13257   if (!N->hasNUsesOfValue(1, 0))
13258     return false;
13259 
13260   SDValue TCChain = Chain;
13261   SDNode *Copy = *N->use_begin();
13262   if (Copy->getOpcode() == ISD::CopyToReg) {
13263     // If the copy has a glue operand, we conservatively assume it isn't safe to
13264     // perform a tail call.
13265     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
13266         MVT::Glue)
13267       return false;
13268     TCChain = Copy->getOperand(0);
13269   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
13270     return false;
13271 
13272   bool HasRet = false;
13273   for (SDNode *Node : Copy->uses()) {
13274     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
13275       return false;
13276     HasRet = true;
13277   }
13278 
13279   if (!HasRet)
13280     return false;
13281 
13282   Chain = TCChain;
13283   return true;
13284 }
13285 
13286 // Return whether the an instruction can potentially be optimized to a tail
13287 // call. This will cause the optimizers to attempt to move, or duplicate,
13288 // return instructions to help enable tail call optimizations for this
13289 // instruction.
13290 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
13291   return CI->isTailCall();
13292 }
13293 
13294 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
13295                                                    SDValue &Offset,
13296                                                    ISD::MemIndexedMode &AM,
13297                                                    bool &IsInc,
13298                                                    SelectionDAG &DAG) const {
13299   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
13300     return false;
13301 
13302   Base = Op->getOperand(0);
13303   // All of the indexed addressing mode instructions take a signed
13304   // 9 bit immediate offset.
13305   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
13306     int64_t RHSC = RHS->getSExtValue();
13307     if (Op->getOpcode() == ISD::SUB)
13308       RHSC = -(uint64_t)RHSC;
13309     if (!isInt<9>(RHSC))
13310       return false;
13311     IsInc = (Op->getOpcode() == ISD::ADD);
13312     Offset = Op->getOperand(1);
13313     return true;
13314   }
13315   return false;
13316 }
13317 
13318 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13319                                                       SDValue &Offset,
13320                                                       ISD::MemIndexedMode &AM,
13321                                                       SelectionDAG &DAG) const {
13322   EVT VT;
13323   SDValue Ptr;
13324   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13325     VT = LD->getMemoryVT();
13326     Ptr = LD->getBasePtr();
13327   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13328     VT = ST->getMemoryVT();
13329     Ptr = ST->getBasePtr();
13330   } else
13331     return false;
13332 
13333   bool IsInc;
13334   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
13335     return false;
13336   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
13337   return true;
13338 }
13339 
13340 bool AArch64TargetLowering::getPostIndexedAddressParts(
13341     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
13342     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
13343   EVT VT;
13344   SDValue Ptr;
13345   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13346     VT = LD->getMemoryVT();
13347     Ptr = LD->getBasePtr();
13348   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13349     VT = ST->getMemoryVT();
13350     Ptr = ST->getBasePtr();
13351   } else
13352     return false;
13353 
13354   bool IsInc;
13355   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
13356     return false;
13357   // Post-indexing updates the base, so it's not a valid transform
13358   // if that's not the same as the load's pointer.
13359   if (Ptr != Base)
13360     return false;
13361   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
13362   return true;
13363 }
13364 
13365 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
13366                                   SelectionDAG &DAG) {
13367   SDLoc DL(N);
13368   SDValue Op = N->getOperand(0);
13369 
13370   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
13371     return;
13372 
13373   Op = SDValue(
13374       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
13375                          DAG.getUNDEF(MVT::i32), Op,
13376                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
13377       0);
13378   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
13379   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
13380 }
13381 
13382 static void ReplaceReductionResults(SDNode *N,
13383                                     SmallVectorImpl<SDValue> &Results,
13384                                     SelectionDAG &DAG, unsigned InterOp,
13385                                     unsigned AcrossOp) {
13386   EVT LoVT, HiVT;
13387   SDValue Lo, Hi;
13388   SDLoc dl(N);
13389   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
13390   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
13391   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
13392   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
13393   Results.push_back(SplitVal);
13394 }
13395 
13396 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
13397   SDLoc DL(N);
13398   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
13399   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
13400                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
13401                                        DAG.getConstant(64, DL, MVT::i64)));
13402   return std::make_pair(Lo, Hi);
13403 }
13404 
13405 // Create an even/odd pair of X registers holding integer value V.
13406 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
13407   SDLoc dl(V.getNode());
13408   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
13409   SDValue VHi = DAG.getAnyExtOrTrunc(
13410       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
13411       dl, MVT::i64);
13412   if (DAG.getDataLayout().isBigEndian())
13413     std::swap (VLo, VHi);
13414   SDValue RegClass =
13415       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
13416   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
13417   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
13418   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
13419   return SDValue(
13420       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
13421 }
13422 
13423 static void ReplaceCMP_SWAP_128Results(SDNode *N,
13424                                        SmallVectorImpl<SDValue> &Results,
13425                                        SelectionDAG &DAG,
13426                                        const AArch64Subtarget *Subtarget) {
13427   assert(N->getValueType(0) == MVT::i128 &&
13428          "AtomicCmpSwap on types less than 128 should be legal");
13429 
13430   if (Subtarget->hasLSE()) {
13431     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
13432     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
13433     SDValue Ops[] = {
13434         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
13435         createGPRPairNode(DAG, N->getOperand(3)), // Store value
13436         N->getOperand(1), // Ptr
13437         N->getOperand(0), // Chain in
13438     };
13439 
13440     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13441 
13442     unsigned Opcode;
13443     switch (MemOp->getOrdering()) {
13444     case AtomicOrdering::Monotonic:
13445       Opcode = AArch64::CASPX;
13446       break;
13447     case AtomicOrdering::Acquire:
13448       Opcode = AArch64::CASPAX;
13449       break;
13450     case AtomicOrdering::Release:
13451       Opcode = AArch64::CASPLX;
13452       break;
13453     case AtomicOrdering::AcquireRelease:
13454     case AtomicOrdering::SequentiallyConsistent:
13455       Opcode = AArch64::CASPALX;
13456       break;
13457     default:
13458       llvm_unreachable("Unexpected ordering!");
13459     }
13460 
13461     MachineSDNode *CmpSwap = DAG.getMachineNode(
13462         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
13463     DAG.setNodeMemRefs(CmpSwap, {MemOp});
13464 
13465     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
13466     if (DAG.getDataLayout().isBigEndian())
13467       std::swap(SubReg1, SubReg2);
13468     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
13469                                             SDValue(CmpSwap, 0));
13470     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
13471                                             SDValue(CmpSwap, 0));
13472     Results.push_back(
13473         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
13474     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
13475     return;
13476   }
13477 
13478   auto Desired = splitInt128(N->getOperand(2), DAG);
13479   auto New = splitInt128(N->getOperand(3), DAG);
13480   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
13481                    New.first,        New.second,    N->getOperand(0)};
13482   SDNode *CmpSwap = DAG.getMachineNode(
13483       AArch64::CMP_SWAP_128, SDLoc(N),
13484       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
13485 
13486   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13487   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
13488 
13489   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13490                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
13491   Results.push_back(SDValue(CmpSwap, 3));
13492 }
13493 
13494 void AArch64TargetLowering::ReplaceNodeResults(
13495     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
13496   switch (N->getOpcode()) {
13497   default:
13498     llvm_unreachable("Don't know how to custom expand this");
13499   case ISD::BITCAST:
13500     ReplaceBITCASTResults(N, Results, DAG);
13501     return;
13502   case ISD::VECREDUCE_ADD:
13503   case ISD::VECREDUCE_SMAX:
13504   case ISD::VECREDUCE_SMIN:
13505   case ISD::VECREDUCE_UMAX:
13506   case ISD::VECREDUCE_UMIN:
13507     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
13508     return;
13509 
13510   case AArch64ISD::SADDV:
13511     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
13512     return;
13513   case AArch64ISD::UADDV:
13514     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
13515     return;
13516   case AArch64ISD::SMINV:
13517     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
13518     return;
13519   case AArch64ISD::UMINV:
13520     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
13521     return;
13522   case AArch64ISD::SMAXV:
13523     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
13524     return;
13525   case AArch64ISD::UMAXV:
13526     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
13527     return;
13528   case ISD::FP_TO_UINT:
13529   case ISD::FP_TO_SINT:
13530     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
13531     // Let normal code take care of it by not adding anything to Results.
13532     return;
13533   case ISD::ATOMIC_CMP_SWAP:
13534     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
13535     return;
13536   case ISD::LOAD: {
13537     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
13538            "unexpected load's value type");
13539     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
13540     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
13541       // Non-volatile loads are optimized later in AArch64's load/store
13542       // optimizer.
13543       return;
13544     }
13545 
13546     SDValue Result = DAG.getMemIntrinsicNode(
13547         AArch64ISD::LDP, SDLoc(N),
13548         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
13549         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
13550         LoadNode->getMemOperand());
13551 
13552     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13553                                Result.getValue(0), Result.getValue(1));
13554     Results.append({Pair, Result.getValue(2) /* Chain */});
13555     return;
13556   }
13557   case ISD::INTRINSIC_WO_CHAIN: {
13558     EVT VT = N->getValueType(0);
13559     assert((VT == MVT::i8 || VT == MVT::i16) &&
13560            "custom lowering for unexpected type");
13561 
13562     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
13563     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13564     switch (IntID) {
13565     default:
13566       return;
13567     case Intrinsic::aarch64_sve_clasta_n: {
13568       SDLoc DL(N);
13569       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13570       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
13571                            N->getOperand(1), Op2, N->getOperand(3));
13572       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13573       return;
13574     }
13575     case Intrinsic::aarch64_sve_clastb_n: {
13576       SDLoc DL(N);
13577       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13578       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
13579                            N->getOperand(1), Op2, N->getOperand(3));
13580       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13581       return;
13582     }
13583     case Intrinsic::aarch64_sve_lasta: {
13584       SDLoc DL(N);
13585       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
13586                            N->getOperand(1), N->getOperand(2));
13587       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13588       return;
13589     }
13590     case Intrinsic::aarch64_sve_lastb: {
13591       SDLoc DL(N);
13592       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
13593                            N->getOperand(1), N->getOperand(2));
13594       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13595       return;
13596     }
13597     }
13598   }
13599   }
13600 }
13601 
13602 bool AArch64TargetLowering::useLoadStackGuardNode() const {
13603   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
13604     return TargetLowering::useLoadStackGuardNode();
13605   return true;
13606 }
13607 
13608 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
13609   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13610   // reciprocal if there are three or more FDIVs.
13611   return 3;
13612 }
13613 
13614 TargetLoweringBase::LegalizeTypeAction
13615 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
13616   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
13617   // v4i16, v2i32 instead of to promote.
13618   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
13619       VT == MVT::v1f32)
13620     return TypeWidenVector;
13621 
13622   return TargetLoweringBase::getPreferredVectorAction(VT);
13623 }
13624 
13625 // Loads and stores less than 128-bits are already atomic; ones above that
13626 // are doomed anyway, so defer to the default libcall and blame the OS when
13627 // things go wrong.
13628 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13629   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13630   return Size == 128;
13631 }
13632 
13633 // Loads and stores less than 128-bits are already atomic; ones above that
13634 // are doomed anyway, so defer to the default libcall and blame the OS when
13635 // things go wrong.
13636 TargetLowering::AtomicExpansionKind
13637 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13638   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13639   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
13640 }
13641 
13642 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
13643 TargetLowering::AtomicExpansionKind
13644 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13645   if (AI->isFloatingPointOperation())
13646     return AtomicExpansionKind::CmpXChg;
13647 
13648   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13649   if (Size > 128) return AtomicExpansionKind::None;
13650   // Nand not supported in LSE.
13651   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13652   // Leave 128 bits to LLSC.
13653   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13654 }
13655 
13656 TargetLowering::AtomicExpansionKind
13657 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13658     AtomicCmpXchgInst *AI) const {
13659   // If subtarget has LSE, leave cmpxchg intact for codegen.
13660   if (Subtarget->hasLSE())
13661     return AtomicExpansionKind::None;
13662   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13663   // implement cmpxchg without spilling. If the address being exchanged is also
13664   // on the stack and close enough to the spill slot, this can lead to a
13665   // situation where the monitor always gets cleared and the atomic operation
13666   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13667   if (getTargetMachine().getOptLevel() == 0)
13668     return AtomicExpansionKind::None;
13669   return AtomicExpansionKind::LLSC;
13670 }
13671 
13672 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13673                                              AtomicOrdering Ord) const {
13674   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13675   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13676   bool IsAcquire = isAcquireOrStronger(Ord);
13677 
13678   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13679   // intrinsic must return {i64, i64} and we have to recombine them into a
13680   // single i128 here.
13681   if (ValTy->getPrimitiveSizeInBits() == 128) {
13682     Intrinsic::ID Int =
13683         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13684     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13685 
13686     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13687     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13688 
13689     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13690     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13691     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13692     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13693     return Builder.CreateOr(
13694         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13695   }
13696 
13697   Type *Tys[] = { Addr->getType() };
13698   Intrinsic::ID Int =
13699       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13700   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13701 
13702   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13703 
13704   const DataLayout &DL = M->getDataLayout();
13705   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13706   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13707 
13708   return Builder.CreateBitCast(Trunc, EltTy);
13709 }
13710 
13711 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13712     IRBuilder<> &Builder) const {
13713   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13714   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13715 }
13716 
13717 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13718                                                    Value *Val, Value *Addr,
13719                                                    AtomicOrdering Ord) const {
13720   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13721   bool IsRelease = isReleaseOrStronger(Ord);
13722 
13723   // Since the intrinsics must have legal type, the i128 intrinsics take two
13724   // parameters: "i64, i64". We must marshal Val into the appropriate form
13725   // before the call.
13726   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13727     Intrinsic::ID Int =
13728         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13729     Function *Stxr = Intrinsic::getDeclaration(M, Int);
13730     Type *Int64Ty = Type::getInt64Ty(M->getContext());
13731 
13732     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13733     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13734     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13735     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13736   }
13737 
13738   Intrinsic::ID Int =
13739       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13740   Type *Tys[] = { Addr->getType() };
13741   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13742 
13743   const DataLayout &DL = M->getDataLayout();
13744   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13745   Val = Builder.CreateBitCast(Val, IntValTy);
13746 
13747   return Builder.CreateCall(Stxr,
13748                             {Builder.CreateZExtOrBitCast(
13749                                  Val, Stxr->getFunctionType()->getParamType(0)),
13750                              Addr});
13751 }
13752 
13753 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13754     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13755   return Ty->isArrayTy();
13756 }
13757 
13758 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13759                                                             EVT) const {
13760   return false;
13761 }
13762 
13763 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13764   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13765   Function *ThreadPointerFunc =
13766       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13767   return IRB.CreatePointerCast(
13768       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13769                              Offset),
13770       IRB.getInt8PtrTy()->getPointerTo(0));
13771 }
13772 
13773 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13774   // Android provides a fixed TLS slot for the stack cookie. See the definition
13775   // of TLS_SLOT_STACK_GUARD in
13776   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13777   if (Subtarget->isTargetAndroid())
13778     return UseTlsOffset(IRB, 0x28);
13779 
13780   // Fuchsia is similar.
13781   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13782   if (Subtarget->isTargetFuchsia())
13783     return UseTlsOffset(IRB, -0x10);
13784 
13785   return TargetLowering::getIRStackGuard(IRB);
13786 }
13787 
13788 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13789   // MSVC CRT provides functionalities for stack protection.
13790   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13791     // MSVC CRT has a global variable holding security cookie.
13792     M.getOrInsertGlobal("__security_cookie",
13793                         Type::getInt8PtrTy(M.getContext()));
13794 
13795     // MSVC CRT has a function to validate security cookie.
13796     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13797         "__security_check_cookie", Type::getVoidTy(M.getContext()),
13798         Type::getInt8PtrTy(M.getContext()));
13799     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13800       F->setCallingConv(CallingConv::Win64);
13801       F->addAttribute(1, Attribute::AttrKind::InReg);
13802     }
13803     return;
13804   }
13805   TargetLowering::insertSSPDeclarations(M);
13806 }
13807 
13808 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13809   // MSVC CRT has a global variable holding security cookie.
13810   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13811     return M.getGlobalVariable("__security_cookie");
13812   return TargetLowering::getSDagStackGuard(M);
13813 }
13814 
13815 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13816   // MSVC CRT has a function to validate security cookie.
13817   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13818     return M.getFunction("__security_check_cookie");
13819   return TargetLowering::getSSPStackGuardCheck(M);
13820 }
13821 
13822 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13823   // Android provides a fixed TLS slot for the SafeStack pointer. See the
13824   // definition of TLS_SLOT_SAFESTACK in
13825   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13826   if (Subtarget->isTargetAndroid())
13827     return UseTlsOffset(IRB, 0x48);
13828 
13829   // Fuchsia is similar.
13830   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13831   if (Subtarget->isTargetFuchsia())
13832     return UseTlsOffset(IRB, -0x8);
13833 
13834   return TargetLowering::getSafeStackPointerLocation(IRB);
13835 }
13836 
13837 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13838     const Instruction &AndI) const {
13839   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13840   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
13841   // may be beneficial to sink in other cases, but we would have to check that
13842   // the cmp would not get folded into the br to form a cbz for these to be
13843   // beneficial.
13844   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13845   if (!Mask)
13846     return false;
13847   return Mask->getValue().isPowerOf2();
13848 }
13849 
13850 bool AArch64TargetLowering::
13851     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13852         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13853         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13854         SelectionDAG &DAG) const {
13855   // Does baseline recommend not to perform the fold by default?
13856   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13857           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13858     return false;
13859   // Else, if this is a vector shift, prefer 'shl'.
13860   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13861 }
13862 
13863 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13864                                               SDNode *N) const {
13865   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13866       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13867     return false;
13868   return true;
13869 }
13870 
13871 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13872   // Update IsSplitCSR in AArch64unctionInfo.
13873   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13874   AFI->setIsSplitCSR(true);
13875 }
13876 
13877 void AArch64TargetLowering::insertCopiesSplitCSR(
13878     MachineBasicBlock *Entry,
13879     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13880   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13881   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13882   if (!IStart)
13883     return;
13884 
13885   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13886   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13887   MachineBasicBlock::iterator MBBI = Entry->begin();
13888   for (const MCPhysReg *I = IStart; *I; ++I) {
13889     const TargetRegisterClass *RC = nullptr;
13890     if (AArch64::GPR64RegClass.contains(*I))
13891       RC = &AArch64::GPR64RegClass;
13892     else if (AArch64::FPR64RegClass.contains(*I))
13893       RC = &AArch64::FPR64RegClass;
13894     else
13895       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13896 
13897     Register NewVR = MRI->createVirtualRegister(RC);
13898     // Create copy from CSR to a virtual register.
13899     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13900     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13901     // nounwind. If we want to generalize this later, we may need to emit
13902     // CFI pseudo-instructions.
13903     assert(Entry->getParent()->getFunction().hasFnAttribute(
13904                Attribute::NoUnwind) &&
13905            "Function should be nounwind in insertCopiesSplitCSR!");
13906     Entry->addLiveIn(*I);
13907     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13908         .addReg(*I);
13909 
13910     // Insert the copy-back instructions right before the terminator.
13911     for (auto *Exit : Exits)
13912       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13913               TII->get(TargetOpcode::COPY), *I)
13914           .addReg(NewVR);
13915   }
13916 }
13917 
13918 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13919   // Integer division on AArch64 is expensive. However, when aggressively
13920   // optimizing for code size, we prefer to use a div instruction, as it is
13921   // usually smaller than the alternative sequence.
13922   // The exception to this is vector division. Since AArch64 doesn't have vector
13923   // integer division, leaving the division as-is is a loss even in terms of
13924   // size, because it will have to be scalarized, while the alternative code
13925   // sequence can be performed in vector form.
13926   bool OptSize =
13927       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13928   return OptSize && !VT.isVector();
13929 }
13930 
13931 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13932   // We want inc-of-add for scalars and sub-of-not for vectors.
13933   return VT.isScalarInteger();
13934 }
13935 
13936 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13937   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13938 }
13939 
13940 unsigned
13941 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13942   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13943     return getPointerTy(DL).getSizeInBits();
13944 
13945   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13946 }
13947 
13948 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13949   MF.getFrameInfo().computeMaxCallFrameSize(MF);
13950   TargetLoweringBase::finalizeLowering(MF);
13951 }
13952 
13953 // Unlike X86, we let frame lowering assign offsets to all catch objects.
13954 bool AArch64TargetLowering::needsFixedCatchObjects() const {
13955   return false;
13956 }
13957 
13958 bool AArch64TargetLowering::shouldLocalize(
13959     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
13960   if (MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE) {
13961     // On Darwin, TLS global vars get selected into function calls, which
13962     // we don't want localized, as they can get moved into the middle of a
13963     // another call sequence.
13964     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
13965     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
13966       return false;
13967   }
13968   return TargetLoweringBase::shouldLocalize(MI, TTI);
13969 }
13970