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/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/ObjCARCUtil.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 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 // Temporary option added for the purpose of testing functionality added
117 // to DAGCombiner.cpp in D92230. It is expected that this can be removed
118 // in future when both implementations will be based off MGATHER rather
119 // than the GLD1 nodes added for the SVE gather load intrinsics.
120 static cl::opt<bool>
121 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
122                                 cl::desc("Combine extends of AArch64 masked "
123                                          "gather intrinsics"),
124                                 cl::init(true));
125 
126 /// Value type used for condition codes.
127 static const MVT MVT_CC = MVT::i32;
128 
129 static inline EVT getPackedSVEVectorVT(EVT VT) {
130   switch (VT.getSimpleVT().SimpleTy) {
131   default:
132     llvm_unreachable("unexpected element type for vector");
133   case MVT::i8:
134     return MVT::nxv16i8;
135   case MVT::i16:
136     return MVT::nxv8i16;
137   case MVT::i32:
138     return MVT::nxv4i32;
139   case MVT::i64:
140     return MVT::nxv2i64;
141   case MVT::f16:
142     return MVT::nxv8f16;
143   case MVT::f32:
144     return MVT::nxv4f32;
145   case MVT::f64:
146     return MVT::nxv2f64;
147   case MVT::bf16:
148     return MVT::nxv8bf16;
149   }
150 }
151 
152 // NOTE: Currently there's only a need to return integer vector types. If this
153 // changes then just add an extra "type" parameter.
154 static inline EVT getPackedSVEVectorVT(ElementCount EC) {
155   switch (EC.getKnownMinValue()) {
156   default:
157     llvm_unreachable("unexpected element count for vector");
158   case 16:
159     return MVT::nxv16i8;
160   case 8:
161     return MVT::nxv8i16;
162   case 4:
163     return MVT::nxv4i32;
164   case 2:
165     return MVT::nxv2i64;
166   }
167 }
168 
169 static inline EVT getPromotedVTForPredicate(EVT VT) {
170   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
171          "Expected scalable predicate vector type!");
172   switch (VT.getVectorMinNumElements()) {
173   default:
174     llvm_unreachable("unexpected element count for vector");
175   case 2:
176     return MVT::nxv2i64;
177   case 4:
178     return MVT::nxv4i32;
179   case 8:
180     return MVT::nxv8i16;
181   case 16:
182     return MVT::nxv16i8;
183   }
184 }
185 
186 /// Returns true if VT's elements occupy the lowest bit positions of its
187 /// associated register class without any intervening space.
188 ///
189 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
190 /// same register class, but only nxv8f16 can be treated as a packed vector.
191 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
192   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
193          "Expected legal vector type!");
194   return VT.isFixedLengthVector() ||
195          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
196 }
197 
198 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
199 // predicate and end with a passthru value matching the result type.
200 static bool isMergePassthruOpcode(unsigned Opc) {
201   switch (Opc) {
202   default:
203     return false;
204   case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
205   case AArch64ISD::BSWAP_MERGE_PASSTHRU:
206   case AArch64ISD::CTLZ_MERGE_PASSTHRU:
207   case AArch64ISD::CTPOP_MERGE_PASSTHRU:
208   case AArch64ISD::DUP_MERGE_PASSTHRU:
209   case AArch64ISD::ABS_MERGE_PASSTHRU:
210   case AArch64ISD::NEG_MERGE_PASSTHRU:
211   case AArch64ISD::FNEG_MERGE_PASSTHRU:
212   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
213   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
214   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
215   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
216   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
217   case AArch64ISD::FRINT_MERGE_PASSTHRU:
218   case AArch64ISD::FROUND_MERGE_PASSTHRU:
219   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
220   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
221   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
222   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
223   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
224   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
225   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
226   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
227   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
228   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
229   case AArch64ISD::FABS_MERGE_PASSTHRU:
230     return true;
231   }
232 }
233 
234 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
235                                              const AArch64Subtarget &STI)
236     : TargetLowering(TM), Subtarget(&STI) {
237   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
238   // we have to make something up. Arbitrarily, choose ZeroOrOne.
239   setBooleanContents(ZeroOrOneBooleanContent);
240   // When comparing vectors the result sets the different elements in the
241   // vector to all-one or all-zero.
242   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
243 
244   // Set up the register classes.
245   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
246   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
247 
248   if (Subtarget->hasFPARMv8()) {
249     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
250     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
251     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
252     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
253     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
254   }
255 
256   if (Subtarget->hasNEON()) {
257     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
258     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
259     // Someone set us up the NEON.
260     addDRTypeForNEON(MVT::v2f32);
261     addDRTypeForNEON(MVT::v8i8);
262     addDRTypeForNEON(MVT::v4i16);
263     addDRTypeForNEON(MVT::v2i32);
264     addDRTypeForNEON(MVT::v1i64);
265     addDRTypeForNEON(MVT::v1f64);
266     addDRTypeForNEON(MVT::v4f16);
267     if (Subtarget->hasBF16())
268       addDRTypeForNEON(MVT::v4bf16);
269 
270     addQRTypeForNEON(MVT::v4f32);
271     addQRTypeForNEON(MVT::v2f64);
272     addQRTypeForNEON(MVT::v16i8);
273     addQRTypeForNEON(MVT::v8i16);
274     addQRTypeForNEON(MVT::v4i32);
275     addQRTypeForNEON(MVT::v2i64);
276     addQRTypeForNEON(MVT::v8f16);
277     if (Subtarget->hasBF16())
278       addQRTypeForNEON(MVT::v8bf16);
279   }
280 
281   if (Subtarget->hasSVE()) {
282     // Add legal sve predicate types
283     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
284     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
285     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
286     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
287 
288     // Add legal sve data types
289     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
290     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
291     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
292     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
293 
294     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
295     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
296     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
297     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
298     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
299     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
300 
301     if (Subtarget->hasBF16()) {
302       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
303       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
304       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
305     }
306 
307     if (Subtarget->useSVEForFixedLengthVectors()) {
308       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
309         if (useSVEForFixedLengthVectorVT(VT))
310           addRegisterClass(VT, &AArch64::ZPRRegClass);
311 
312       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
313         if (useSVEForFixedLengthVectorVT(VT))
314           addRegisterClass(VT, &AArch64::ZPRRegClass);
315     }
316 
317     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
318       setOperationAction(ISD::SADDSAT, VT, Legal);
319       setOperationAction(ISD::UADDSAT, VT, Legal);
320       setOperationAction(ISD::SSUBSAT, VT, Legal);
321       setOperationAction(ISD::USUBSAT, VT, Legal);
322       setOperationAction(ISD::UREM, VT, Expand);
323       setOperationAction(ISD::SREM, VT, Expand);
324       setOperationAction(ISD::SDIVREM, VT, Expand);
325       setOperationAction(ISD::UDIVREM, VT, Expand);
326     }
327 
328     for (auto VT :
329          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
330            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
331       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
332 
333     for (auto VT :
334          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
335            MVT::nxv2f64 }) {
336       setCondCodeAction(ISD::SETO, VT, Expand);
337       setCondCodeAction(ISD::SETOLT, VT, Expand);
338       setCondCodeAction(ISD::SETLT, VT, Expand);
339       setCondCodeAction(ISD::SETOLE, VT, Expand);
340       setCondCodeAction(ISD::SETLE, VT, Expand);
341       setCondCodeAction(ISD::SETULT, VT, Expand);
342       setCondCodeAction(ISD::SETULE, VT, Expand);
343       setCondCodeAction(ISD::SETUGE, VT, Expand);
344       setCondCodeAction(ISD::SETUGT, VT, Expand);
345       setCondCodeAction(ISD::SETUEQ, VT, Expand);
346       setCondCodeAction(ISD::SETUNE, VT, Expand);
347     }
348   }
349 
350   // Compute derived properties from the register classes
351   computeRegisterProperties(Subtarget->getRegisterInfo());
352 
353   // Provide all sorts of operation actions
354   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
355   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
356   setOperationAction(ISD::SETCC, MVT::i32, Custom);
357   setOperationAction(ISD::SETCC, MVT::i64, Custom);
358   setOperationAction(ISD::SETCC, MVT::f16, Custom);
359   setOperationAction(ISD::SETCC, MVT::f32, Custom);
360   setOperationAction(ISD::SETCC, MVT::f64, Custom);
361   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
362   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
363   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
364   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
365   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
366   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
367   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
368   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
369   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
370   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
371   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
372   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
373   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
374   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
375   setOperationAction(ISD::SELECT, MVT::i32, Custom);
376   setOperationAction(ISD::SELECT, MVT::i64, Custom);
377   setOperationAction(ISD::SELECT, MVT::f16, Custom);
378   setOperationAction(ISD::SELECT, MVT::f32, Custom);
379   setOperationAction(ISD::SELECT, MVT::f64, Custom);
380   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
381   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
382   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
383   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
384   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
385   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
386   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
387 
388   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
389   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
390   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
391 
392   setOperationAction(ISD::FREM, MVT::f32, Expand);
393   setOperationAction(ISD::FREM, MVT::f64, Expand);
394   setOperationAction(ISD::FREM, MVT::f80, Expand);
395 
396   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
397 
398   // Custom lowering hooks are needed for XOR
399   // to fold it into CSINC/CSINV.
400   setOperationAction(ISD::XOR, MVT::i32, Custom);
401   setOperationAction(ISD::XOR, MVT::i64, Custom);
402 
403   // Virtually no operation on f128 is legal, but LLVM can't expand them when
404   // there's a valid register class, so we need custom operations in most cases.
405   setOperationAction(ISD::FABS, MVT::f128, Expand);
406   setOperationAction(ISD::FADD, MVT::f128, LibCall);
407   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
408   setOperationAction(ISD::FCOS, MVT::f128, Expand);
409   setOperationAction(ISD::FDIV, MVT::f128, LibCall);
410   setOperationAction(ISD::FMA, MVT::f128, Expand);
411   setOperationAction(ISD::FMUL, MVT::f128, LibCall);
412   setOperationAction(ISD::FNEG, MVT::f128, Expand);
413   setOperationAction(ISD::FPOW, MVT::f128, Expand);
414   setOperationAction(ISD::FREM, MVT::f128, Expand);
415   setOperationAction(ISD::FRINT, MVT::f128, Expand);
416   setOperationAction(ISD::FSIN, MVT::f128, Expand);
417   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
418   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
419   setOperationAction(ISD::FSUB, MVT::f128, LibCall);
420   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
421   setOperationAction(ISD::SETCC, MVT::f128, Custom);
422   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
423   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
424   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
425   setOperationAction(ISD::SELECT, MVT::f128, Custom);
426   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
427   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
428 
429   // Lowering for many of the conversions is actually specified by the non-f128
430   // type. The LowerXXX function will be trivial when f128 isn't involved.
431   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
432   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
433   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
434   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
435   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
436   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
437   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
438   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
439   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
440   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
441   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
442   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
443   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
444   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
445   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
446   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
447   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
448   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
449   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
450   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
451   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
452   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
453   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
454   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
455   setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
456   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
457   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
458   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
459   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
460   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
461 
462   // Variable arguments.
463   setOperationAction(ISD::VASTART, MVT::Other, Custom);
464   setOperationAction(ISD::VAARG, MVT::Other, Custom);
465   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
466   setOperationAction(ISD::VAEND, MVT::Other, Expand);
467 
468   // Variable-sized objects.
469   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
470   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
471 
472   if (Subtarget->isTargetWindows())
473     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
474   else
475     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
476 
477   // Constant pool entries
478   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
479 
480   // BlockAddress
481   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
482 
483   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
484   setOperationAction(ISD::ADDC, MVT::i32, Custom);
485   setOperationAction(ISD::ADDE, MVT::i32, Custom);
486   setOperationAction(ISD::SUBC, MVT::i32, Custom);
487   setOperationAction(ISD::SUBE, MVT::i32, Custom);
488   setOperationAction(ISD::ADDC, MVT::i64, Custom);
489   setOperationAction(ISD::ADDE, MVT::i64, Custom);
490   setOperationAction(ISD::SUBC, MVT::i64, Custom);
491   setOperationAction(ISD::SUBE, MVT::i64, Custom);
492 
493   // AArch64 lacks both left-rotate and popcount instructions.
494   setOperationAction(ISD::ROTL, MVT::i32, Expand);
495   setOperationAction(ISD::ROTL, MVT::i64, Expand);
496   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
497     setOperationAction(ISD::ROTL, VT, Expand);
498     setOperationAction(ISD::ROTR, VT, Expand);
499   }
500 
501   // AArch64 doesn't have i32 MULH{S|U}.
502   setOperationAction(ISD::MULHU, MVT::i32, Expand);
503   setOperationAction(ISD::MULHS, MVT::i32, Expand);
504 
505   // AArch64 doesn't have {U|S}MUL_LOHI.
506   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
507   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
508 
509   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
510   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
511   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
512 
513   setOperationAction(ISD::ABS, MVT::i32, Custom);
514   setOperationAction(ISD::ABS, MVT::i64, Custom);
515 
516   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
517   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
518   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
519     setOperationAction(ISD::SDIVREM, VT, Expand);
520     setOperationAction(ISD::UDIVREM, VT, Expand);
521   }
522   setOperationAction(ISD::SREM, MVT::i32, Expand);
523   setOperationAction(ISD::SREM, MVT::i64, Expand);
524   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
525   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
526   setOperationAction(ISD::UREM, MVT::i32, Expand);
527   setOperationAction(ISD::UREM, MVT::i64, Expand);
528 
529   // Custom lower Add/Sub/Mul with overflow.
530   setOperationAction(ISD::SADDO, MVT::i32, Custom);
531   setOperationAction(ISD::SADDO, MVT::i64, Custom);
532   setOperationAction(ISD::UADDO, MVT::i32, Custom);
533   setOperationAction(ISD::UADDO, MVT::i64, Custom);
534   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
535   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
536   setOperationAction(ISD::USUBO, MVT::i32, Custom);
537   setOperationAction(ISD::USUBO, MVT::i64, Custom);
538   setOperationAction(ISD::SMULO, MVT::i32, Custom);
539   setOperationAction(ISD::SMULO, MVT::i64, Custom);
540   setOperationAction(ISD::UMULO, MVT::i32, Custom);
541   setOperationAction(ISD::UMULO, MVT::i64, Custom);
542 
543   setOperationAction(ISD::FSIN, MVT::f32, Expand);
544   setOperationAction(ISD::FSIN, MVT::f64, Expand);
545   setOperationAction(ISD::FCOS, MVT::f32, Expand);
546   setOperationAction(ISD::FCOS, MVT::f64, Expand);
547   setOperationAction(ISD::FPOW, MVT::f32, Expand);
548   setOperationAction(ISD::FPOW, MVT::f64, Expand);
549   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
550   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
551   if (Subtarget->hasFullFP16())
552     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
553   else
554     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
555 
556   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
557   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
558   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
559   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
560   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
561   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
562   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
563   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
564   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
565   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
566   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
567   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
568   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
569   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
570   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
571   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
572   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
573   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
574   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
575   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
576   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
577   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
578   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
579   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
580   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
581   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
582   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
583   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
584   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
585   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
586   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
587   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
588   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
589 
590   if (!Subtarget->hasFullFP16()) {
591     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
592     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
593     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
594     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
595     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
596     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
597     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
598     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
599     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
600     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
601     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
602     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
603     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
604     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
605     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
606     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
607     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
608     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
609     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
610     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
611     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
612     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
613 
614     // promote v4f16 to v4f32 when that is known to be safe.
615     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
616     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
617     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
618     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
619     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
620     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
621     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
622     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
623 
624     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
625     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
626     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
627     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
628     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
629     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
630     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
631     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
632     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
633     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
634     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
635     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
636     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
637     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
638     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
639 
640     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
641     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
642     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
643     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
644     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
645     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
646     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
647     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
648     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
649     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
650     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
651     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
652     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
653     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
654     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
655     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
656     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
657     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
658     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
659     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
660   }
661 
662   // AArch64 has implementations of a lot of rounding-like FP operations.
663   for (MVT Ty : {MVT::f32, MVT::f64}) {
664     setOperationAction(ISD::FFLOOR, Ty, Legal);
665     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
666     setOperationAction(ISD::FCEIL, Ty, Legal);
667     setOperationAction(ISD::FRINT, Ty, Legal);
668     setOperationAction(ISD::FTRUNC, Ty, Legal);
669     setOperationAction(ISD::FROUND, Ty, Legal);
670     setOperationAction(ISD::FMINNUM, Ty, Legal);
671     setOperationAction(ISD::FMAXNUM, Ty, Legal);
672     setOperationAction(ISD::FMINIMUM, Ty, Legal);
673     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
674     setOperationAction(ISD::LROUND, Ty, Legal);
675     setOperationAction(ISD::LLROUND, Ty, Legal);
676     setOperationAction(ISD::LRINT, Ty, Legal);
677     setOperationAction(ISD::LLRINT, Ty, Legal);
678   }
679 
680   if (Subtarget->hasFullFP16()) {
681     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
682     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
683     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
684     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
685     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
686     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
687     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
688     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
689     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
690     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
691   }
692 
693   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
694 
695   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
696 
697   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
698   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
699   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
700   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
701   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
702 
703   // Generate outline atomics library calls only if LSE was not specified for
704   // subtarget
705   if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
706     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
707     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
708     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
709     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
710     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
711     setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
712     setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
713     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
714     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
715     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
716     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
717     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
718     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
719     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
720     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
721     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
722     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
723     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
724     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
725     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
726     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
727     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
728     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
729     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
730     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
731 #define LCALLNAMES(A, B, N)                                                    \
732   setLibcallName(A##N##_RELAX, #B #N "_relax");                                \
733   setLibcallName(A##N##_ACQ, #B #N "_acq");                                    \
734   setLibcallName(A##N##_REL, #B #N "_rel");                                    \
735   setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
736 #define LCALLNAME4(A, B)                                                       \
737   LCALLNAMES(A, B, 1)                                                          \
738   LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
739 #define LCALLNAME5(A, B)                                                       \
740   LCALLNAMES(A, B, 1)                                                          \
741   LCALLNAMES(A, B, 2)                                                          \
742   LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
743     LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
744     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
745     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
746     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
747     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
748     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
749 #undef LCALLNAMES
750 #undef LCALLNAME4
751 #undef LCALLNAME5
752   }
753 
754   // 128-bit loads and stores can be done without expanding
755   setOperationAction(ISD::LOAD, MVT::i128, Custom);
756   setOperationAction(ISD::STORE, MVT::i128, Custom);
757 
758   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
759   // custom lowering, as there are no un-paired non-temporal stores and
760   // legalization will break up 256 bit inputs.
761   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
762   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
763   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
764   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
765   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
766   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
767   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
768 
769   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
770   // This requires the Performance Monitors extension.
771   if (Subtarget->hasPerfMon())
772     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
773 
774   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
775       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
776     // Issue __sincos_stret if available.
777     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
778     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
779   } else {
780     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
781     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
782   }
783 
784   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
785     // MSVCRT doesn't have powi; fall back to pow
786     setLibcallName(RTLIB::POWI_F32, nullptr);
787     setLibcallName(RTLIB::POWI_F64, nullptr);
788   }
789 
790   // Make floating-point constants legal for the large code model, so they don't
791   // become loads from the constant pool.
792   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
793     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
794     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
795   }
796 
797   // AArch64 does not have floating-point extending loads, i1 sign-extending
798   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
799   for (MVT VT : MVT::fp_valuetypes()) {
800     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
801     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
802     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
803     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
804   }
805   for (MVT VT : MVT::integer_valuetypes())
806     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
807 
808   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
809   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
810   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
811   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
812   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
813   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
814   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
815 
816   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
817   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
818   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
819 
820   // Indexed loads and stores are supported.
821   for (unsigned im = (unsigned)ISD::PRE_INC;
822        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
823     setIndexedLoadAction(im, MVT::i8, Legal);
824     setIndexedLoadAction(im, MVT::i16, Legal);
825     setIndexedLoadAction(im, MVT::i32, Legal);
826     setIndexedLoadAction(im, MVT::i64, Legal);
827     setIndexedLoadAction(im, MVT::f64, Legal);
828     setIndexedLoadAction(im, MVT::f32, Legal);
829     setIndexedLoadAction(im, MVT::f16, Legal);
830     setIndexedLoadAction(im, MVT::bf16, Legal);
831     setIndexedStoreAction(im, MVT::i8, Legal);
832     setIndexedStoreAction(im, MVT::i16, Legal);
833     setIndexedStoreAction(im, MVT::i32, Legal);
834     setIndexedStoreAction(im, MVT::i64, Legal);
835     setIndexedStoreAction(im, MVT::f64, Legal);
836     setIndexedStoreAction(im, MVT::f32, Legal);
837     setIndexedStoreAction(im, MVT::f16, Legal);
838     setIndexedStoreAction(im, MVT::bf16, Legal);
839   }
840 
841   // Trap.
842   setOperationAction(ISD::TRAP, MVT::Other, Legal);
843   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
844   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
845 
846   // We combine OR nodes for bitfield operations.
847   setTargetDAGCombine(ISD::OR);
848   // Try to create BICs for vector ANDs.
849   setTargetDAGCombine(ISD::AND);
850 
851   // Vector add and sub nodes may conceal a high-half opportunity.
852   // Also, try to fold ADD into CSINC/CSINV..
853   setTargetDAGCombine(ISD::ADD);
854   setTargetDAGCombine(ISD::ABS);
855   setTargetDAGCombine(ISD::SUB);
856   setTargetDAGCombine(ISD::SRL);
857   setTargetDAGCombine(ISD::XOR);
858   setTargetDAGCombine(ISD::SINT_TO_FP);
859   setTargetDAGCombine(ISD::UINT_TO_FP);
860 
861   setTargetDAGCombine(ISD::FP_TO_SINT);
862   setTargetDAGCombine(ISD::FP_TO_UINT);
863   setTargetDAGCombine(ISD::FDIV);
864 
865   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
866 
867   setTargetDAGCombine(ISD::ANY_EXTEND);
868   setTargetDAGCombine(ISD::ZERO_EXTEND);
869   setTargetDAGCombine(ISD::SIGN_EXTEND);
870   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
871   setTargetDAGCombine(ISD::TRUNCATE);
872   setTargetDAGCombine(ISD::CONCAT_VECTORS);
873   setTargetDAGCombine(ISD::STORE);
874   if (Subtarget->supportsAddressTopByteIgnored())
875     setTargetDAGCombine(ISD::LOAD);
876 
877   setTargetDAGCombine(ISD::MUL);
878 
879   setTargetDAGCombine(ISD::SELECT);
880   setTargetDAGCombine(ISD::VSELECT);
881 
882   setTargetDAGCombine(ISD::INTRINSIC_VOID);
883   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
884   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
885   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
886   setTargetDAGCombine(ISD::VECREDUCE_ADD);
887 
888   setTargetDAGCombine(ISD::GlobalAddress);
889 
890   // In case of strict alignment, avoid an excessive number of byte wide stores.
891   MaxStoresPerMemsetOptSize = 8;
892   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
893                        ? MaxStoresPerMemsetOptSize : 32;
894 
895   MaxGluedStoresPerMemcpy = 4;
896   MaxStoresPerMemcpyOptSize = 4;
897   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
898                        ? MaxStoresPerMemcpyOptSize : 16;
899 
900   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
901 
902   MaxLoadsPerMemcmpOptSize = 4;
903   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
904                       ? MaxLoadsPerMemcmpOptSize : 8;
905 
906   setStackPointerRegisterToSaveRestore(AArch64::SP);
907 
908   setSchedulingPreference(Sched::Hybrid);
909 
910   EnableExtLdPromotion = true;
911 
912   // Set required alignment.
913   setMinFunctionAlignment(Align(4));
914   // Set preferred alignments.
915   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
916   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
917 
918   // Only change the limit for entries in a jump table if specified by
919   // the sub target, but not at the command line.
920   unsigned MaxJT = STI.getMaximumJumpTableSize();
921   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
922     setMaximumJumpTableSize(MaxJT);
923 
924   setHasExtractBitsInsn(true);
925 
926   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
927 
928   if (Subtarget->hasNEON()) {
929     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
930     // silliness like this:
931     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
932     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
933     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
934     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
935     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
936     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
937     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
938     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
939     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
940     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
941     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
942     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
943     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
944     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
945     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
946     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
947     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
948     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
949     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
950     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
951     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
952     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
953     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
954     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
955     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
956 
957     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
958     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
959     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
960     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
961     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
962 
963     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
964 
965     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
966     // elements smaller than i32, so promote the input to i32 first.
967     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
968     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
969     // i8 vector elements also need promotion to i32 for v8i8
970     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
971     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
972     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
973     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
974     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
975     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
976     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
977     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
978     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
979     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
980     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
981 
982     if (Subtarget->hasFullFP16()) {
983       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
984       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
985       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
986       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
987     } else {
988       // when AArch64 doesn't have fullfp16 support, promote the input
989       // to i32 first.
990       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
991       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
992       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
993       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
994     }
995 
996     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
997     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
998 
999     // AArch64 doesn't have MUL.2d:
1000     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
1001     // Custom handling for some quad-vector types to detect MULL.
1002     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
1003     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1004     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1005 
1006     // Saturates
1007     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1008                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1009       setOperationAction(ISD::SADDSAT, VT, Legal);
1010       setOperationAction(ISD::UADDSAT, VT, Legal);
1011       setOperationAction(ISD::SSUBSAT, VT, Legal);
1012       setOperationAction(ISD::USUBSAT, VT, Legal);
1013     }
1014 
1015     // Vector reductions
1016     for (MVT VT : { MVT::v4f16, MVT::v2f32,
1017                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1018       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1019       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1020 
1021       if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())
1022         setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
1023     }
1024     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1025                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1026       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1027       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1028       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1029       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1030       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1031     }
1032     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
1033 
1034     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
1035     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
1036     // Likewise, narrowing and extending vector loads/stores aren't handled
1037     // directly.
1038     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1039       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
1040 
1041       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
1042         setOperationAction(ISD::MULHS, VT, Legal);
1043         setOperationAction(ISD::MULHU, VT, Legal);
1044       } else {
1045         setOperationAction(ISD::MULHS, VT, Expand);
1046         setOperationAction(ISD::MULHU, VT, Expand);
1047       }
1048       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1049       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1050 
1051       setOperationAction(ISD::BSWAP, VT, Expand);
1052       setOperationAction(ISD::CTTZ, VT, Expand);
1053 
1054       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1055         setTruncStoreAction(VT, InnerVT, Expand);
1056         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1057         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1058         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1059       }
1060     }
1061 
1062     // AArch64 has implementations of a lot of rounding-like FP operations.
1063     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
1064       setOperationAction(ISD::FFLOOR, Ty, Legal);
1065       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1066       setOperationAction(ISD::FCEIL, Ty, Legal);
1067       setOperationAction(ISD::FRINT, Ty, Legal);
1068       setOperationAction(ISD::FTRUNC, Ty, Legal);
1069       setOperationAction(ISD::FROUND, Ty, Legal);
1070     }
1071 
1072     if (Subtarget->hasFullFP16()) {
1073       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
1074         setOperationAction(ISD::FFLOOR, Ty, Legal);
1075         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1076         setOperationAction(ISD::FCEIL, Ty, Legal);
1077         setOperationAction(ISD::FRINT, Ty, Legal);
1078         setOperationAction(ISD::FTRUNC, Ty, Legal);
1079         setOperationAction(ISD::FROUND, Ty, Legal);
1080       }
1081     }
1082 
1083     if (Subtarget->hasSVE())
1084       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
1085 
1086     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
1087   }
1088 
1089   if (Subtarget->hasSVE()) {
1090     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
1091     // splat of 0 or undef) once vector selects supported in SVE codegen. See
1092     // D68877 for more details.
1093     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
1094       setOperationAction(ISD::BITREVERSE, VT, Custom);
1095       setOperationAction(ISD::BSWAP, VT, Custom);
1096       setOperationAction(ISD::CTLZ, VT, Custom);
1097       setOperationAction(ISD::CTPOP, VT, Custom);
1098       setOperationAction(ISD::CTTZ, VT, Custom);
1099       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1100       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1101       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1102       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1103       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1104       setOperationAction(ISD::MGATHER, VT, Custom);
1105       setOperationAction(ISD::MSCATTER, VT, Custom);
1106       setOperationAction(ISD::MUL, VT, Custom);
1107       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1108       setOperationAction(ISD::SELECT, VT, Custom);
1109       setOperationAction(ISD::SDIV, VT, Custom);
1110       setOperationAction(ISD::UDIV, VT, Custom);
1111       setOperationAction(ISD::SMIN, VT, Custom);
1112       setOperationAction(ISD::UMIN, VT, Custom);
1113       setOperationAction(ISD::SMAX, VT, Custom);
1114       setOperationAction(ISD::UMAX, VT, Custom);
1115       setOperationAction(ISD::SHL, VT, Custom);
1116       setOperationAction(ISD::SRL, VT, Custom);
1117       setOperationAction(ISD::SRA, VT, Custom);
1118       setOperationAction(ISD::ABS, VT, Custom);
1119       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1120       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1121       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1122       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1123       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1124       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1125       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1126       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1127     }
1128 
1129     // Illegal unpacked integer vector types.
1130     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1131       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1132       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1133     }
1134 
1135     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1136       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1137       setOperationAction(ISD::SELECT, VT, Custom);
1138       setOperationAction(ISD::SETCC, VT, Custom);
1139       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1140       setOperationAction(ISD::TRUNCATE, VT, Custom);
1141       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1142       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1143       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1144 
1145       // There are no legal MVT::nxv16f## based types.
1146       if (VT != MVT::nxv16i1) {
1147         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1148         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1149       }
1150     }
1151 
1152     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1153                     MVT::nxv4f32, MVT::nxv2f64}) {
1154       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1155       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1156       setOperationAction(ISD::MGATHER, VT, Custom);
1157       setOperationAction(ISD::MSCATTER, VT, Custom);
1158       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1159       setOperationAction(ISD::SELECT, VT, Custom);
1160       setOperationAction(ISD::FADD, VT, Custom);
1161       setOperationAction(ISD::FDIV, VT, Custom);
1162       setOperationAction(ISD::FMA, VT, Custom);
1163       setOperationAction(ISD::FMAXNUM, VT, Custom);
1164       setOperationAction(ISD::FMINNUM, VT, Custom);
1165       setOperationAction(ISD::FMUL, VT, Custom);
1166       setOperationAction(ISD::FNEG, VT, Custom);
1167       setOperationAction(ISD::FSUB, VT, Custom);
1168       setOperationAction(ISD::FCEIL, VT, Custom);
1169       setOperationAction(ISD::FFLOOR, VT, Custom);
1170       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1171       setOperationAction(ISD::FRINT, VT, Custom);
1172       setOperationAction(ISD::FROUND, VT, Custom);
1173       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1174       setOperationAction(ISD::FTRUNC, VT, Custom);
1175       setOperationAction(ISD::FSQRT, VT, Custom);
1176       setOperationAction(ISD::FABS, VT, Custom);
1177       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1178       setOperationAction(ISD::FP_ROUND, VT, Custom);
1179       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1180       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1181       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1182       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1183     }
1184 
1185     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
1186       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1187       setOperationAction(ISD::MGATHER, VT, Custom);
1188       setOperationAction(ISD::MSCATTER, VT, Custom);
1189     }
1190 
1191     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1192 
1193     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1194     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1195 
1196     // NOTE: Currently this has to happen after computeRegisterProperties rather
1197     // than the preferred option of combining it with the addRegisterClass call.
1198     if (Subtarget->useSVEForFixedLengthVectors()) {
1199       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1200         if (useSVEForFixedLengthVectorVT(VT))
1201           addTypeForFixedLengthSVE(VT);
1202       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1203         if (useSVEForFixedLengthVectorVT(VT))
1204           addTypeForFixedLengthSVE(VT);
1205 
1206       // 64bit results can mean a bigger than NEON input.
1207       for (auto VT : {MVT::v8i8, MVT::v4i16})
1208         setOperationAction(ISD::TRUNCATE, VT, Custom);
1209       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1210 
1211       // 128bit results imply a bigger than NEON input.
1212       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1213         setOperationAction(ISD::TRUNCATE, VT, Custom);
1214       for (auto VT : {MVT::v8f16, MVT::v4f32})
1215         setOperationAction(ISD::FP_ROUND, VT, Expand);
1216 
1217       // These operations are not supported on NEON but SVE can do them.
1218       setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1219       setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
1220       setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1221       setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
1222       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1223       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1224       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1225       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1226       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1227       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1228       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1229       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1230       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1231       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1232       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1233       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1234       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1235       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1236       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1237       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1238       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1239       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1240       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1241       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1242       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1243       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1244       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1245       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1246       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1247       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1248       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1249       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1250       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1251       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1252 
1253       // Int operations with no NEON support.
1254       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1255                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1256         setOperationAction(ISD::BITREVERSE, VT, Custom);
1257         setOperationAction(ISD::CTTZ, VT, Custom);
1258         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1259         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1260         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1261       }
1262 
1263       // FP operations with no NEON support.
1264       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
1265                       MVT::v1f64, MVT::v2f64})
1266         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1267 
1268       // Use SVE for vectors with more than 2 elements.
1269       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1270         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1271     }
1272   }
1273 
1274   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1275 }
1276 
1277 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
1278   assert(VT.isVector() && "VT should be a vector type");
1279 
1280   if (VT.isFloatingPoint()) {
1281     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1282     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1283     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1284   }
1285 
1286   // Mark vector float intrinsics as expand.
1287   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1288     setOperationAction(ISD::FSIN, VT, Expand);
1289     setOperationAction(ISD::FCOS, VT, Expand);
1290     setOperationAction(ISD::FPOW, VT, Expand);
1291     setOperationAction(ISD::FLOG, VT, Expand);
1292     setOperationAction(ISD::FLOG2, VT, Expand);
1293     setOperationAction(ISD::FLOG10, VT, Expand);
1294     setOperationAction(ISD::FEXP, VT, Expand);
1295     setOperationAction(ISD::FEXP2, VT, Expand);
1296 
1297     // But we do support custom-lowering for FCOPYSIGN.
1298     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1299   }
1300 
1301   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1302   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1303   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1304   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1305   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1306   setOperationAction(ISD::SRA, VT, Custom);
1307   setOperationAction(ISD::SRL, VT, Custom);
1308   setOperationAction(ISD::SHL, VT, Custom);
1309   setOperationAction(ISD::OR, VT, Custom);
1310   setOperationAction(ISD::SETCC, VT, Custom);
1311   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1312 
1313   setOperationAction(ISD::SELECT, VT, Expand);
1314   setOperationAction(ISD::SELECT_CC, VT, Expand);
1315   setOperationAction(ISD::VSELECT, VT, Expand);
1316   for (MVT InnerVT : MVT::all_valuetypes())
1317     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1318 
1319   // CNT supports only B element sizes, then use UADDLP to widen.
1320   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1321     setOperationAction(ISD::CTPOP, VT, Custom);
1322 
1323   setOperationAction(ISD::UDIV, VT, Expand);
1324   setOperationAction(ISD::SDIV, VT, Expand);
1325   setOperationAction(ISD::UREM, VT, Expand);
1326   setOperationAction(ISD::SREM, VT, Expand);
1327   setOperationAction(ISD::FREM, VT, Expand);
1328 
1329   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1330   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1331 
1332   if (!VT.isFloatingPoint())
1333     setOperationAction(ISD::ABS, VT, Legal);
1334 
1335   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1336   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1337     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1338       setOperationAction(Opcode, VT, Legal);
1339 
1340   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1341   if (VT.isFloatingPoint() &&
1342       VT.getVectorElementType() != MVT::bf16 &&
1343       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1344     for (unsigned Opcode :
1345          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1346       setOperationAction(Opcode, VT, Legal);
1347 
1348   if (Subtarget->isLittleEndian()) {
1349     for (unsigned im = (unsigned)ISD::PRE_INC;
1350          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1351       setIndexedLoadAction(im, VT, Legal);
1352       setIndexedStoreAction(im, VT, Legal);
1353     }
1354   }
1355 }
1356 
1357 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1358   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1359 
1360   // By default everything must be expanded.
1361   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1362     setOperationAction(Op, VT, Expand);
1363 
1364   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1365   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1366 
1367   // Lower fixed length vector operations to scalable equivalents.
1368   setOperationAction(ISD::ABS, VT, Custom);
1369   setOperationAction(ISD::ADD, VT, Custom);
1370   setOperationAction(ISD::AND, VT, Custom);
1371   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1372   setOperationAction(ISD::BITREVERSE, VT, Custom);
1373   setOperationAction(ISD::BSWAP, VT, Custom);
1374   setOperationAction(ISD::CTLZ, VT, Custom);
1375   setOperationAction(ISD::CTPOP, VT, Custom);
1376   setOperationAction(ISD::CTTZ, VT, Custom);
1377   setOperationAction(ISD::FADD, VT, Custom);
1378   setOperationAction(ISD::FCEIL, VT, Custom);
1379   setOperationAction(ISD::FDIV, VT, Custom);
1380   setOperationAction(ISD::FFLOOR, VT, Custom);
1381   setOperationAction(ISD::FMA, VT, Custom);
1382   setOperationAction(ISD::FMAXNUM, VT, Custom);
1383   setOperationAction(ISD::FMINNUM, VT, Custom);
1384   setOperationAction(ISD::FMUL, VT, Custom);
1385   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1386   setOperationAction(ISD::FNEG, VT, Custom);
1387   setOperationAction(ISD::FRINT, VT, Custom);
1388   setOperationAction(ISD::FROUND, VT, Custom);
1389   setOperationAction(ISD::FSQRT, VT, Custom);
1390   setOperationAction(ISD::FSUB, VT, Custom);
1391   setOperationAction(ISD::FTRUNC, VT, Custom);
1392   setOperationAction(ISD::LOAD, VT, Custom);
1393   setOperationAction(ISD::MUL, VT, Custom);
1394   setOperationAction(ISD::OR, VT, Custom);
1395   setOperationAction(ISD::SDIV, VT, Custom);
1396   setOperationAction(ISD::SETCC, VT, Custom);
1397   setOperationAction(ISD::SHL, VT, Custom);
1398   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1399   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1400   setOperationAction(ISD::SMAX, VT, Custom);
1401   setOperationAction(ISD::SMIN, VT, Custom);
1402   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1403   setOperationAction(ISD::SRA, VT, Custom);
1404   setOperationAction(ISD::SRL, VT, Custom);
1405   setOperationAction(ISD::STORE, VT, Custom);
1406   setOperationAction(ISD::SUB, VT, Custom);
1407   setOperationAction(ISD::TRUNCATE, VT, Custom);
1408   setOperationAction(ISD::UDIV, VT, Custom);
1409   setOperationAction(ISD::UMAX, VT, Custom);
1410   setOperationAction(ISD::UMIN, VT, Custom);
1411   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1412   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1413   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1414   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1415   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1416   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1417   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1418   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1419   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1420   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1421   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1422   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1423   setOperationAction(ISD::VSELECT, VT, Custom);
1424   setOperationAction(ISD::XOR, VT, Custom);
1425   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1426 }
1427 
1428 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1429   addRegisterClass(VT, &AArch64::FPR64RegClass);
1430   addTypeForNEON(VT, MVT::v2i32);
1431 }
1432 
1433 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1434   addRegisterClass(VT, &AArch64::FPR128RegClass);
1435   addTypeForNEON(VT, MVT::v4i32);
1436 }
1437 
1438 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1439                                               LLVMContext &C, EVT VT) const {
1440   if (!VT.isVector())
1441     return MVT::i32;
1442   if (VT.isScalableVector())
1443     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1444   return VT.changeVectorElementTypeToInteger();
1445 }
1446 
1447 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1448                                const APInt &Demanded,
1449                                TargetLowering::TargetLoweringOpt &TLO,
1450                                unsigned NewOpc) {
1451   uint64_t OldImm = Imm, NewImm, Enc;
1452   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1453 
1454   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1455   // bimm64.
1456   if (Imm == 0 || Imm == Mask ||
1457       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1458     return false;
1459 
1460   unsigned EltSize = Size;
1461   uint64_t DemandedBits = Demanded.getZExtValue();
1462 
1463   // Clear bits that are not demanded.
1464   Imm &= DemandedBits;
1465 
1466   while (true) {
1467     // The goal here is to set the non-demanded bits in a way that minimizes
1468     // the number of switching between 0 and 1. In order to achieve this goal,
1469     // we set the non-demanded bits to the value of the preceding demanded bits.
1470     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1471     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1472     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1473     // The final result is 0b11000011.
1474     uint64_t NonDemandedBits = ~DemandedBits;
1475     uint64_t InvertedImm = ~Imm & DemandedBits;
1476     uint64_t RotatedImm =
1477         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1478         NonDemandedBits;
1479     uint64_t Sum = RotatedImm + NonDemandedBits;
1480     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1481     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1482     NewImm = (Imm | Ones) & Mask;
1483 
1484     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1485     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1486     // we halve the element size and continue the search.
1487     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1488       break;
1489 
1490     // We cannot shrink the element size any further if it is 2-bits.
1491     if (EltSize == 2)
1492       return false;
1493 
1494     EltSize /= 2;
1495     Mask >>= EltSize;
1496     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1497 
1498     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1499     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1500       return false;
1501 
1502     // Merge the upper and lower halves of Imm and DemandedBits.
1503     Imm |= Hi;
1504     DemandedBits |= DemandedBitsHi;
1505   }
1506 
1507   ++NumOptimizedImms;
1508 
1509   // Replicate the element across the register width.
1510   while (EltSize < Size) {
1511     NewImm |= NewImm << EltSize;
1512     EltSize *= 2;
1513   }
1514 
1515   (void)OldImm;
1516   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1517          "demanded bits should never be altered");
1518   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1519 
1520   // Create the new constant immediate node.
1521   EVT VT = Op.getValueType();
1522   SDLoc DL(Op);
1523   SDValue New;
1524 
1525   // If the new constant immediate is all-zeros or all-ones, let the target
1526   // independent DAG combine optimize this node.
1527   if (NewImm == 0 || NewImm == OrigMask) {
1528     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1529                           TLO.DAG.getConstant(NewImm, DL, VT));
1530   // Otherwise, create a machine node so that target independent DAG combine
1531   // doesn't undo this optimization.
1532   } else {
1533     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1534     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1535     New = SDValue(
1536         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1537   }
1538 
1539   return TLO.CombineTo(Op, New);
1540 }
1541 
1542 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1543     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1544     TargetLoweringOpt &TLO) const {
1545   // Delay this optimization to as late as possible.
1546   if (!TLO.LegalOps)
1547     return false;
1548 
1549   if (!EnableOptimizeLogicalImm)
1550     return false;
1551 
1552   EVT VT = Op.getValueType();
1553   if (VT.isVector())
1554     return false;
1555 
1556   unsigned Size = VT.getSizeInBits();
1557   assert((Size == 32 || Size == 64) &&
1558          "i32 or i64 is expected after legalization.");
1559 
1560   // Exit early if we demand all bits.
1561   if (DemandedBits.countPopulation() == Size)
1562     return false;
1563 
1564   unsigned NewOpc;
1565   switch (Op.getOpcode()) {
1566   default:
1567     return false;
1568   case ISD::AND:
1569     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1570     break;
1571   case ISD::OR:
1572     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1573     break;
1574   case ISD::XOR:
1575     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1576     break;
1577   }
1578   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1579   if (!C)
1580     return false;
1581   uint64_t Imm = C->getZExtValue();
1582   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1583 }
1584 
1585 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1586 /// Mask are known to be either zero or one and return them Known.
1587 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1588     const SDValue Op, KnownBits &Known,
1589     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1590   switch (Op.getOpcode()) {
1591   default:
1592     break;
1593   case AArch64ISD::CSEL: {
1594     KnownBits Known2;
1595     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1596     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1597     Known = KnownBits::commonBits(Known, Known2);
1598     break;
1599   }
1600   case AArch64ISD::LOADgot:
1601   case AArch64ISD::ADDlow: {
1602     if (!Subtarget->isTargetILP32())
1603       break;
1604     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1605     Known.Zero = APInt::getHighBitsSet(64, 32);
1606     break;
1607   }
1608   case ISD::INTRINSIC_W_CHAIN: {
1609     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1610     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1611     switch (IntID) {
1612     default: return;
1613     case Intrinsic::aarch64_ldaxr:
1614     case Intrinsic::aarch64_ldxr: {
1615       unsigned BitWidth = Known.getBitWidth();
1616       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1617       unsigned MemBits = VT.getScalarSizeInBits();
1618       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1619       return;
1620     }
1621     }
1622     break;
1623   }
1624   case ISD::INTRINSIC_WO_CHAIN:
1625   case ISD::INTRINSIC_VOID: {
1626     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1627     switch (IntNo) {
1628     default:
1629       break;
1630     case Intrinsic::aarch64_neon_umaxv:
1631     case Intrinsic::aarch64_neon_uminv: {
1632       // Figure out the datatype of the vector operand. The UMINV instruction
1633       // will zero extend the result, so we can mark as known zero all the
1634       // bits larger than the element datatype. 32-bit or larget doesn't need
1635       // this as those are legal types and will be handled by isel directly.
1636       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1637       unsigned BitWidth = Known.getBitWidth();
1638       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1639         assert(BitWidth >= 8 && "Unexpected width!");
1640         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1641         Known.Zero |= Mask;
1642       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1643         assert(BitWidth >= 16 && "Unexpected width!");
1644         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1645         Known.Zero |= Mask;
1646       }
1647       break;
1648     } break;
1649     }
1650   }
1651   }
1652 }
1653 
1654 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1655                                                   EVT) const {
1656   return MVT::i64;
1657 }
1658 
1659 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1660     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1661     bool *Fast) const {
1662   if (Subtarget->requiresStrictAlign())
1663     return false;
1664 
1665   if (Fast) {
1666     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1667     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1668             // See comments in performSTORECombine() for more details about
1669             // these conditions.
1670 
1671             // Code that uses clang vector extensions can mark that it
1672             // wants unaligned accesses to be treated as fast by
1673             // underspecifying alignment to be 1 or 2.
1674             Alignment <= 2 ||
1675 
1676             // Disregard v2i64. Memcpy lowering produces those and splitting
1677             // them regresses performance on micro-benchmarks and olden/bh.
1678             VT == MVT::v2i64;
1679   }
1680   return true;
1681 }
1682 
1683 // Same as above but handling LLTs instead.
1684 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1685     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1686     bool *Fast) const {
1687   if (Subtarget->requiresStrictAlign())
1688     return false;
1689 
1690   if (Fast) {
1691     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1692     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1693             Ty.getSizeInBytes() != 16 ||
1694             // See comments in performSTORECombine() for more details about
1695             // these conditions.
1696 
1697             // Code that uses clang vector extensions can mark that it
1698             // wants unaligned accesses to be treated as fast by
1699             // underspecifying alignment to be 1 or 2.
1700             Alignment <= 2 ||
1701 
1702             // Disregard v2i64. Memcpy lowering produces those and splitting
1703             // them regresses performance on micro-benchmarks and olden/bh.
1704             Ty == LLT::vector(2, 64);
1705   }
1706   return true;
1707 }
1708 
1709 FastISel *
1710 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1711                                       const TargetLibraryInfo *libInfo) const {
1712   return AArch64::createFastISel(funcInfo, libInfo);
1713 }
1714 
1715 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1716 #define MAKE_CASE(V)                                                           \
1717   case V:                                                                      \
1718     return #V;
1719   switch ((AArch64ISD::NodeType)Opcode) {
1720   case AArch64ISD::FIRST_NUMBER:
1721     break;
1722     MAKE_CASE(AArch64ISD::CALL)
1723     MAKE_CASE(AArch64ISD::ADRP)
1724     MAKE_CASE(AArch64ISD::ADR)
1725     MAKE_CASE(AArch64ISD::ADDlow)
1726     MAKE_CASE(AArch64ISD::LOADgot)
1727     MAKE_CASE(AArch64ISD::RET_FLAG)
1728     MAKE_CASE(AArch64ISD::BRCOND)
1729     MAKE_CASE(AArch64ISD::CSEL)
1730     MAKE_CASE(AArch64ISD::FCSEL)
1731     MAKE_CASE(AArch64ISD::CSINV)
1732     MAKE_CASE(AArch64ISD::CSNEG)
1733     MAKE_CASE(AArch64ISD::CSINC)
1734     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1735     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1736     MAKE_CASE(AArch64ISD::ADD_PRED)
1737     MAKE_CASE(AArch64ISD::MUL_PRED)
1738     MAKE_CASE(AArch64ISD::SDIV_PRED)
1739     MAKE_CASE(AArch64ISD::SHL_PRED)
1740     MAKE_CASE(AArch64ISD::SMAX_PRED)
1741     MAKE_CASE(AArch64ISD::SMIN_PRED)
1742     MAKE_CASE(AArch64ISD::SRA_PRED)
1743     MAKE_CASE(AArch64ISD::SRL_PRED)
1744     MAKE_CASE(AArch64ISD::SUB_PRED)
1745     MAKE_CASE(AArch64ISD::UDIV_PRED)
1746     MAKE_CASE(AArch64ISD::UMAX_PRED)
1747     MAKE_CASE(AArch64ISD::UMIN_PRED)
1748     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
1749     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1750     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1751     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
1752     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
1753     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
1754     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
1755     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
1756     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
1757     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
1758     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
1759     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
1760     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
1761     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
1762     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
1763     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
1764     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
1765     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
1766     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
1767     MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
1768     MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
1769     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1770     MAKE_CASE(AArch64ISD::ADC)
1771     MAKE_CASE(AArch64ISD::SBC)
1772     MAKE_CASE(AArch64ISD::ADDS)
1773     MAKE_CASE(AArch64ISD::SUBS)
1774     MAKE_CASE(AArch64ISD::ADCS)
1775     MAKE_CASE(AArch64ISD::SBCS)
1776     MAKE_CASE(AArch64ISD::ANDS)
1777     MAKE_CASE(AArch64ISD::CCMP)
1778     MAKE_CASE(AArch64ISD::CCMN)
1779     MAKE_CASE(AArch64ISD::FCCMP)
1780     MAKE_CASE(AArch64ISD::FCMP)
1781     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1782     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1783     MAKE_CASE(AArch64ISD::DUP)
1784     MAKE_CASE(AArch64ISD::DUPLANE8)
1785     MAKE_CASE(AArch64ISD::DUPLANE16)
1786     MAKE_CASE(AArch64ISD::DUPLANE32)
1787     MAKE_CASE(AArch64ISD::DUPLANE64)
1788     MAKE_CASE(AArch64ISD::MOVI)
1789     MAKE_CASE(AArch64ISD::MOVIshift)
1790     MAKE_CASE(AArch64ISD::MOVIedit)
1791     MAKE_CASE(AArch64ISD::MOVImsl)
1792     MAKE_CASE(AArch64ISD::FMOV)
1793     MAKE_CASE(AArch64ISD::MVNIshift)
1794     MAKE_CASE(AArch64ISD::MVNImsl)
1795     MAKE_CASE(AArch64ISD::BICi)
1796     MAKE_CASE(AArch64ISD::ORRi)
1797     MAKE_CASE(AArch64ISD::BSP)
1798     MAKE_CASE(AArch64ISD::NEG)
1799     MAKE_CASE(AArch64ISD::EXTR)
1800     MAKE_CASE(AArch64ISD::ZIP1)
1801     MAKE_CASE(AArch64ISD::ZIP2)
1802     MAKE_CASE(AArch64ISD::UZP1)
1803     MAKE_CASE(AArch64ISD::UZP2)
1804     MAKE_CASE(AArch64ISD::TRN1)
1805     MAKE_CASE(AArch64ISD::TRN2)
1806     MAKE_CASE(AArch64ISD::REV16)
1807     MAKE_CASE(AArch64ISD::REV32)
1808     MAKE_CASE(AArch64ISD::REV64)
1809     MAKE_CASE(AArch64ISD::EXT)
1810     MAKE_CASE(AArch64ISD::VSHL)
1811     MAKE_CASE(AArch64ISD::VLSHR)
1812     MAKE_CASE(AArch64ISD::VASHR)
1813     MAKE_CASE(AArch64ISD::VSLI)
1814     MAKE_CASE(AArch64ISD::VSRI)
1815     MAKE_CASE(AArch64ISD::CMEQ)
1816     MAKE_CASE(AArch64ISD::CMGE)
1817     MAKE_CASE(AArch64ISD::CMGT)
1818     MAKE_CASE(AArch64ISD::CMHI)
1819     MAKE_CASE(AArch64ISD::CMHS)
1820     MAKE_CASE(AArch64ISD::FCMEQ)
1821     MAKE_CASE(AArch64ISD::FCMGE)
1822     MAKE_CASE(AArch64ISD::FCMGT)
1823     MAKE_CASE(AArch64ISD::CMEQz)
1824     MAKE_CASE(AArch64ISD::CMGEz)
1825     MAKE_CASE(AArch64ISD::CMGTz)
1826     MAKE_CASE(AArch64ISD::CMLEz)
1827     MAKE_CASE(AArch64ISD::CMLTz)
1828     MAKE_CASE(AArch64ISD::FCMEQz)
1829     MAKE_CASE(AArch64ISD::FCMGEz)
1830     MAKE_CASE(AArch64ISD::FCMGTz)
1831     MAKE_CASE(AArch64ISD::FCMLEz)
1832     MAKE_CASE(AArch64ISD::FCMLTz)
1833     MAKE_CASE(AArch64ISD::SADDV)
1834     MAKE_CASE(AArch64ISD::UADDV)
1835     MAKE_CASE(AArch64ISD::SRHADD)
1836     MAKE_CASE(AArch64ISD::URHADD)
1837     MAKE_CASE(AArch64ISD::SHADD)
1838     MAKE_CASE(AArch64ISD::UHADD)
1839     MAKE_CASE(AArch64ISD::SMINV)
1840     MAKE_CASE(AArch64ISD::UMINV)
1841     MAKE_CASE(AArch64ISD::SMAXV)
1842     MAKE_CASE(AArch64ISD::UMAXV)
1843     MAKE_CASE(AArch64ISD::SADDV_PRED)
1844     MAKE_CASE(AArch64ISD::UADDV_PRED)
1845     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1846     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1847     MAKE_CASE(AArch64ISD::SMINV_PRED)
1848     MAKE_CASE(AArch64ISD::UMINV_PRED)
1849     MAKE_CASE(AArch64ISD::ORV_PRED)
1850     MAKE_CASE(AArch64ISD::EORV_PRED)
1851     MAKE_CASE(AArch64ISD::ANDV_PRED)
1852     MAKE_CASE(AArch64ISD::CLASTA_N)
1853     MAKE_CASE(AArch64ISD::CLASTB_N)
1854     MAKE_CASE(AArch64ISD::LASTA)
1855     MAKE_CASE(AArch64ISD::LASTB)
1856     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1857     MAKE_CASE(AArch64ISD::TBL)
1858     MAKE_CASE(AArch64ISD::FADD_PRED)
1859     MAKE_CASE(AArch64ISD::FADDA_PRED)
1860     MAKE_CASE(AArch64ISD::FADDV_PRED)
1861     MAKE_CASE(AArch64ISD::FDIV_PRED)
1862     MAKE_CASE(AArch64ISD::FMA_PRED)
1863     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1864     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
1865     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1866     MAKE_CASE(AArch64ISD::FMINV_PRED)
1867     MAKE_CASE(AArch64ISD::FMINNM_PRED)
1868     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1869     MAKE_CASE(AArch64ISD::FMUL_PRED)
1870     MAKE_CASE(AArch64ISD::FSUB_PRED)
1871     MAKE_CASE(AArch64ISD::BIT)
1872     MAKE_CASE(AArch64ISD::CBZ)
1873     MAKE_CASE(AArch64ISD::CBNZ)
1874     MAKE_CASE(AArch64ISD::TBZ)
1875     MAKE_CASE(AArch64ISD::TBNZ)
1876     MAKE_CASE(AArch64ISD::TC_RETURN)
1877     MAKE_CASE(AArch64ISD::PREFETCH)
1878     MAKE_CASE(AArch64ISD::SITOF)
1879     MAKE_CASE(AArch64ISD::UITOF)
1880     MAKE_CASE(AArch64ISD::NVCAST)
1881     MAKE_CASE(AArch64ISD::SQSHL_I)
1882     MAKE_CASE(AArch64ISD::UQSHL_I)
1883     MAKE_CASE(AArch64ISD::SRSHR_I)
1884     MAKE_CASE(AArch64ISD::URSHR_I)
1885     MAKE_CASE(AArch64ISD::SQSHLU_I)
1886     MAKE_CASE(AArch64ISD::WrapperLarge)
1887     MAKE_CASE(AArch64ISD::LD2post)
1888     MAKE_CASE(AArch64ISD::LD3post)
1889     MAKE_CASE(AArch64ISD::LD4post)
1890     MAKE_CASE(AArch64ISD::ST2post)
1891     MAKE_CASE(AArch64ISD::ST3post)
1892     MAKE_CASE(AArch64ISD::ST4post)
1893     MAKE_CASE(AArch64ISD::LD1x2post)
1894     MAKE_CASE(AArch64ISD::LD1x3post)
1895     MAKE_CASE(AArch64ISD::LD1x4post)
1896     MAKE_CASE(AArch64ISD::ST1x2post)
1897     MAKE_CASE(AArch64ISD::ST1x3post)
1898     MAKE_CASE(AArch64ISD::ST1x4post)
1899     MAKE_CASE(AArch64ISD::LD1DUPpost)
1900     MAKE_CASE(AArch64ISD::LD2DUPpost)
1901     MAKE_CASE(AArch64ISD::LD3DUPpost)
1902     MAKE_CASE(AArch64ISD::LD4DUPpost)
1903     MAKE_CASE(AArch64ISD::LD1LANEpost)
1904     MAKE_CASE(AArch64ISD::LD2LANEpost)
1905     MAKE_CASE(AArch64ISD::LD3LANEpost)
1906     MAKE_CASE(AArch64ISD::LD4LANEpost)
1907     MAKE_CASE(AArch64ISD::ST2LANEpost)
1908     MAKE_CASE(AArch64ISD::ST3LANEpost)
1909     MAKE_CASE(AArch64ISD::ST4LANEpost)
1910     MAKE_CASE(AArch64ISD::SMULL)
1911     MAKE_CASE(AArch64ISD::UMULL)
1912     MAKE_CASE(AArch64ISD::FRECPE)
1913     MAKE_CASE(AArch64ISD::FRECPS)
1914     MAKE_CASE(AArch64ISD::FRSQRTE)
1915     MAKE_CASE(AArch64ISD::FRSQRTS)
1916     MAKE_CASE(AArch64ISD::STG)
1917     MAKE_CASE(AArch64ISD::STZG)
1918     MAKE_CASE(AArch64ISD::ST2G)
1919     MAKE_CASE(AArch64ISD::STZ2G)
1920     MAKE_CASE(AArch64ISD::SUNPKHI)
1921     MAKE_CASE(AArch64ISD::SUNPKLO)
1922     MAKE_CASE(AArch64ISD::UUNPKHI)
1923     MAKE_CASE(AArch64ISD::UUNPKLO)
1924     MAKE_CASE(AArch64ISD::INSR)
1925     MAKE_CASE(AArch64ISD::PTEST)
1926     MAKE_CASE(AArch64ISD::PTRUE)
1927     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1928     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1929     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1930     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1931     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1932     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1933     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1934     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1935     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1936     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1937     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1938     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1939     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1940     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1941     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1942     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1943     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1944     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1945     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1946     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1947     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1948     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1949     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1950     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1951     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1952     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1953     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1954     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1955     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1956     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1957     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1958     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1959     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1960     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1961     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1962     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1963     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1964     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1965     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1966     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1967     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1968     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1969     MAKE_CASE(AArch64ISD::ST1_PRED)
1970     MAKE_CASE(AArch64ISD::SST1_PRED)
1971     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1972     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1973     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1974     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1975     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1976     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1977     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1978     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1979     MAKE_CASE(AArch64ISD::LDP)
1980     MAKE_CASE(AArch64ISD::STP)
1981     MAKE_CASE(AArch64ISD::STNP)
1982     MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
1983     MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
1984     MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
1985     MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
1986     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1987     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1988     MAKE_CASE(AArch64ISD::UABD)
1989     MAKE_CASE(AArch64ISD::SABD)
1990     MAKE_CASE(AArch64ISD::CALL_RVMARKER)
1991   }
1992 #undef MAKE_CASE
1993   return nullptr;
1994 }
1995 
1996 MachineBasicBlock *
1997 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1998                                     MachineBasicBlock *MBB) const {
1999   // We materialise the F128CSEL pseudo-instruction as some control flow and a
2000   // phi node:
2001 
2002   // OrigBB:
2003   //     [... previous instrs leading to comparison ...]
2004   //     b.ne TrueBB
2005   //     b EndBB
2006   // TrueBB:
2007   //     ; Fallthrough
2008   // EndBB:
2009   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
2010 
2011   MachineFunction *MF = MBB->getParent();
2012   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2013   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2014   DebugLoc DL = MI.getDebugLoc();
2015   MachineFunction::iterator It = ++MBB->getIterator();
2016 
2017   Register DestReg = MI.getOperand(0).getReg();
2018   Register IfTrueReg = MI.getOperand(1).getReg();
2019   Register IfFalseReg = MI.getOperand(2).getReg();
2020   unsigned CondCode = MI.getOperand(3).getImm();
2021   bool NZCVKilled = MI.getOperand(4).isKill();
2022 
2023   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
2024   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
2025   MF->insert(It, TrueBB);
2026   MF->insert(It, EndBB);
2027 
2028   // Transfer rest of current basic-block to EndBB
2029   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
2030                 MBB->end());
2031   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
2032 
2033   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
2034   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
2035   MBB->addSuccessor(TrueBB);
2036   MBB->addSuccessor(EndBB);
2037 
2038   // TrueBB falls through to the end.
2039   TrueBB->addSuccessor(EndBB);
2040 
2041   if (!NZCVKilled) {
2042     TrueBB->addLiveIn(AArch64::NZCV);
2043     EndBB->addLiveIn(AArch64::NZCV);
2044   }
2045 
2046   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
2047       .addReg(IfTrueReg)
2048       .addMBB(TrueBB)
2049       .addReg(IfFalseReg)
2050       .addMBB(MBB);
2051 
2052   MI.eraseFromParent();
2053   return EndBB;
2054 }
2055 
2056 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
2057        MachineInstr &MI, MachineBasicBlock *BB) const {
2058   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2059              BB->getParent()->getFunction().getPersonalityFn())) &&
2060          "SEH does not use catchret!");
2061   return BB;
2062 }
2063 
2064 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
2065     MachineInstr &MI, MachineBasicBlock *BB) const {
2066   switch (MI.getOpcode()) {
2067   default:
2068 #ifndef NDEBUG
2069     MI.dump();
2070 #endif
2071     llvm_unreachable("Unexpected instruction for custom inserter!");
2072 
2073   case AArch64::F128CSEL:
2074     return EmitF128CSEL(MI, BB);
2075 
2076   case TargetOpcode::STACKMAP:
2077   case TargetOpcode::PATCHPOINT:
2078   case TargetOpcode::STATEPOINT:
2079     return emitPatchPoint(MI, BB);
2080 
2081   case AArch64::CATCHRET:
2082     return EmitLoweredCatchRet(MI, BB);
2083   }
2084 }
2085 
2086 //===----------------------------------------------------------------------===//
2087 // AArch64 Lowering private implementation.
2088 //===----------------------------------------------------------------------===//
2089 
2090 //===----------------------------------------------------------------------===//
2091 // Lowering Code
2092 //===----------------------------------------------------------------------===//
2093 
2094 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
2095 /// CC
2096 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
2097   switch (CC) {
2098   default:
2099     llvm_unreachable("Unknown condition code!");
2100   case ISD::SETNE:
2101     return AArch64CC::NE;
2102   case ISD::SETEQ:
2103     return AArch64CC::EQ;
2104   case ISD::SETGT:
2105     return AArch64CC::GT;
2106   case ISD::SETGE:
2107     return AArch64CC::GE;
2108   case ISD::SETLT:
2109     return AArch64CC::LT;
2110   case ISD::SETLE:
2111     return AArch64CC::LE;
2112   case ISD::SETUGT:
2113     return AArch64CC::HI;
2114   case ISD::SETUGE:
2115     return AArch64CC::HS;
2116   case ISD::SETULT:
2117     return AArch64CC::LO;
2118   case ISD::SETULE:
2119     return AArch64CC::LS;
2120   }
2121 }
2122 
2123 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
2124 static void changeFPCCToAArch64CC(ISD::CondCode CC,
2125                                   AArch64CC::CondCode &CondCode,
2126                                   AArch64CC::CondCode &CondCode2) {
2127   CondCode2 = AArch64CC::AL;
2128   switch (CC) {
2129   default:
2130     llvm_unreachable("Unknown FP condition!");
2131   case ISD::SETEQ:
2132   case ISD::SETOEQ:
2133     CondCode = AArch64CC::EQ;
2134     break;
2135   case ISD::SETGT:
2136   case ISD::SETOGT:
2137     CondCode = AArch64CC::GT;
2138     break;
2139   case ISD::SETGE:
2140   case ISD::SETOGE:
2141     CondCode = AArch64CC::GE;
2142     break;
2143   case ISD::SETOLT:
2144     CondCode = AArch64CC::MI;
2145     break;
2146   case ISD::SETOLE:
2147     CondCode = AArch64CC::LS;
2148     break;
2149   case ISD::SETONE:
2150     CondCode = AArch64CC::MI;
2151     CondCode2 = AArch64CC::GT;
2152     break;
2153   case ISD::SETO:
2154     CondCode = AArch64CC::VC;
2155     break;
2156   case ISD::SETUO:
2157     CondCode = AArch64CC::VS;
2158     break;
2159   case ISD::SETUEQ:
2160     CondCode = AArch64CC::EQ;
2161     CondCode2 = AArch64CC::VS;
2162     break;
2163   case ISD::SETUGT:
2164     CondCode = AArch64CC::HI;
2165     break;
2166   case ISD::SETUGE:
2167     CondCode = AArch64CC::PL;
2168     break;
2169   case ISD::SETLT:
2170   case ISD::SETULT:
2171     CondCode = AArch64CC::LT;
2172     break;
2173   case ISD::SETLE:
2174   case ISD::SETULE:
2175     CondCode = AArch64CC::LE;
2176     break;
2177   case ISD::SETNE:
2178   case ISD::SETUNE:
2179     CondCode = AArch64CC::NE;
2180     break;
2181   }
2182 }
2183 
2184 /// Convert a DAG fp condition code to an AArch64 CC.
2185 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2186 /// should be AND'ed instead of OR'ed.
2187 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2188                                      AArch64CC::CondCode &CondCode,
2189                                      AArch64CC::CondCode &CondCode2) {
2190   CondCode2 = AArch64CC::AL;
2191   switch (CC) {
2192   default:
2193     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2194     assert(CondCode2 == AArch64CC::AL);
2195     break;
2196   case ISD::SETONE:
2197     // (a one b)
2198     // == ((a olt b) || (a ogt b))
2199     // == ((a ord b) && (a une b))
2200     CondCode = AArch64CC::VC;
2201     CondCode2 = AArch64CC::NE;
2202     break;
2203   case ISD::SETUEQ:
2204     // (a ueq b)
2205     // == ((a uno b) || (a oeq b))
2206     // == ((a ule b) && (a uge b))
2207     CondCode = AArch64CC::PL;
2208     CondCode2 = AArch64CC::LE;
2209     break;
2210   }
2211 }
2212 
2213 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2214 /// CC usable with the vector instructions. Fewer operations are available
2215 /// without a real NZCV register, so we have to use less efficient combinations
2216 /// to get the same effect.
2217 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2218                                         AArch64CC::CondCode &CondCode,
2219                                         AArch64CC::CondCode &CondCode2,
2220                                         bool &Invert) {
2221   Invert = false;
2222   switch (CC) {
2223   default:
2224     // Mostly the scalar mappings work fine.
2225     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2226     break;
2227   case ISD::SETUO:
2228     Invert = true;
2229     LLVM_FALLTHROUGH;
2230   case ISD::SETO:
2231     CondCode = AArch64CC::MI;
2232     CondCode2 = AArch64CC::GE;
2233     break;
2234   case ISD::SETUEQ:
2235   case ISD::SETULT:
2236   case ISD::SETULE:
2237   case ISD::SETUGT:
2238   case ISD::SETUGE:
2239     // All of the compare-mask comparisons are ordered, but we can switch
2240     // between the two by a double inversion. E.g. ULE == !OGT.
2241     Invert = true;
2242     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2243                           CondCode, CondCode2);
2244     break;
2245   }
2246 }
2247 
2248 static bool isLegalArithImmed(uint64_t C) {
2249   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2250   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2251   LLVM_DEBUG(dbgs() << "Is imm " << C
2252                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2253   return IsLegal;
2254 }
2255 
2256 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2257 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2258 // can be set differently by this operation. It comes down to whether
2259 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2260 // everything is fine. If not then the optimization is wrong. Thus general
2261 // comparisons are only valid if op2 != 0.
2262 //
2263 // So, finally, the only LLVM-native comparisons that don't mention C and V
2264 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2265 // the absence of information about op2.
2266 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2267   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2268          (CC == ISD::SETEQ || CC == ISD::SETNE);
2269 }
2270 
2271 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2272                                       SelectionDAG &DAG, SDValue Chain,
2273                                       bool IsSignaling) {
2274   EVT VT = LHS.getValueType();
2275   assert(VT != MVT::f128);
2276   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2277   unsigned Opcode =
2278       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2279   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2280 }
2281 
2282 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2283                               const SDLoc &dl, SelectionDAG &DAG) {
2284   EVT VT = LHS.getValueType();
2285   const bool FullFP16 =
2286     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2287 
2288   if (VT.isFloatingPoint()) {
2289     assert(VT != MVT::f128);
2290     if (VT == MVT::f16 && !FullFP16) {
2291       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2292       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2293       VT = MVT::f32;
2294     }
2295     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2296   }
2297 
2298   // The CMP instruction is just an alias for SUBS, and representing it as
2299   // SUBS means that it's possible to get CSE with subtract operations.
2300   // A later phase can perform the optimization of setting the destination
2301   // register to WZR/XZR if it ends up being unused.
2302   unsigned Opcode = AArch64ISD::SUBS;
2303 
2304   if (isCMN(RHS, CC)) {
2305     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2306     Opcode = AArch64ISD::ADDS;
2307     RHS = RHS.getOperand(1);
2308   } else if (isCMN(LHS, CC)) {
2309     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2310     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2311     Opcode = AArch64ISD::ADDS;
2312     LHS = LHS.getOperand(1);
2313   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2314     if (LHS.getOpcode() == ISD::AND) {
2315       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2316       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2317       // of the signed comparisons.
2318       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2319                                            DAG.getVTList(VT, MVT_CC),
2320                                            LHS.getOperand(0),
2321                                            LHS.getOperand(1));
2322       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2323       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2324       return ANDSNode.getValue(1);
2325     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2326       // Use result of ANDS
2327       return LHS.getValue(1);
2328     }
2329   }
2330 
2331   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2332       .getValue(1);
2333 }
2334 
2335 /// \defgroup AArch64CCMP CMP;CCMP matching
2336 ///
2337 /// These functions deal with the formation of CMP;CCMP;... sequences.
2338 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2339 /// a comparison. They set the NZCV flags to a predefined value if their
2340 /// predicate is false. This allows to express arbitrary conjunctions, for
2341 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2342 /// expressed as:
2343 ///   cmp A
2344 ///   ccmp B, inv(CB), CA
2345 ///   check for CB flags
2346 ///
2347 /// This naturally lets us implement chains of AND operations with SETCC
2348 /// operands. And we can even implement some other situations by transforming
2349 /// them:
2350 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2351 ///     negating the flags used in a CCMP/FCCMP operations.
2352 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2353 ///     by negating the flags we test for afterwards. i.e.
2354 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2355 ///   - Note that we can only ever negate all previously processed results.
2356 ///     What we can not implement by flipping the flags to test is a negation
2357 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2358 ///     far, so the 2nd sub-tree we emit would also affect the first).
2359 /// With those tools we can implement some OR operations:
2360 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2361 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2362 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2363 ///     elimination rules from earlier to implement the whole thing as a
2364 ///     CCMP/FCCMP chain.
2365 ///
2366 /// As complete example:
2367 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2368 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2369 /// can be reassociated to:
2370 ///     or (and (setCC (cmp C)) setCD (cmp D))
2371 //         (or (setCA (cmp A)) (setCB (cmp B)))
2372 /// can be transformed to:
2373 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2374 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2375 /// which can be implemented as:
2376 ///   cmp C
2377 ///   ccmp D, inv(CD), CC
2378 ///   ccmp A, CA, inv(CD)
2379 ///   ccmp B, CB, inv(CA)
2380 ///   check for CB flags
2381 ///
2382 /// A counterexample is "or (and A B) (and C D)" which translates to
2383 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2384 /// can only implement 1 of the inner (not) operations, but not both!
2385 /// @{
2386 
2387 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2388 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2389                                          ISD::CondCode CC, SDValue CCOp,
2390                                          AArch64CC::CondCode Predicate,
2391                                          AArch64CC::CondCode OutCC,
2392                                          const SDLoc &DL, SelectionDAG &DAG) {
2393   unsigned Opcode = 0;
2394   const bool FullFP16 =
2395     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2396 
2397   if (LHS.getValueType().isFloatingPoint()) {
2398     assert(LHS.getValueType() != MVT::f128);
2399     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2400       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2401       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2402     }
2403     Opcode = AArch64ISD::FCCMP;
2404   } else if (RHS.getOpcode() == ISD::SUB) {
2405     SDValue SubOp0 = RHS.getOperand(0);
2406     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2407       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2408       Opcode = AArch64ISD::CCMN;
2409       RHS = RHS.getOperand(1);
2410     }
2411   }
2412   if (Opcode == 0)
2413     Opcode = AArch64ISD::CCMP;
2414 
2415   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2416   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2417   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2418   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2419   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2420 }
2421 
2422 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2423 /// expressed as a conjunction. See \ref AArch64CCMP.
2424 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2425 ///                     changing the conditions on the SETCC tests.
2426 ///                     (this means we can call emitConjunctionRec() with
2427 ///                      Negate==true on this sub-tree)
2428 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2429 ///                     cannot do the negation naturally. We are required to
2430 ///                     emit the subtree first in this case.
2431 /// \param WillNegate   Is true if are called when the result of this
2432 ///                     subexpression must be negated. This happens when the
2433 ///                     outer expression is an OR. We can use this fact to know
2434 ///                     that we have a double negation (or (or ...) ...) that
2435 ///                     can be implemented for free.
2436 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2437                                bool &MustBeFirst, bool WillNegate,
2438                                unsigned Depth = 0) {
2439   if (!Val.hasOneUse())
2440     return false;
2441   unsigned Opcode = Val->getOpcode();
2442   if (Opcode == ISD::SETCC) {
2443     if (Val->getOperand(0).getValueType() == MVT::f128)
2444       return false;
2445     CanNegate = true;
2446     MustBeFirst = false;
2447     return true;
2448   }
2449   // Protect against exponential runtime and stack overflow.
2450   if (Depth > 6)
2451     return false;
2452   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2453     bool IsOR = Opcode == ISD::OR;
2454     SDValue O0 = Val->getOperand(0);
2455     SDValue O1 = Val->getOperand(1);
2456     bool CanNegateL;
2457     bool MustBeFirstL;
2458     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2459       return false;
2460     bool CanNegateR;
2461     bool MustBeFirstR;
2462     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2463       return false;
2464 
2465     if (MustBeFirstL && MustBeFirstR)
2466       return false;
2467 
2468     if (IsOR) {
2469       // For an OR expression we need to be able to naturally negate at least
2470       // one side or we cannot do the transformation at all.
2471       if (!CanNegateL && !CanNegateR)
2472         return false;
2473       // If we the result of the OR will be negated and we can naturally negate
2474       // the leafs, then this sub-tree as a whole negates naturally.
2475       CanNegate = WillNegate && CanNegateL && CanNegateR;
2476       // If we cannot naturally negate the whole sub-tree, then this must be
2477       // emitted first.
2478       MustBeFirst = !CanNegate;
2479     } else {
2480       assert(Opcode == ISD::AND && "Must be OR or AND");
2481       // We cannot naturally negate an AND operation.
2482       CanNegate = false;
2483       MustBeFirst = MustBeFirstL || MustBeFirstR;
2484     }
2485     return true;
2486   }
2487   return false;
2488 }
2489 
2490 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2491 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2492 /// Tries to transform the given i1 producing node @p Val to a series compare
2493 /// and conditional compare operations. @returns an NZCV flags producing node
2494 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2495 /// transformation was not possible.
2496 /// \p Negate is true if we want this sub-tree being negated just by changing
2497 /// SETCC conditions.
2498 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2499     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2500     AArch64CC::CondCode Predicate) {
2501   // We're at a tree leaf, produce a conditional comparison operation.
2502   unsigned Opcode = Val->getOpcode();
2503   if (Opcode == ISD::SETCC) {
2504     SDValue LHS = Val->getOperand(0);
2505     SDValue RHS = Val->getOperand(1);
2506     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2507     bool isInteger = LHS.getValueType().isInteger();
2508     if (Negate)
2509       CC = getSetCCInverse(CC, LHS.getValueType());
2510     SDLoc DL(Val);
2511     // Determine OutCC and handle FP special case.
2512     if (isInteger) {
2513       OutCC = changeIntCCToAArch64CC(CC);
2514     } else {
2515       assert(LHS.getValueType().isFloatingPoint());
2516       AArch64CC::CondCode ExtraCC;
2517       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2518       // Some floating point conditions can't be tested with a single condition
2519       // code. Construct an additional comparison in this case.
2520       if (ExtraCC != AArch64CC::AL) {
2521         SDValue ExtraCmp;
2522         if (!CCOp.getNode())
2523           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2524         else
2525           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2526                                                ExtraCC, DL, DAG);
2527         CCOp = ExtraCmp;
2528         Predicate = ExtraCC;
2529       }
2530     }
2531 
2532     // Produce a normal comparison if we are first in the chain
2533     if (!CCOp)
2534       return emitComparison(LHS, RHS, CC, DL, DAG);
2535     // Otherwise produce a ccmp.
2536     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2537                                      DAG);
2538   }
2539   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2540 
2541   bool IsOR = Opcode == ISD::OR;
2542 
2543   SDValue LHS = Val->getOperand(0);
2544   bool CanNegateL;
2545   bool MustBeFirstL;
2546   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2547   assert(ValidL && "Valid conjunction/disjunction tree");
2548   (void)ValidL;
2549 
2550   SDValue RHS = Val->getOperand(1);
2551   bool CanNegateR;
2552   bool MustBeFirstR;
2553   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2554   assert(ValidR && "Valid conjunction/disjunction tree");
2555   (void)ValidR;
2556 
2557   // Swap sub-tree that must come first to the right side.
2558   if (MustBeFirstL) {
2559     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2560     std::swap(LHS, RHS);
2561     std::swap(CanNegateL, CanNegateR);
2562     std::swap(MustBeFirstL, MustBeFirstR);
2563   }
2564 
2565   bool NegateR;
2566   bool NegateAfterR;
2567   bool NegateL;
2568   bool NegateAfterAll;
2569   if (Opcode == ISD::OR) {
2570     // Swap the sub-tree that we can negate naturally to the left.
2571     if (!CanNegateL) {
2572       assert(CanNegateR && "at least one side must be negatable");
2573       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2574       assert(!Negate);
2575       std::swap(LHS, RHS);
2576       NegateR = false;
2577       NegateAfterR = true;
2578     } else {
2579       // Negate the left sub-tree if possible, otherwise negate the result.
2580       NegateR = CanNegateR;
2581       NegateAfterR = !CanNegateR;
2582     }
2583     NegateL = true;
2584     NegateAfterAll = !Negate;
2585   } else {
2586     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2587     assert(!Negate && "Valid conjunction/disjunction tree");
2588 
2589     NegateL = false;
2590     NegateR = false;
2591     NegateAfterR = false;
2592     NegateAfterAll = false;
2593   }
2594 
2595   // Emit sub-trees.
2596   AArch64CC::CondCode RHSCC;
2597   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2598   if (NegateAfterR)
2599     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2600   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2601   if (NegateAfterAll)
2602     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2603   return CmpL;
2604 }
2605 
2606 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2607 /// In some cases this is even possible with OR operations in the expression.
2608 /// See \ref AArch64CCMP.
2609 /// \see emitConjunctionRec().
2610 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2611                                AArch64CC::CondCode &OutCC) {
2612   bool DummyCanNegate;
2613   bool DummyMustBeFirst;
2614   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2615     return SDValue();
2616 
2617   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2618 }
2619 
2620 /// @}
2621 
2622 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2623 /// extension operations.
2624 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2625   auto isSupportedExtend = [&](SDValue V) {
2626     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2627       return true;
2628 
2629     if (V.getOpcode() == ISD::AND)
2630       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2631         uint64_t Mask = MaskCst->getZExtValue();
2632         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2633       }
2634 
2635     return false;
2636   };
2637 
2638   if (!Op.hasOneUse())
2639     return 0;
2640 
2641   if (isSupportedExtend(Op))
2642     return 1;
2643 
2644   unsigned Opc = Op.getOpcode();
2645   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2646     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2647       uint64_t Shift = ShiftCst->getZExtValue();
2648       if (isSupportedExtend(Op.getOperand(0)))
2649         return (Shift <= 4) ? 2 : 1;
2650       EVT VT = Op.getValueType();
2651       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2652         return 1;
2653     }
2654 
2655   return 0;
2656 }
2657 
2658 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2659                              SDValue &AArch64cc, SelectionDAG &DAG,
2660                              const SDLoc &dl) {
2661   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2662     EVT VT = RHS.getValueType();
2663     uint64_t C = RHSC->getZExtValue();
2664     if (!isLegalArithImmed(C)) {
2665       // Constant does not fit, try adjusting it by one?
2666       switch (CC) {
2667       default:
2668         break;
2669       case ISD::SETLT:
2670       case ISD::SETGE:
2671         if ((VT == MVT::i32 && C != 0x80000000 &&
2672              isLegalArithImmed((uint32_t)(C - 1))) ||
2673             (VT == MVT::i64 && C != 0x80000000ULL &&
2674              isLegalArithImmed(C - 1ULL))) {
2675           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2676           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2677           RHS = DAG.getConstant(C, dl, VT);
2678         }
2679         break;
2680       case ISD::SETULT:
2681       case ISD::SETUGE:
2682         if ((VT == MVT::i32 && C != 0 &&
2683              isLegalArithImmed((uint32_t)(C - 1))) ||
2684             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2685           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2686           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2687           RHS = DAG.getConstant(C, dl, VT);
2688         }
2689         break;
2690       case ISD::SETLE:
2691       case ISD::SETGT:
2692         if ((VT == MVT::i32 && C != INT32_MAX &&
2693              isLegalArithImmed((uint32_t)(C + 1))) ||
2694             (VT == MVT::i64 && C != INT64_MAX &&
2695              isLegalArithImmed(C + 1ULL))) {
2696           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2697           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2698           RHS = DAG.getConstant(C, dl, VT);
2699         }
2700         break;
2701       case ISD::SETULE:
2702       case ISD::SETUGT:
2703         if ((VT == MVT::i32 && C != UINT32_MAX &&
2704              isLegalArithImmed((uint32_t)(C + 1))) ||
2705             (VT == MVT::i64 && C != UINT64_MAX &&
2706              isLegalArithImmed(C + 1ULL))) {
2707           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2708           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2709           RHS = DAG.getConstant(C, dl, VT);
2710         }
2711         break;
2712       }
2713     }
2714   }
2715 
2716   // Comparisons are canonicalized so that the RHS operand is simpler than the
2717   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2718   // can fold some shift+extend operations on the RHS operand, so swap the
2719   // operands if that can be done.
2720   //
2721   // For example:
2722   //    lsl     w13, w11, #1
2723   //    cmp     w13, w12
2724   // can be turned into:
2725   //    cmp     w12, w11, lsl #1
2726   if (!isa<ConstantSDNode>(RHS) ||
2727       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2728     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2729 
2730     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2731       std::swap(LHS, RHS);
2732       CC = ISD::getSetCCSwappedOperands(CC);
2733     }
2734   }
2735 
2736   SDValue Cmp;
2737   AArch64CC::CondCode AArch64CC;
2738   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2739     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2740 
2741     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2742     // For the i8 operand, the largest immediate is 255, so this can be easily
2743     // encoded in the compare instruction. For the i16 operand, however, the
2744     // largest immediate cannot be encoded in the compare.
2745     // Therefore, use a sign extending load and cmn to avoid materializing the
2746     // -1 constant. For example,
2747     // movz w1, #65535
2748     // ldrh w0, [x0, #0]
2749     // cmp w0, w1
2750     // >
2751     // ldrsh w0, [x0, #0]
2752     // cmn w0, #1
2753     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2754     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2755     // ensure both the LHS and RHS are truly zero extended and to make sure the
2756     // transformation is profitable.
2757     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2758         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2759         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2760         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2761       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2762       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2763         SDValue SExt =
2764             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2765                         DAG.getValueType(MVT::i16));
2766         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2767                                                    RHS.getValueType()),
2768                              CC, dl, DAG);
2769         AArch64CC = changeIntCCToAArch64CC(CC);
2770       }
2771     }
2772 
2773     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2774       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2775         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2776           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2777       }
2778     }
2779   }
2780 
2781   if (!Cmp) {
2782     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2783     AArch64CC = changeIntCCToAArch64CC(CC);
2784   }
2785   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2786   return Cmp;
2787 }
2788 
2789 static std::pair<SDValue, SDValue>
2790 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2791   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2792          "Unsupported value type");
2793   SDValue Value, Overflow;
2794   SDLoc DL(Op);
2795   SDValue LHS = Op.getOperand(0);
2796   SDValue RHS = Op.getOperand(1);
2797   unsigned Opc = 0;
2798   switch (Op.getOpcode()) {
2799   default:
2800     llvm_unreachable("Unknown overflow instruction!");
2801   case ISD::SADDO:
2802     Opc = AArch64ISD::ADDS;
2803     CC = AArch64CC::VS;
2804     break;
2805   case ISD::UADDO:
2806     Opc = AArch64ISD::ADDS;
2807     CC = AArch64CC::HS;
2808     break;
2809   case ISD::SSUBO:
2810     Opc = AArch64ISD::SUBS;
2811     CC = AArch64CC::VS;
2812     break;
2813   case ISD::USUBO:
2814     Opc = AArch64ISD::SUBS;
2815     CC = AArch64CC::LO;
2816     break;
2817   // Multiply needs a little bit extra work.
2818   case ISD::SMULO:
2819   case ISD::UMULO: {
2820     CC = AArch64CC::NE;
2821     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2822     if (Op.getValueType() == MVT::i32) {
2823       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2824       // For a 32 bit multiply with overflow check we want the instruction
2825       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2826       // need to generate the following pattern:
2827       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2828       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2829       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2830       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2831       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2832                                 DAG.getConstant(0, DL, MVT::i64));
2833       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2834       // operation. We need to clear out the upper 32 bits, because we used a
2835       // widening multiply that wrote all 64 bits. In the end this should be a
2836       // noop.
2837       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2838       if (IsSigned) {
2839         // The signed overflow check requires more than just a simple check for
2840         // any bit set in the upper 32 bits of the result. These bits could be
2841         // just the sign bits of a negative number. To perform the overflow
2842         // check we have to arithmetic shift right the 32nd bit of the result by
2843         // 31 bits. Then we compare the result to the upper 32 bits.
2844         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2845                                         DAG.getConstant(32, DL, MVT::i64));
2846         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2847         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2848                                         DAG.getConstant(31, DL, MVT::i64));
2849         // It is important that LowerBits is last, otherwise the arithmetic
2850         // shift will not be folded into the compare (SUBS).
2851         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2852         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2853                        .getValue(1);
2854       } else {
2855         // The overflow check for unsigned multiply is easy. We only need to
2856         // check if any of the upper 32 bits are set. This can be done with a
2857         // CMP (shifted register). For that we need to generate the following
2858         // pattern:
2859         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2860         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2861                                         DAG.getConstant(32, DL, MVT::i64));
2862         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2863         Overflow =
2864             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2865                         DAG.getConstant(0, DL, MVT::i64),
2866                         UpperBits).getValue(1);
2867       }
2868       break;
2869     }
2870     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2871     // For the 64 bit multiply
2872     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2873     if (IsSigned) {
2874       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2875       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2876                                       DAG.getConstant(63, DL, MVT::i64));
2877       // It is important that LowerBits is last, otherwise the arithmetic
2878       // shift will not be folded into the compare (SUBS).
2879       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2880       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2881                      .getValue(1);
2882     } else {
2883       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2884       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2885       Overflow =
2886           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2887                       DAG.getConstant(0, DL, MVT::i64),
2888                       UpperBits).getValue(1);
2889     }
2890     break;
2891   }
2892   } // switch (...)
2893 
2894   if (Opc) {
2895     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2896 
2897     // Emit the AArch64 operation with overflow check.
2898     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2899     Overflow = Value.getValue(1);
2900   }
2901   return std::make_pair(Value, Overflow);
2902 }
2903 
2904 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
2905   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
2906     return LowerToScalableOp(Op, DAG);
2907 
2908   SDValue Sel = Op.getOperand(0);
2909   SDValue Other = Op.getOperand(1);
2910   SDLoc dl(Sel);
2911 
2912   // If the operand is an overflow checking operation, invert the condition
2913   // code and kill the Not operation. I.e., transform:
2914   // (xor (overflow_op_bool, 1))
2915   //   -->
2916   // (csel 1, 0, invert(cc), overflow_op_bool)
2917   // ... which later gets transformed to just a cset instruction with an
2918   // inverted condition code, rather than a cset + eor sequence.
2919   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2920     // Only lower legal XALUO ops.
2921     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2922       return SDValue();
2923 
2924     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2925     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2926     AArch64CC::CondCode CC;
2927     SDValue Value, Overflow;
2928     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2929     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2930     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2931                        CCVal, Overflow);
2932   }
2933   // If neither operand is a SELECT_CC, give up.
2934   if (Sel.getOpcode() != ISD::SELECT_CC)
2935     std::swap(Sel, Other);
2936   if (Sel.getOpcode() != ISD::SELECT_CC)
2937     return Op;
2938 
2939   // The folding we want to perform is:
2940   // (xor x, (select_cc a, b, cc, 0, -1) )
2941   //   -->
2942   // (csel x, (xor x, -1), cc ...)
2943   //
2944   // The latter will get matched to a CSINV instruction.
2945 
2946   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2947   SDValue LHS = Sel.getOperand(0);
2948   SDValue RHS = Sel.getOperand(1);
2949   SDValue TVal = Sel.getOperand(2);
2950   SDValue FVal = Sel.getOperand(3);
2951 
2952   // FIXME: This could be generalized to non-integer comparisons.
2953   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2954     return Op;
2955 
2956   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2957   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2958 
2959   // The values aren't constants, this isn't the pattern we're looking for.
2960   if (!CFVal || !CTVal)
2961     return Op;
2962 
2963   // We can commute the SELECT_CC by inverting the condition.  This
2964   // might be needed to make this fit into a CSINV pattern.
2965   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2966     std::swap(TVal, FVal);
2967     std::swap(CTVal, CFVal);
2968     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2969   }
2970 
2971   // If the constants line up, perform the transform!
2972   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2973     SDValue CCVal;
2974     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2975 
2976     FVal = Other;
2977     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2978                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2979 
2980     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2981                        CCVal, Cmp);
2982   }
2983 
2984   return Op;
2985 }
2986 
2987 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2988   EVT VT = Op.getValueType();
2989 
2990   // Let legalize expand this if it isn't a legal type yet.
2991   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2992     return SDValue();
2993 
2994   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2995 
2996   unsigned Opc;
2997   bool ExtraOp = false;
2998   switch (Op.getOpcode()) {
2999   default:
3000     llvm_unreachable("Invalid code");
3001   case ISD::ADDC:
3002     Opc = AArch64ISD::ADDS;
3003     break;
3004   case ISD::SUBC:
3005     Opc = AArch64ISD::SUBS;
3006     break;
3007   case ISD::ADDE:
3008     Opc = AArch64ISD::ADCS;
3009     ExtraOp = true;
3010     break;
3011   case ISD::SUBE:
3012     Opc = AArch64ISD::SBCS;
3013     ExtraOp = true;
3014     break;
3015   }
3016 
3017   if (!ExtraOp)
3018     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
3019   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
3020                      Op.getOperand(2));
3021 }
3022 
3023 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
3024   // Let legalize expand this if it isn't a legal type yet.
3025   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3026     return SDValue();
3027 
3028   SDLoc dl(Op);
3029   AArch64CC::CondCode CC;
3030   // The actual operation that sets the overflow or carry flag.
3031   SDValue Value, Overflow;
3032   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
3033 
3034   // We use 0 and 1 as false and true values.
3035   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3036   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3037 
3038   // We use an inverted condition, because the conditional select is inverted
3039   // too. This will allow it to be selected to a single instruction:
3040   // CSINC Wd, WZR, WZR, invert(cond).
3041   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3042   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
3043                          CCVal, Overflow);
3044 
3045   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3046   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3047 }
3048 
3049 // Prefetch operands are:
3050 // 1: Address to prefetch
3051 // 2: bool isWrite
3052 // 3: int locality (0 = no locality ... 3 = extreme locality)
3053 // 4: bool isDataCache
3054 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
3055   SDLoc DL(Op);
3056   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3057   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
3058   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3059 
3060   bool IsStream = !Locality;
3061   // When the locality number is set
3062   if (Locality) {
3063     // The front-end should have filtered out the out-of-range values
3064     assert(Locality <= 3 && "Prefetch locality out-of-range");
3065     // The locality degree is the opposite of the cache speed.
3066     // Put the number the other way around.
3067     // The encoding starts at 0 for level 1
3068     Locality = 3 - Locality;
3069   }
3070 
3071   // built the mask value encoding the expected behavior.
3072   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
3073                    (!IsData << 3) |     // IsDataCache bit
3074                    (Locality << 1) |    // Cache level bits
3075                    (unsigned)IsStream;  // Stream bit
3076   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
3077                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
3078 }
3079 
3080 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
3081                                               SelectionDAG &DAG) const {
3082   if (Op.getValueType().isScalableVector())
3083     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
3084 
3085   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
3086   return SDValue();
3087 }
3088 
3089 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
3090                                              SelectionDAG &DAG) const {
3091   if (Op.getValueType().isScalableVector())
3092     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
3093 
3094   bool IsStrict = Op->isStrictFPOpcode();
3095   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3096   EVT SrcVT = SrcVal.getValueType();
3097 
3098   if (SrcVT != MVT::f128) {
3099     // Expand cases where the input is a vector bigger than NEON.
3100     if (useSVEForFixedLengthVectorVT(SrcVT))
3101       return SDValue();
3102 
3103     // It's legal except when f128 is involved
3104     return Op;
3105   }
3106 
3107   return SDValue();
3108 }
3109 
3110 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3111                                                     SelectionDAG &DAG) const {
3112   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3113   // Any additional optimization in this function should be recorded
3114   // in the cost tables.
3115   EVT InVT = Op.getOperand(0).getValueType();
3116   EVT VT = Op.getValueType();
3117 
3118   if (VT.isScalableVector()) {
3119     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3120                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3121                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3122     return LowerToPredicatedOp(Op, DAG, Opcode);
3123   }
3124 
3125   unsigned NumElts = InVT.getVectorNumElements();
3126 
3127   // f16 conversions are promoted to f32 when full fp16 is not supported.
3128   if (InVT.getVectorElementType() == MVT::f16 &&
3129       !Subtarget->hasFullFP16()) {
3130     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3131     SDLoc dl(Op);
3132     return DAG.getNode(
3133         Op.getOpcode(), dl, Op.getValueType(),
3134         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3135   }
3136 
3137   uint64_t VTSize = VT.getFixedSizeInBits();
3138   uint64_t InVTSize = InVT.getFixedSizeInBits();
3139   if (VTSize < InVTSize) {
3140     SDLoc dl(Op);
3141     SDValue Cv =
3142         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3143                     Op.getOperand(0));
3144     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3145   }
3146 
3147   if (VTSize > InVTSize) {
3148     SDLoc dl(Op);
3149     MVT ExtVT =
3150         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3151                          VT.getVectorNumElements());
3152     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3153     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3154   }
3155 
3156   // Type changing conversions are illegal.
3157   return Op;
3158 }
3159 
3160 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3161                                               SelectionDAG &DAG) const {
3162   bool IsStrict = Op->isStrictFPOpcode();
3163   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3164 
3165   if (SrcVal.getValueType().isVector())
3166     return LowerVectorFP_TO_INT(Op, DAG);
3167 
3168   // f16 conversions are promoted to f32 when full fp16 is not supported.
3169   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3170     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3171     SDLoc dl(Op);
3172     return DAG.getNode(
3173         Op.getOpcode(), dl, Op.getValueType(),
3174         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3175   }
3176 
3177   if (SrcVal.getValueType() != MVT::f128) {
3178     // It's legal except when f128 is involved
3179     return Op;
3180   }
3181 
3182   return SDValue();
3183 }
3184 
3185 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3186                                                     SelectionDAG &DAG) const {
3187   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3188   // Any additional optimization in this function should be recorded
3189   // in the cost tables.
3190   EVT VT = Op.getValueType();
3191   SDLoc dl(Op);
3192   SDValue In = Op.getOperand(0);
3193   EVT InVT = In.getValueType();
3194   unsigned Opc = Op.getOpcode();
3195   bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
3196 
3197   if (VT.isScalableVector()) {
3198     if (InVT.getVectorElementType() == MVT::i1) {
3199       // We can't directly extend an SVE predicate; extend it first.
3200       unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3201       EVT CastVT = getPromotedVTForPredicate(InVT);
3202       In = DAG.getNode(CastOpc, dl, CastVT, In);
3203       return DAG.getNode(Opc, dl, VT, In);
3204     }
3205 
3206     unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
3207                                : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
3208     return LowerToPredicatedOp(Op, DAG, Opcode);
3209   }
3210 
3211   uint64_t VTSize = VT.getFixedSizeInBits();
3212   uint64_t InVTSize = InVT.getFixedSizeInBits();
3213   if (VTSize < InVTSize) {
3214     MVT CastVT =
3215         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3216                          InVT.getVectorNumElements());
3217     In = DAG.getNode(Opc, dl, CastVT, In);
3218     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3219   }
3220 
3221   if (VTSize > InVTSize) {
3222     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3223     EVT CastVT = VT.changeVectorElementTypeToInteger();
3224     In = DAG.getNode(CastOpc, dl, CastVT, In);
3225     return DAG.getNode(Opc, dl, VT, In);
3226   }
3227 
3228   return Op;
3229 }
3230 
3231 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3232                                             SelectionDAG &DAG) const {
3233   if (Op.getValueType().isVector())
3234     return LowerVectorINT_TO_FP(Op, DAG);
3235 
3236   bool IsStrict = Op->isStrictFPOpcode();
3237   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3238 
3239   // f16 conversions are promoted to f32 when full fp16 is not supported.
3240   if (Op.getValueType() == MVT::f16 &&
3241       !Subtarget->hasFullFP16()) {
3242     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3243     SDLoc dl(Op);
3244     return DAG.getNode(
3245         ISD::FP_ROUND, dl, MVT::f16,
3246         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3247         DAG.getIntPtrConstant(0, dl));
3248   }
3249 
3250   // i128 conversions are libcalls.
3251   if (SrcVal.getValueType() == MVT::i128)
3252     return SDValue();
3253 
3254   // Other conversions are legal, unless it's to the completely software-based
3255   // fp128.
3256   if (Op.getValueType() != MVT::f128)
3257     return Op;
3258   return SDValue();
3259 }
3260 
3261 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3262                                             SelectionDAG &DAG) const {
3263   // For iOS, we want to call an alternative entry point: __sincos_stret,
3264   // which returns the values in two S / D registers.
3265   SDLoc dl(Op);
3266   SDValue Arg = Op.getOperand(0);
3267   EVT ArgVT = Arg.getValueType();
3268   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3269 
3270   ArgListTy Args;
3271   ArgListEntry Entry;
3272 
3273   Entry.Node = Arg;
3274   Entry.Ty = ArgTy;
3275   Entry.IsSExt = false;
3276   Entry.IsZExt = false;
3277   Args.push_back(Entry);
3278 
3279   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3280                                         : RTLIB::SINCOS_STRET_F32;
3281   const char *LibcallName = getLibcallName(LC);
3282   SDValue Callee =
3283       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3284 
3285   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3286   TargetLowering::CallLoweringInfo CLI(DAG);
3287   CLI.setDebugLoc(dl)
3288       .setChain(DAG.getEntryNode())
3289       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3290 
3291   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3292   return CallResult.first;
3293 }
3294 
3295 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
3296   EVT OpVT = Op.getValueType();
3297   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3298     return SDValue();
3299 
3300   assert(Op.getOperand(0).getValueType() == MVT::i16);
3301   SDLoc DL(Op);
3302 
3303   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3304   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3305   return SDValue(
3306       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3307                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3308       0);
3309 }
3310 
3311 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3312   if (OrigVT.getSizeInBits() >= 64)
3313     return OrigVT;
3314 
3315   assert(OrigVT.isSimple() && "Expecting a simple value type");
3316 
3317   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3318   switch (OrigSimpleTy) {
3319   default: llvm_unreachable("Unexpected Vector Type");
3320   case MVT::v2i8:
3321   case MVT::v2i16:
3322      return MVT::v2i32;
3323   case MVT::v4i8:
3324     return  MVT::v4i16;
3325   }
3326 }
3327 
3328 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3329                                                  const EVT &OrigTy,
3330                                                  const EVT &ExtTy,
3331                                                  unsigned ExtOpcode) {
3332   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3333   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3334   // 64-bits we need to insert a new extension so that it will be 64-bits.
3335   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3336   if (OrigTy.getSizeInBits() >= 64)
3337     return N;
3338 
3339   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3340   EVT NewVT = getExtensionTo64Bits(OrigTy);
3341 
3342   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3343 }
3344 
3345 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3346                                    bool isSigned) {
3347   EVT VT = N->getValueType(0);
3348 
3349   if (N->getOpcode() != ISD::BUILD_VECTOR)
3350     return false;
3351 
3352   for (const SDValue &Elt : N->op_values()) {
3353     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3354       unsigned EltSize = VT.getScalarSizeInBits();
3355       unsigned HalfSize = EltSize / 2;
3356       if (isSigned) {
3357         if (!isIntN(HalfSize, C->getSExtValue()))
3358           return false;
3359       } else {
3360         if (!isUIntN(HalfSize, C->getZExtValue()))
3361           return false;
3362       }
3363       continue;
3364     }
3365     return false;
3366   }
3367 
3368   return true;
3369 }
3370 
3371 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3372   if (N->getOpcode() == ISD::SIGN_EXTEND ||
3373       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
3374     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3375                                              N->getOperand(0)->getValueType(0),
3376                                              N->getValueType(0),
3377                                              N->getOpcode());
3378 
3379   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3380   EVT VT = N->getValueType(0);
3381   SDLoc dl(N);
3382   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3383   unsigned NumElts = VT.getVectorNumElements();
3384   MVT TruncVT = MVT::getIntegerVT(EltSize);
3385   SmallVector<SDValue, 8> Ops;
3386   for (unsigned i = 0; i != NumElts; ++i) {
3387     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3388     const APInt &CInt = C->getAPIntValue();
3389     // Element types smaller than 32 bits are not legal, so use i32 elements.
3390     // The values are implicitly truncated so sext vs. zext doesn't matter.
3391     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3392   }
3393   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3394 }
3395 
3396 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3397   return N->getOpcode() == ISD::SIGN_EXTEND ||
3398          N->getOpcode() == ISD::ANY_EXTEND ||
3399          isExtendedBUILD_VECTOR(N, DAG, true);
3400 }
3401 
3402 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3403   return N->getOpcode() == ISD::ZERO_EXTEND ||
3404          N->getOpcode() == ISD::ANY_EXTEND ||
3405          isExtendedBUILD_VECTOR(N, DAG, false);
3406 }
3407 
3408 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3409   unsigned Opcode = N->getOpcode();
3410   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3411     SDNode *N0 = N->getOperand(0).getNode();
3412     SDNode *N1 = N->getOperand(1).getNode();
3413     return N0->hasOneUse() && N1->hasOneUse() &&
3414       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3415   }
3416   return false;
3417 }
3418 
3419 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3420   unsigned Opcode = N->getOpcode();
3421   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3422     SDNode *N0 = N->getOperand(0).getNode();
3423     SDNode *N1 = N->getOperand(1).getNode();
3424     return N0->hasOneUse() && N1->hasOneUse() &&
3425       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3426   }
3427   return false;
3428 }
3429 
3430 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3431                                                 SelectionDAG &DAG) const {
3432   // The rounding mode is in bits 23:22 of the FPSCR.
3433   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3434   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3435   // so that the shift + and get folded into a bitfield extract.
3436   SDLoc dl(Op);
3437 
3438   SDValue Chain = Op.getOperand(0);
3439   SDValue FPCR_64 = DAG.getNode(
3440       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3441       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3442   Chain = FPCR_64.getValue(1);
3443   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3444   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3445                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3446   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3447                               DAG.getConstant(22, dl, MVT::i32));
3448   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3449                             DAG.getConstant(3, dl, MVT::i32));
3450   return DAG.getMergeValues({AND, Chain}, dl);
3451 }
3452 
3453 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3454   EVT VT = Op.getValueType();
3455 
3456   // If SVE is available then i64 vector multiplications can also be made legal.
3457   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3458 
3459   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3460     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3461 
3462   // Multiplications are only custom-lowered for 128-bit vectors so that
3463   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3464   assert(VT.is128BitVector() && VT.isInteger() &&
3465          "unexpected type for custom-lowering ISD::MUL");
3466   SDNode *N0 = Op.getOperand(0).getNode();
3467   SDNode *N1 = Op.getOperand(1).getNode();
3468   unsigned NewOpc = 0;
3469   bool isMLA = false;
3470   bool isN0SExt = isSignExtended(N0, DAG);
3471   bool isN1SExt = isSignExtended(N1, DAG);
3472   if (isN0SExt && isN1SExt)
3473     NewOpc = AArch64ISD::SMULL;
3474   else {
3475     bool isN0ZExt = isZeroExtended(N0, DAG);
3476     bool isN1ZExt = isZeroExtended(N1, DAG);
3477     if (isN0ZExt && isN1ZExt)
3478       NewOpc = AArch64ISD::UMULL;
3479     else if (isN1SExt || isN1ZExt) {
3480       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3481       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3482       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3483         NewOpc = AArch64ISD::SMULL;
3484         isMLA = true;
3485       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3486         NewOpc =  AArch64ISD::UMULL;
3487         isMLA = true;
3488       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3489         std::swap(N0, N1);
3490         NewOpc =  AArch64ISD::UMULL;
3491         isMLA = true;
3492       }
3493     }
3494 
3495     if (!NewOpc) {
3496       if (VT == MVT::v2i64)
3497         // Fall through to expand this.  It is not legal.
3498         return SDValue();
3499       else
3500         // Other vector multiplications are legal.
3501         return Op;
3502     }
3503   }
3504 
3505   // Legalize to a S/UMULL instruction
3506   SDLoc DL(Op);
3507   SDValue Op0;
3508   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3509   if (!isMLA) {
3510     Op0 = skipExtensionForVectorMULL(N0, DAG);
3511     assert(Op0.getValueType().is64BitVector() &&
3512            Op1.getValueType().is64BitVector() &&
3513            "unexpected types for extended operands to VMULL");
3514     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3515   }
3516   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3517   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3518   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3519   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3520   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3521   EVT Op1VT = Op1.getValueType();
3522   return DAG.getNode(N0->getOpcode(), DL, VT,
3523                      DAG.getNode(NewOpc, DL, VT,
3524                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3525                      DAG.getNode(NewOpc, DL, VT,
3526                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3527 }
3528 
3529 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3530                                int Pattern) {
3531   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3532                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3533 }
3534 
3535 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3536                                                      SelectionDAG &DAG) const {
3537   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3538   SDLoc dl(Op);
3539   switch (IntNo) {
3540   default: return SDValue();    // Don't custom lower most intrinsics.
3541   case Intrinsic::thread_pointer: {
3542     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3543     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3544   }
3545   case Intrinsic::aarch64_neon_abs: {
3546     EVT Ty = Op.getValueType();
3547     if (Ty == MVT::i64) {
3548       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3549                                    Op.getOperand(1));
3550       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3551       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3552     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3553       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3554     } else {
3555       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3556     }
3557   }
3558   case Intrinsic::aarch64_neon_smax:
3559     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3560                        Op.getOperand(1), Op.getOperand(2));
3561   case Intrinsic::aarch64_neon_umax:
3562     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3563                        Op.getOperand(1), Op.getOperand(2));
3564   case Intrinsic::aarch64_neon_smin:
3565     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3566                        Op.getOperand(1), Op.getOperand(2));
3567   case Intrinsic::aarch64_neon_umin:
3568     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3569                        Op.getOperand(1), Op.getOperand(2));
3570 
3571   case Intrinsic::aarch64_sve_sunpkhi:
3572     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3573                        Op.getOperand(1));
3574   case Intrinsic::aarch64_sve_sunpklo:
3575     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3576                        Op.getOperand(1));
3577   case Intrinsic::aarch64_sve_uunpkhi:
3578     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3579                        Op.getOperand(1));
3580   case Intrinsic::aarch64_sve_uunpklo:
3581     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3582                        Op.getOperand(1));
3583   case Intrinsic::aarch64_sve_clasta_n:
3584     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3585                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3586   case Intrinsic::aarch64_sve_clastb_n:
3587     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3588                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3589   case Intrinsic::aarch64_sve_lasta:
3590     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3591                        Op.getOperand(1), Op.getOperand(2));
3592   case Intrinsic::aarch64_sve_lastb:
3593     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3594                        Op.getOperand(1), Op.getOperand(2));
3595   case Intrinsic::aarch64_sve_rev:
3596     return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
3597                        Op.getOperand(1));
3598   case Intrinsic::aarch64_sve_tbl:
3599     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3600                        Op.getOperand(1), Op.getOperand(2));
3601   case Intrinsic::aarch64_sve_trn1:
3602     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3603                        Op.getOperand(1), Op.getOperand(2));
3604   case Intrinsic::aarch64_sve_trn2:
3605     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3606                        Op.getOperand(1), Op.getOperand(2));
3607   case Intrinsic::aarch64_sve_uzp1:
3608     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3609                        Op.getOperand(1), Op.getOperand(2));
3610   case Intrinsic::aarch64_sve_uzp2:
3611     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3612                        Op.getOperand(1), Op.getOperand(2));
3613   case Intrinsic::aarch64_sve_zip1:
3614     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3615                        Op.getOperand(1), Op.getOperand(2));
3616   case Intrinsic::aarch64_sve_zip2:
3617     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3618                        Op.getOperand(1), Op.getOperand(2));
3619   case Intrinsic::aarch64_sve_ptrue:
3620     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3621                        Op.getOperand(1));
3622   case Intrinsic::aarch64_sve_clz:
3623     return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
3624                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3625   case Intrinsic::aarch64_sve_cnt: {
3626     SDValue Data = Op.getOperand(3);
3627     // CTPOP only supports integer operands.
3628     if (Data.getValueType().isFloatingPoint())
3629       Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
3630     return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
3631                        Op.getOperand(2), Data, Op.getOperand(1));
3632   }
3633   case Intrinsic::aarch64_sve_dupq_lane:
3634     return LowerDUPQLane(Op, DAG);
3635   case Intrinsic::aarch64_sve_convert_from_svbool:
3636     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3637                        Op.getOperand(1));
3638   case Intrinsic::aarch64_sve_fneg:
3639     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
3640                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3641   case Intrinsic::aarch64_sve_frintp:
3642     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
3643                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3644   case Intrinsic::aarch64_sve_frintm:
3645     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
3646                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3647   case Intrinsic::aarch64_sve_frinti:
3648     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3649                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3650   case Intrinsic::aarch64_sve_frintx:
3651     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3652                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3653   case Intrinsic::aarch64_sve_frinta:
3654     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
3655                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3656   case Intrinsic::aarch64_sve_frintn:
3657     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
3658                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3659   case Intrinsic::aarch64_sve_frintz:
3660     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
3661                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3662   case Intrinsic::aarch64_sve_ucvtf:
3663     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
3664                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3665                        Op.getOperand(1));
3666   case Intrinsic::aarch64_sve_scvtf:
3667     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
3668                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3669                        Op.getOperand(1));
3670   case Intrinsic::aarch64_sve_fcvtzu:
3671     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
3672                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3673                        Op.getOperand(1));
3674   case Intrinsic::aarch64_sve_fcvtzs:
3675     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
3676                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3677                        Op.getOperand(1));
3678   case Intrinsic::aarch64_sve_fsqrt:
3679     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
3680                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3681   case Intrinsic::aarch64_sve_frecpx:
3682     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
3683                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3684   case Intrinsic::aarch64_sve_fabs:
3685     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
3686                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3687   case Intrinsic::aarch64_sve_abs:
3688     return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
3689                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3690   case Intrinsic::aarch64_sve_neg:
3691     return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
3692                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3693   case Intrinsic::aarch64_sve_convert_to_svbool: {
3694     EVT OutVT = Op.getValueType();
3695     EVT InVT = Op.getOperand(1).getValueType();
3696     // Return the operand if the cast isn't changing type,
3697     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3698     if (InVT == OutVT)
3699       return Op.getOperand(1);
3700     // Otherwise, zero the newly introduced lanes.
3701     SDValue Reinterpret =
3702         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3703     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3704     SDValue MaskReinterpret =
3705         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3706     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3707   }
3708 
3709   case Intrinsic::aarch64_sve_insr: {
3710     SDValue Scalar = Op.getOperand(2);
3711     EVT ScalarTy = Scalar.getValueType();
3712     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3713       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3714 
3715     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3716                        Op.getOperand(1), Scalar);
3717   }
3718   case Intrinsic::aarch64_sve_rbit:
3719     return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
3720                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3721                        Op.getOperand(1));
3722   case Intrinsic::aarch64_sve_revb:
3723     return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
3724                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3725   case Intrinsic::aarch64_sve_sxtb:
3726     return DAG.getNode(
3727         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3728         Op.getOperand(2), Op.getOperand(3),
3729         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3730         Op.getOperand(1));
3731   case Intrinsic::aarch64_sve_sxth:
3732     return DAG.getNode(
3733         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3734         Op.getOperand(2), Op.getOperand(3),
3735         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3736         Op.getOperand(1));
3737   case Intrinsic::aarch64_sve_sxtw:
3738     return DAG.getNode(
3739         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3740         Op.getOperand(2), Op.getOperand(3),
3741         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3742         Op.getOperand(1));
3743   case Intrinsic::aarch64_sve_uxtb:
3744     return DAG.getNode(
3745         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3746         Op.getOperand(2), Op.getOperand(3),
3747         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3748         Op.getOperand(1));
3749   case Intrinsic::aarch64_sve_uxth:
3750     return DAG.getNode(
3751         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3752         Op.getOperand(2), Op.getOperand(3),
3753         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3754         Op.getOperand(1));
3755   case Intrinsic::aarch64_sve_uxtw:
3756     return DAG.getNode(
3757         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3758         Op.getOperand(2), Op.getOperand(3),
3759         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3760         Op.getOperand(1));
3761 
3762   case Intrinsic::localaddress: {
3763     const auto &MF = DAG.getMachineFunction();
3764     const auto *RegInfo = Subtarget->getRegisterInfo();
3765     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3766     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3767                               Op.getSimpleValueType());
3768   }
3769 
3770   case Intrinsic::eh_recoverfp: {
3771     // FIXME: This needs to be implemented to correctly handle highly aligned
3772     // stack objects. For now we simply return the incoming FP. Refer D53541
3773     // for more details.
3774     SDValue FnOp = Op.getOperand(1);
3775     SDValue IncomingFPOp = Op.getOperand(2);
3776     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3777     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3778     if (!Fn)
3779       report_fatal_error(
3780           "llvm.eh.recoverfp must take a function as the first argument");
3781     return IncomingFPOp;
3782   }
3783 
3784   case Intrinsic::aarch64_neon_vsri:
3785   case Intrinsic::aarch64_neon_vsli: {
3786     EVT Ty = Op.getValueType();
3787 
3788     if (!Ty.isVector())
3789       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3790 
3791     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3792 
3793     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3794     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3795     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3796                        Op.getOperand(3));
3797   }
3798 
3799   case Intrinsic::aarch64_neon_srhadd:
3800   case Intrinsic::aarch64_neon_urhadd:
3801   case Intrinsic::aarch64_neon_shadd:
3802   case Intrinsic::aarch64_neon_uhadd: {
3803     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3804                         IntNo == Intrinsic::aarch64_neon_shadd);
3805     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3806                           IntNo == Intrinsic::aarch64_neon_urhadd);
3807     unsigned Opcode =
3808         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
3809                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
3810     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3811                        Op.getOperand(2));
3812   }
3813 
3814   case Intrinsic::aarch64_neon_uabd: {
3815     return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(),
3816                        Op.getOperand(1), Op.getOperand(2));
3817   }
3818   case Intrinsic::aarch64_neon_sabd: {
3819     return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(),
3820                        Op.getOperand(1), Op.getOperand(2));
3821   }
3822   }
3823 }
3824 
3825 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
3826   if (VT.getVectorElementType() == MVT::i8 ||
3827       VT.getVectorElementType() == MVT::i16) {
3828     EltTy = MVT::i32;
3829     return true;
3830   }
3831   return false;
3832 }
3833 
3834 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
3835   if (VT.getVectorElementType() == MVT::i32 &&
3836       VT.getVectorElementCount().getKnownMinValue() >= 4)
3837     return true;
3838 
3839   return false;
3840 }
3841 
3842 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3843   return ExtVal.getValueType().isScalableVector();
3844 }
3845 
3846 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
3847   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
3848       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
3849        AArch64ISD::GLD1_MERGE_ZERO},
3850       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
3851        AArch64ISD::GLD1_UXTW_MERGE_ZERO},
3852       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
3853        AArch64ISD::GLD1_MERGE_ZERO},
3854       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
3855        AArch64ISD::GLD1_SXTW_MERGE_ZERO},
3856       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
3857        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
3858       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
3859        AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
3860       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
3861        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
3862       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
3863        AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
3864   };
3865   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
3866   return AddrModes.find(Key)->second;
3867 }
3868 
3869 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
3870   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
3871       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
3872        AArch64ISD::SST1_PRED},
3873       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
3874        AArch64ISD::SST1_UXTW_PRED},
3875       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
3876        AArch64ISD::SST1_PRED},
3877       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
3878        AArch64ISD::SST1_SXTW_PRED},
3879       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
3880        AArch64ISD::SST1_SCALED_PRED},
3881       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
3882        AArch64ISD::SST1_UXTW_SCALED_PRED},
3883       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
3884        AArch64ISD::SST1_SCALED_PRED},
3885       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
3886        AArch64ISD::SST1_SXTW_SCALED_PRED},
3887   };
3888   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
3889   return AddrModes.find(Key)->second;
3890 }
3891 
3892 unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
3893   switch (Opcode) {
3894   default:
3895     llvm_unreachable("unimplemented opcode");
3896     return Opcode;
3897   case AArch64ISD::GLD1_MERGE_ZERO:
3898     return AArch64ISD::GLD1S_MERGE_ZERO;
3899   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
3900     return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
3901   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
3902     return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
3903   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
3904     return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
3905   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
3906     return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
3907   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
3908     return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
3909   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
3910     return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
3911   }
3912 }
3913 
3914 bool getGatherScatterIndexIsExtended(SDValue Index) {
3915   unsigned Opcode = Index.getOpcode();
3916   if (Opcode == ISD::SIGN_EXTEND_INREG)
3917     return true;
3918 
3919   if (Opcode == ISD::AND) {
3920     SDValue Splat = Index.getOperand(1);
3921     if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
3922       return false;
3923     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
3924     if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
3925       return false;
3926     return true;
3927   }
3928 
3929   return false;
3930 }
3931 
3932 // If the base pointer of a masked gather or scatter is null, we
3933 // may be able to swap BasePtr & Index and use the vector + register
3934 // or vector + immediate addressing mode, e.g.
3935 // VECTOR + REGISTER:
3936 //    getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
3937 // -> getelementptr %offset, <vscale x N x T> %indices
3938 // VECTOR + IMMEDIATE:
3939 //    getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
3940 // -> getelementptr #x, <vscale x N x T> %indices
3941 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
3942                                  unsigned &Opcode, bool IsGather,
3943                                  SelectionDAG &DAG) {
3944   if (!isNullConstant(BasePtr))
3945     return;
3946 
3947   ConstantSDNode *Offset = nullptr;
3948   if (Index.getOpcode() == ISD::ADD)
3949     if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
3950       if (isa<ConstantSDNode>(SplatVal))
3951         Offset = cast<ConstantSDNode>(SplatVal);
3952       else {
3953         BasePtr = SplatVal;
3954         Index = Index->getOperand(0);
3955         return;
3956       }
3957     }
3958 
3959   unsigned NewOp =
3960       IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
3961 
3962   if (!Offset) {
3963     std::swap(BasePtr, Index);
3964     Opcode = NewOp;
3965     return;
3966   }
3967 
3968   uint64_t OffsetVal = Offset->getZExtValue();
3969   unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
3970   auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
3971 
3972   if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
3973     // Index is out of range for the immediate addressing mode
3974     BasePtr = ConstOffset;
3975     Index = Index->getOperand(0);
3976     return;
3977   }
3978 
3979   // Immediate is in range
3980   Opcode = NewOp;
3981   BasePtr = Index->getOperand(0);
3982   Index = ConstOffset;
3983 }
3984 
3985 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
3986                                             SelectionDAG &DAG) const {
3987   SDLoc DL(Op);
3988   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
3989   assert(MGT && "Can only custom lower gather load nodes");
3990 
3991   SDValue Index = MGT->getIndex();
3992   SDValue Chain = MGT->getChain();
3993   SDValue PassThru = MGT->getPassThru();
3994   SDValue Mask = MGT->getMask();
3995   SDValue BasePtr = MGT->getBasePtr();
3996   ISD::LoadExtType ExtTy = MGT->getExtensionType();
3997 
3998   ISD::MemIndexType IndexType = MGT->getIndexType();
3999   bool IsScaled =
4000       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4001   bool IsSigned =
4002       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4003   bool IdxNeedsExtend =
4004       getGatherScatterIndexIsExtended(Index) ||
4005       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4006   bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
4007 
4008   EVT VT = PassThru.getSimpleValueType();
4009   EVT MemVT = MGT->getMemoryVT();
4010   SDValue InputVT = DAG.getValueType(MemVT);
4011 
4012   if (VT.getVectorElementType() == MVT::bf16 &&
4013       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4014     return SDValue();
4015 
4016   // Handle FP data by using an integer gather and casting the result.
4017   if (VT.isFloatingPoint()) {
4018     EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4019     PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
4020     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4021   }
4022 
4023   SDVTList VTs = DAG.getVTList(PassThru.getSimpleValueType(), MVT::Other);
4024 
4025   if (getGatherScatterIndexIsExtended(Index))
4026     Index = Index.getOperand(0);
4027 
4028   unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
4029   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4030                               /*isGather=*/true, DAG);
4031 
4032   if (ResNeedsSignExtend)
4033     Opcode = getSignExtendedGatherOpcode(Opcode);
4034 
4035   SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT, PassThru};
4036   SDValue Gather = DAG.getNode(Opcode, DL, VTs, Ops);
4037 
4038   if (VT.isFloatingPoint()) {
4039     SDValue Cast = getSVESafeBitCast(VT, Gather, DAG);
4040     return DAG.getMergeValues({Cast, Gather}, DL);
4041   }
4042 
4043   return Gather;
4044 }
4045 
4046 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
4047                                              SelectionDAG &DAG) const {
4048   SDLoc DL(Op);
4049   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
4050   assert(MSC && "Can only custom lower scatter store nodes");
4051 
4052   SDValue Index = MSC->getIndex();
4053   SDValue Chain = MSC->getChain();
4054   SDValue StoreVal = MSC->getValue();
4055   SDValue Mask = MSC->getMask();
4056   SDValue BasePtr = MSC->getBasePtr();
4057 
4058   ISD::MemIndexType IndexType = MSC->getIndexType();
4059   bool IsScaled =
4060       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4061   bool IsSigned =
4062       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4063   bool NeedsExtend =
4064       getGatherScatterIndexIsExtended(Index) ||
4065       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4066 
4067   EVT VT = StoreVal.getSimpleValueType();
4068   SDVTList VTs = DAG.getVTList(MVT::Other);
4069   EVT MemVT = MSC->getMemoryVT();
4070   SDValue InputVT = DAG.getValueType(MemVT);
4071 
4072   if (VT.getVectorElementType() == MVT::bf16 &&
4073       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4074     return SDValue();
4075 
4076   // Handle FP data by casting the data so an integer scatter can be used.
4077   if (VT.isFloatingPoint()) {
4078     EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4079     StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
4080     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4081   }
4082 
4083   if (getGatherScatterIndexIsExtended(Index))
4084     Index = Index.getOperand(0);
4085 
4086   unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
4087   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4088                               /*isGather=*/false, DAG);
4089 
4090   SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
4091   return DAG.getNode(Opcode, DL, VTs, Ops);
4092 }
4093 
4094 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
4095 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
4096                                         EVT VT, EVT MemVT,
4097                                         SelectionDAG &DAG) {
4098   assert(VT.isVector() && "VT should be a vector type");
4099   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
4100 
4101   SDValue Value = ST->getValue();
4102 
4103   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
4104   // the word lane which represent the v4i8 subvector.  It optimizes the store
4105   // to:
4106   //
4107   //   xtn  v0.8b, v0.8h
4108   //   str  s0, [x0]
4109 
4110   SDValue Undef = DAG.getUNDEF(MVT::i16);
4111   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
4112                                         {Undef, Undef, Undef, Undef});
4113 
4114   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
4115                                  Value, UndefVec);
4116   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
4117 
4118   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
4119   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
4120                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
4121 
4122   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
4123                       ST->getBasePtr(), ST->getMemOperand());
4124 }
4125 
4126 // Custom lowering for any store, vector or scalar and/or default or with
4127 // a truncate operations.  Currently only custom lower truncate operation
4128 // from vector v4i16 to v4i8 or volatile stores of i128.
4129 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
4130                                           SelectionDAG &DAG) const {
4131   SDLoc Dl(Op);
4132   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
4133   assert (StoreNode && "Can only custom lower store nodes");
4134 
4135   SDValue Value = StoreNode->getValue();
4136 
4137   EVT VT = Value.getValueType();
4138   EVT MemVT = StoreNode->getMemoryVT();
4139 
4140   if (VT.isVector()) {
4141     if (useSVEForFixedLengthVectorVT(VT))
4142       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
4143 
4144     unsigned AS = StoreNode->getAddressSpace();
4145     Align Alignment = StoreNode->getAlign();
4146     if (Alignment < MemVT.getStoreSize() &&
4147         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
4148                                         StoreNode->getMemOperand()->getFlags(),
4149                                         nullptr)) {
4150       return scalarizeVectorStore(StoreNode, DAG);
4151     }
4152 
4153     if (StoreNode->isTruncatingStore()) {
4154       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
4155     }
4156     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
4157     // the custom lowering, as there are no un-paired non-temporal stores and
4158     // legalization will break up 256 bit inputs.
4159     ElementCount EC = MemVT.getVectorElementCount();
4160     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
4161         EC.isKnownEven() &&
4162         ((MemVT.getScalarSizeInBits() == 8u ||
4163           MemVT.getScalarSizeInBits() == 16u ||
4164           MemVT.getScalarSizeInBits() == 32u ||
4165           MemVT.getScalarSizeInBits() == 64u))) {
4166       SDValue Lo =
4167           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4168                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4169                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
4170       SDValue Hi =
4171           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4172                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4173                       StoreNode->getValue(),
4174                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
4175       SDValue Result = DAG.getMemIntrinsicNode(
4176           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
4177           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4178           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4179       return Result;
4180     }
4181   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
4182     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
4183     SDValue Lo =
4184         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
4185                     DAG.getConstant(0, Dl, MVT::i64));
4186     SDValue Hi =
4187         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
4188                     DAG.getConstant(1, Dl, MVT::i64));
4189     SDValue Result = DAG.getMemIntrinsicNode(
4190         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
4191         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4192         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4193     return Result;
4194   }
4195 
4196   return SDValue();
4197 }
4198 
4199 // Generate SUBS and CSEL for integer abs.
4200 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
4201   MVT VT = Op.getSimpleValueType();
4202 
4203   if (VT.isVector())
4204     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
4205 
4206   SDLoc DL(Op);
4207   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4208                             Op.getOperand(0));
4209   // Generate SUBS & CSEL.
4210   SDValue Cmp =
4211       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
4212                   Op.getOperand(0), DAG.getConstant(0, DL, VT));
4213   return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
4214                      DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
4215                      Cmp.getValue(1));
4216 }
4217 
4218 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
4219                                               SelectionDAG &DAG) const {
4220   LLVM_DEBUG(dbgs() << "Custom lowering: ");
4221   LLVM_DEBUG(Op.dump());
4222 
4223   switch (Op.getOpcode()) {
4224   default:
4225     llvm_unreachable("unimplemented operand");
4226     return SDValue();
4227   case ISD::BITCAST:
4228     return LowerBITCAST(Op, DAG);
4229   case ISD::GlobalAddress:
4230     return LowerGlobalAddress(Op, DAG);
4231   case ISD::GlobalTLSAddress:
4232     return LowerGlobalTLSAddress(Op, DAG);
4233   case ISD::SETCC:
4234   case ISD::STRICT_FSETCC:
4235   case ISD::STRICT_FSETCCS:
4236     return LowerSETCC(Op, DAG);
4237   case ISD::BR_CC:
4238     return LowerBR_CC(Op, DAG);
4239   case ISD::SELECT:
4240     return LowerSELECT(Op, DAG);
4241   case ISD::SELECT_CC:
4242     return LowerSELECT_CC(Op, DAG);
4243   case ISD::JumpTable:
4244     return LowerJumpTable(Op, DAG);
4245   case ISD::BR_JT:
4246     return LowerBR_JT(Op, DAG);
4247   case ISD::ConstantPool:
4248     return LowerConstantPool(Op, DAG);
4249   case ISD::BlockAddress:
4250     return LowerBlockAddress(Op, DAG);
4251   case ISD::VASTART:
4252     return LowerVASTART(Op, DAG);
4253   case ISD::VACOPY:
4254     return LowerVACOPY(Op, DAG);
4255   case ISD::VAARG:
4256     return LowerVAARG(Op, DAG);
4257   case ISD::ADDC:
4258   case ISD::ADDE:
4259   case ISD::SUBC:
4260   case ISD::SUBE:
4261     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
4262   case ISD::SADDO:
4263   case ISD::UADDO:
4264   case ISD::SSUBO:
4265   case ISD::USUBO:
4266   case ISD::SMULO:
4267   case ISD::UMULO:
4268     return LowerXALUO(Op, DAG);
4269   case ISD::FADD:
4270     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
4271   case ISD::FSUB:
4272     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
4273   case ISD::FMUL:
4274     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
4275   case ISD::FMA:
4276     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
4277   case ISD::FDIV:
4278     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
4279   case ISD::FNEG:
4280     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
4281   case ISD::FCEIL:
4282     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
4283   case ISD::FFLOOR:
4284     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
4285   case ISD::FNEARBYINT:
4286     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
4287   case ISD::FRINT:
4288     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
4289   case ISD::FROUND:
4290     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
4291   case ISD::FROUNDEVEN:
4292     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
4293   case ISD::FTRUNC:
4294     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
4295   case ISD::FSQRT:
4296     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
4297   case ISD::FABS:
4298     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
4299   case ISD::FP_ROUND:
4300   case ISD::STRICT_FP_ROUND:
4301     return LowerFP_ROUND(Op, DAG);
4302   case ISD::FP_EXTEND:
4303     return LowerFP_EXTEND(Op, DAG);
4304   case ISD::FRAMEADDR:
4305     return LowerFRAMEADDR(Op, DAG);
4306   case ISD::SPONENTRY:
4307     return LowerSPONENTRY(Op, DAG);
4308   case ISD::RETURNADDR:
4309     return LowerRETURNADDR(Op, DAG);
4310   case ISD::ADDROFRETURNADDR:
4311     return LowerADDROFRETURNADDR(Op, DAG);
4312   case ISD::CONCAT_VECTORS:
4313     return LowerCONCAT_VECTORS(Op, DAG);
4314   case ISD::INSERT_VECTOR_ELT:
4315     return LowerINSERT_VECTOR_ELT(Op, DAG);
4316   case ISD::EXTRACT_VECTOR_ELT:
4317     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4318   case ISD::BUILD_VECTOR:
4319     return LowerBUILD_VECTOR(Op, DAG);
4320   case ISD::VECTOR_SHUFFLE:
4321     return LowerVECTOR_SHUFFLE(Op, DAG);
4322   case ISD::SPLAT_VECTOR:
4323     return LowerSPLAT_VECTOR(Op, DAG);
4324   case ISD::EXTRACT_SUBVECTOR:
4325     return LowerEXTRACT_SUBVECTOR(Op, DAG);
4326   case ISD::INSERT_SUBVECTOR:
4327     return LowerINSERT_SUBVECTOR(Op, DAG);
4328   case ISD::SDIV:
4329   case ISD::UDIV:
4330     return LowerDIV(Op, DAG);
4331   case ISD::SMIN:
4332     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
4333                                /*OverrideNEON=*/true);
4334   case ISD::UMIN:
4335     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
4336                                /*OverrideNEON=*/true);
4337   case ISD::SMAX:
4338     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
4339                                /*OverrideNEON=*/true);
4340   case ISD::UMAX:
4341     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
4342                                /*OverrideNEON=*/true);
4343   case ISD::SRA:
4344   case ISD::SRL:
4345   case ISD::SHL:
4346     return LowerVectorSRA_SRL_SHL(Op, DAG);
4347   case ISD::SHL_PARTS:
4348     return LowerShiftLeftParts(Op, DAG);
4349   case ISD::SRL_PARTS:
4350   case ISD::SRA_PARTS:
4351     return LowerShiftRightParts(Op, DAG);
4352   case ISD::CTPOP:
4353     return LowerCTPOP(Op, DAG);
4354   case ISD::FCOPYSIGN:
4355     return LowerFCOPYSIGN(Op, DAG);
4356   case ISD::OR:
4357     return LowerVectorOR(Op, DAG);
4358   case ISD::XOR:
4359     return LowerXOR(Op, DAG);
4360   case ISD::PREFETCH:
4361     return LowerPREFETCH(Op, DAG);
4362   case ISD::SINT_TO_FP:
4363   case ISD::UINT_TO_FP:
4364   case ISD::STRICT_SINT_TO_FP:
4365   case ISD::STRICT_UINT_TO_FP:
4366     return LowerINT_TO_FP(Op, DAG);
4367   case ISD::FP_TO_SINT:
4368   case ISD::FP_TO_UINT:
4369   case ISD::STRICT_FP_TO_SINT:
4370   case ISD::STRICT_FP_TO_UINT:
4371     return LowerFP_TO_INT(Op, DAG);
4372   case ISD::FSINCOS:
4373     return LowerFSINCOS(Op, DAG);
4374   case ISD::FLT_ROUNDS_:
4375     return LowerFLT_ROUNDS_(Op, DAG);
4376   case ISD::MUL:
4377     return LowerMUL(Op, DAG);
4378   case ISD::INTRINSIC_WO_CHAIN:
4379     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4380   case ISD::STORE:
4381     return LowerSTORE(Op, DAG);
4382   case ISD::MGATHER:
4383     return LowerMGATHER(Op, DAG);
4384   case ISD::MSCATTER:
4385     return LowerMSCATTER(Op, DAG);
4386   case ISD::VECREDUCE_SEQ_FADD:
4387     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
4388   case ISD::VECREDUCE_ADD:
4389   case ISD::VECREDUCE_AND:
4390   case ISD::VECREDUCE_OR:
4391   case ISD::VECREDUCE_XOR:
4392   case ISD::VECREDUCE_SMAX:
4393   case ISD::VECREDUCE_SMIN:
4394   case ISD::VECREDUCE_UMAX:
4395   case ISD::VECREDUCE_UMIN:
4396   case ISD::VECREDUCE_FADD:
4397   case ISD::VECREDUCE_FMAX:
4398   case ISD::VECREDUCE_FMIN:
4399     return LowerVECREDUCE(Op, DAG);
4400   case ISD::ATOMIC_LOAD_SUB:
4401     return LowerATOMIC_LOAD_SUB(Op, DAG);
4402   case ISD::ATOMIC_LOAD_AND:
4403     return LowerATOMIC_LOAD_AND(Op, DAG);
4404   case ISD::DYNAMIC_STACKALLOC:
4405     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4406   case ISD::VSCALE:
4407     return LowerVSCALE(Op, DAG);
4408   case ISD::ANY_EXTEND:
4409   case ISD::SIGN_EXTEND:
4410   case ISD::ZERO_EXTEND:
4411     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
4412   case ISD::SIGN_EXTEND_INREG: {
4413     // Only custom lower when ExtraVT has a legal byte based element type.
4414     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4415     EVT ExtraEltVT = ExtraVT.getVectorElementType();
4416     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
4417         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
4418       return SDValue();
4419 
4420     return LowerToPredicatedOp(Op, DAG,
4421                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
4422   }
4423   case ISD::TRUNCATE:
4424     return LowerTRUNCATE(Op, DAG);
4425   case ISD::LOAD:
4426     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
4427       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
4428     llvm_unreachable("Unexpected request to lower ISD::LOAD");
4429   case ISD::ADD:
4430     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
4431   case ISD::AND:
4432     return LowerToScalableOp(Op, DAG);
4433   case ISD::SUB:
4434     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
4435   case ISD::FMAXNUM:
4436     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
4437   case ISD::FMINNUM:
4438     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
4439   case ISD::VSELECT:
4440     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
4441   case ISD::ABS:
4442     return LowerABS(Op, DAG);
4443   case ISD::BITREVERSE:
4444     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
4445                                /*OverrideNEON=*/true);
4446   case ISD::BSWAP:
4447     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
4448   case ISD::CTLZ:
4449     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
4450                                /*OverrideNEON=*/true);
4451   case ISD::CTTZ:
4452     return LowerCTTZ(Op, DAG);
4453   }
4454 }
4455 
4456 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
4457   return !Subtarget->useSVEForFixedLengthVectors();
4458 }
4459 
4460 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
4461     EVT VT, bool OverrideNEON) const {
4462   if (!Subtarget->useSVEForFixedLengthVectors())
4463     return false;
4464 
4465   if (!VT.isFixedLengthVector())
4466     return false;
4467 
4468   // Don't use SVE for vectors we cannot scalarize if required.
4469   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
4470   // Fixed length predicates should be promoted to i8.
4471   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
4472   case MVT::i1:
4473   default:
4474     return false;
4475   case MVT::i8:
4476   case MVT::i16:
4477   case MVT::i32:
4478   case MVT::i64:
4479   case MVT::f16:
4480   case MVT::f32:
4481   case MVT::f64:
4482     break;
4483   }
4484 
4485   // All SVE implementations support NEON sized vectors.
4486   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
4487     return true;
4488 
4489   // Ensure NEON MVTs only belong to a single register class.
4490   if (VT.getFixedSizeInBits() <= 128)
4491     return false;
4492 
4493   // Don't use SVE for types that don't fit.
4494   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
4495     return false;
4496 
4497   // TODO: Perhaps an artificial restriction, but worth having whilst getting
4498   // the base fixed length SVE support in place.
4499   if (!VT.isPow2VectorType())
4500     return false;
4501 
4502   return true;
4503 }
4504 
4505 //===----------------------------------------------------------------------===//
4506 //                      Calling Convention Implementation
4507 //===----------------------------------------------------------------------===//
4508 
4509 /// Selects the correct CCAssignFn for a given CallingConvention value.
4510 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
4511                                                      bool IsVarArg) const {
4512   switch (CC) {
4513   default:
4514     report_fatal_error("Unsupported calling convention.");
4515   case CallingConv::WebKit_JS:
4516     return CC_AArch64_WebKit_JS;
4517   case CallingConv::GHC:
4518     return CC_AArch64_GHC;
4519   case CallingConv::C:
4520   case CallingConv::Fast:
4521   case CallingConv::PreserveMost:
4522   case CallingConv::CXX_FAST_TLS:
4523   case CallingConv::Swift:
4524     if (Subtarget->isTargetWindows() && IsVarArg)
4525       return CC_AArch64_Win64_VarArg;
4526     if (!Subtarget->isTargetDarwin())
4527       return CC_AArch64_AAPCS;
4528     if (!IsVarArg)
4529       return CC_AArch64_DarwinPCS;
4530     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
4531                                       : CC_AArch64_DarwinPCS_VarArg;
4532    case CallingConv::Win64:
4533     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
4534    case CallingConv::CFGuard_Check:
4535      return CC_AArch64_Win64_CFGuard_Check;
4536    case CallingConv::AArch64_VectorCall:
4537    case CallingConv::AArch64_SVE_VectorCall:
4538      return CC_AArch64_AAPCS;
4539   }
4540 }
4541 
4542 CCAssignFn *
4543 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
4544   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
4545                                       : RetCC_AArch64_AAPCS;
4546 }
4547 
4548 SDValue AArch64TargetLowering::LowerFormalArguments(
4549     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4550     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4551     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4552   MachineFunction &MF = DAG.getMachineFunction();
4553   MachineFrameInfo &MFI = MF.getFrameInfo();
4554   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4555 
4556   // Assign locations to all of the incoming arguments.
4557   SmallVector<CCValAssign, 16> ArgLocs;
4558   DenseMap<unsigned, SDValue> CopiedRegs;
4559   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4560                  *DAG.getContext());
4561 
4562   // At this point, Ins[].VT may already be promoted to i32. To correctly
4563   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4564   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4565   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
4566   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
4567   // LocVT.
4568   unsigned NumArgs = Ins.size();
4569   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4570   unsigned CurArgIdx = 0;
4571   for (unsigned i = 0; i != NumArgs; ++i) {
4572     MVT ValVT = Ins[i].VT;
4573     if (Ins[i].isOrigArg()) {
4574       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
4575       CurArgIdx = Ins[i].getOrigArgIndex();
4576 
4577       // Get type of the original argument.
4578       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
4579                                   /*AllowUnknown*/ true);
4580       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
4581       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4582       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4583         ValVT = MVT::i8;
4584       else if (ActualMVT == MVT::i16)
4585         ValVT = MVT::i16;
4586     }
4587     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4588     bool Res =
4589         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
4590     assert(!Res && "Call operand has unhandled type");
4591     (void)Res;
4592   }
4593   SmallVector<SDValue, 16> ArgValues;
4594   unsigned ExtraArgLocs = 0;
4595   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4596     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
4597 
4598     if (Ins[i].Flags.isByVal()) {
4599       // Byval is used for HFAs in the PCS, but the system should work in a
4600       // non-compliant manner for larger structs.
4601       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4602       int Size = Ins[i].Flags.getByValSize();
4603       unsigned NumRegs = (Size + 7) / 8;
4604 
4605       // FIXME: This works on big-endian for composite byvals, which are the common
4606       // case. It should also work for fundamental types too.
4607       unsigned FrameIdx =
4608         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
4609       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
4610       InVals.push_back(FrameIdxN);
4611 
4612       continue;
4613     }
4614 
4615     SDValue ArgValue;
4616     if (VA.isRegLoc()) {
4617       // Arguments stored in registers.
4618       EVT RegVT = VA.getLocVT();
4619       const TargetRegisterClass *RC;
4620 
4621       if (RegVT == MVT::i32)
4622         RC = &AArch64::GPR32RegClass;
4623       else if (RegVT == MVT::i64)
4624         RC = &AArch64::GPR64RegClass;
4625       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4626         RC = &AArch64::FPR16RegClass;
4627       else if (RegVT == MVT::f32)
4628         RC = &AArch64::FPR32RegClass;
4629       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
4630         RC = &AArch64::FPR64RegClass;
4631       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
4632         RC = &AArch64::FPR128RegClass;
4633       else if (RegVT.isScalableVector() &&
4634                RegVT.getVectorElementType() == MVT::i1)
4635         RC = &AArch64::PPRRegClass;
4636       else if (RegVT.isScalableVector())
4637         RC = &AArch64::ZPRRegClass;
4638       else
4639         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4640 
4641       // Transform the arguments in physical registers into virtual ones.
4642       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4643       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
4644 
4645       // If this is an 8, 16 or 32-bit value, it is really passed promoted
4646       // to 64 bits.  Insert an assert[sz]ext to capture this, then
4647       // truncate to the right size.
4648       switch (VA.getLocInfo()) {
4649       default:
4650         llvm_unreachable("Unknown loc info!");
4651       case CCValAssign::Full:
4652         break;
4653       case CCValAssign::Indirect:
4654         assert(VA.getValVT().isScalableVector() &&
4655                "Only scalable vectors can be passed indirectly");
4656         break;
4657       case CCValAssign::BCvt:
4658         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
4659         break;
4660       case CCValAssign::AExt:
4661       case CCValAssign::SExt:
4662       case CCValAssign::ZExt:
4663         break;
4664       case CCValAssign::AExtUpper:
4665         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
4666                                DAG.getConstant(32, DL, RegVT));
4667         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
4668         break;
4669       }
4670     } else { // VA.isRegLoc()
4671       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
4672       unsigned ArgOffset = VA.getLocMemOffset();
4673       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
4674                               ? VA.getLocVT().getSizeInBits()
4675                               : VA.getValVT().getSizeInBits()) / 8;
4676 
4677       uint32_t BEAlign = 0;
4678       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
4679           !Ins[i].Flags.isInConsecutiveRegs())
4680         BEAlign = 8 - ArgSize;
4681 
4682       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
4683 
4684       // Create load nodes to retrieve arguments from the stack.
4685       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4686 
4687       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
4688       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4689       MVT MemVT = VA.getValVT();
4690 
4691       switch (VA.getLocInfo()) {
4692       default:
4693         break;
4694       case CCValAssign::Trunc:
4695       case CCValAssign::BCvt:
4696         MemVT = VA.getLocVT();
4697         break;
4698       case CCValAssign::Indirect:
4699         assert(VA.getValVT().isScalableVector() &&
4700                "Only scalable vectors can be passed indirectly");
4701         MemVT = VA.getLocVT();
4702         break;
4703       case CCValAssign::SExt:
4704         ExtType = ISD::SEXTLOAD;
4705         break;
4706       case CCValAssign::ZExt:
4707         ExtType = ISD::ZEXTLOAD;
4708         break;
4709       case CCValAssign::AExt:
4710         ExtType = ISD::EXTLOAD;
4711         break;
4712       }
4713 
4714       ArgValue = DAG.getExtLoad(
4715           ExtType, DL, VA.getLocVT(), Chain, FIN,
4716           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
4717           MemVT);
4718 
4719     }
4720 
4721     if (VA.getLocInfo() == CCValAssign::Indirect) {
4722       assert(VA.getValVT().isScalableVector() &&
4723            "Only scalable vectors can be passed indirectly");
4724 
4725       uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
4726       unsigned NumParts = 1;
4727       if (Ins[i].Flags.isInConsecutiveRegs()) {
4728         assert(!Ins[i].Flags.isInConsecutiveRegsLast());
4729         while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
4730           ++NumParts;
4731       }
4732 
4733       MVT PartLoad = VA.getValVT();
4734       SDValue Ptr = ArgValue;
4735 
4736       // Ensure we generate all loads for each tuple part, whilst updating the
4737       // pointer after each load correctly using vscale.
4738       while (NumParts > 0) {
4739         ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
4740         InVals.push_back(ArgValue);
4741         NumParts--;
4742         if (NumParts > 0) {
4743           SDValue BytesIncrement = DAG.getVScale(
4744               DL, Ptr.getValueType(),
4745               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
4746           SDNodeFlags Flags;
4747           Flags.setNoUnsignedWrap(true);
4748           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4749                             BytesIncrement, Flags);
4750           ExtraArgLocs++;
4751           i++;
4752         }
4753       }
4754     } else {
4755       if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
4756         ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
4757                                ArgValue, DAG.getValueType(MVT::i32));
4758       InVals.push_back(ArgValue);
4759     }
4760   }
4761   assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
4762 
4763   // varargs
4764   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4765   if (isVarArg) {
4766     if (!Subtarget->isTargetDarwin() || IsWin64) {
4767       // The AAPCS variadic function ABI is identical to the non-variadic
4768       // one. As a result there may be more arguments in registers and we should
4769       // save them for future reference.
4770       // Win64 variadic functions also pass arguments in registers, but all float
4771       // arguments are passed in integer registers.
4772       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
4773     }
4774 
4775     // This will point to the next argument passed via stack.
4776     unsigned StackOffset = CCInfo.getNextStackOffset();
4777     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
4778     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
4779     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
4780 
4781     if (MFI.hasMustTailInVarArgFunc()) {
4782       SmallVector<MVT, 2> RegParmTypes;
4783       RegParmTypes.push_back(MVT::i64);
4784       RegParmTypes.push_back(MVT::f128);
4785       // Compute the set of forwarded registers. The rest are scratch.
4786       SmallVectorImpl<ForwardedRegister> &Forwards =
4787                                        FuncInfo->getForwardedMustTailRegParms();
4788       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
4789                                                CC_AArch64_AAPCS);
4790 
4791       // Conservatively forward X8, since it might be used for aggregate return.
4792       if (!CCInfo.isAllocated(AArch64::X8)) {
4793         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
4794         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
4795       }
4796     }
4797   }
4798 
4799   // On Windows, InReg pointers must be returned, so record the pointer in a
4800   // virtual register at the start of the function so it can be returned in the
4801   // epilogue.
4802   if (IsWin64) {
4803     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4804       if (Ins[I].Flags.isInReg()) {
4805         assert(!FuncInfo->getSRetReturnReg());
4806 
4807         MVT PtrTy = getPointerTy(DAG.getDataLayout());
4808         Register Reg =
4809             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4810         FuncInfo->setSRetReturnReg(Reg);
4811 
4812         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
4813         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4814         break;
4815       }
4816     }
4817   }
4818 
4819   unsigned StackArgSize = CCInfo.getNextStackOffset();
4820   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4821   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
4822     // This is a non-standard ABI so by fiat I say we're allowed to make full
4823     // use of the stack area to be popped, which must be aligned to 16 bytes in
4824     // any case:
4825     StackArgSize = alignTo(StackArgSize, 16);
4826 
4827     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
4828     // a multiple of 16.
4829     FuncInfo->setArgumentStackToRestore(StackArgSize);
4830 
4831     // This realignment carries over to the available bytes below. Our own
4832     // callers will guarantee the space is free by giving an aligned value to
4833     // CALLSEQ_START.
4834   }
4835   // Even if we're not expected to free up the space, it's useful to know how
4836   // much is there while considering tail calls (because we can reuse it).
4837   FuncInfo->setBytesInStackArgArea(StackArgSize);
4838 
4839   if (Subtarget->hasCustomCallingConv())
4840     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
4841 
4842   return Chain;
4843 }
4844 
4845 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
4846                                                 SelectionDAG &DAG,
4847                                                 const SDLoc &DL,
4848                                                 SDValue &Chain) const {
4849   MachineFunction &MF = DAG.getMachineFunction();
4850   MachineFrameInfo &MFI = MF.getFrameInfo();
4851   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4852   auto PtrVT = getPointerTy(DAG.getDataLayout());
4853   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4854 
4855   SmallVector<SDValue, 8> MemOps;
4856 
4857   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
4858                                           AArch64::X3, AArch64::X4, AArch64::X5,
4859                                           AArch64::X6, AArch64::X7 };
4860   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
4861   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
4862 
4863   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
4864   int GPRIdx = 0;
4865   if (GPRSaveSize != 0) {
4866     if (IsWin64) {
4867       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
4868       if (GPRSaveSize & 15)
4869         // The extra size here, if triggered, will always be 8.
4870         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
4871     } else
4872       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
4873 
4874     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
4875 
4876     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
4877       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
4878       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
4879       SDValue Store = DAG.getStore(
4880           Val.getValue(1), DL, Val, FIN,
4881           IsWin64
4882               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
4883                                                   GPRIdx,
4884                                                   (i - FirstVariadicGPR) * 8)
4885               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
4886       MemOps.push_back(Store);
4887       FIN =
4888           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
4889     }
4890   }
4891   FuncInfo->setVarArgsGPRIndex(GPRIdx);
4892   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4893 
4894   if (Subtarget->hasFPARMv8() && !IsWin64) {
4895     static const MCPhysReg FPRArgRegs[] = {
4896         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4897         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4898     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4899     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4900 
4901     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4902     int FPRIdx = 0;
4903     if (FPRSaveSize != 0) {
4904       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4905 
4906       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4907 
4908       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4909         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4910         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4911 
4912         SDValue Store = DAG.getStore(
4913             Val.getValue(1), DL, Val, FIN,
4914             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4915         MemOps.push_back(Store);
4916         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4917                           DAG.getConstant(16, DL, PtrVT));
4918       }
4919     }
4920     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4921     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4922   }
4923 
4924   if (!MemOps.empty()) {
4925     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4926   }
4927 }
4928 
4929 /// LowerCallResult - Lower the result values of a call into the
4930 /// appropriate copies out of appropriate physical registers.
4931 SDValue AArch64TargetLowering::LowerCallResult(
4932     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4933     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4934     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4935     SDValue ThisVal) const {
4936   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
4937   // Assign locations to each value returned by this call.
4938   SmallVector<CCValAssign, 16> RVLocs;
4939   DenseMap<unsigned, SDValue> CopiedRegs;
4940   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4941                  *DAG.getContext());
4942   CCInfo.AnalyzeCallResult(Ins, RetCC);
4943 
4944   // Copy all of the result registers out of their specified physreg.
4945   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4946     CCValAssign VA = RVLocs[i];
4947 
4948     // Pass 'this' value directly from the argument to return value, to avoid
4949     // reg unit interference
4950     if (i == 0 && isThisReturn) {
4951       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4952              "unexpected return calling convention register assignment");
4953       InVals.push_back(ThisVal);
4954       continue;
4955     }
4956 
4957     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4958     // allows one use of a physreg per block.
4959     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4960     if (!Val) {
4961       Val =
4962           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4963       Chain = Val.getValue(1);
4964       InFlag = Val.getValue(2);
4965       CopiedRegs[VA.getLocReg()] = Val;
4966     }
4967 
4968     switch (VA.getLocInfo()) {
4969     default:
4970       llvm_unreachable("Unknown loc info!");
4971     case CCValAssign::Full:
4972       break;
4973     case CCValAssign::BCvt:
4974       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4975       break;
4976     case CCValAssign::AExtUpper:
4977       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4978                         DAG.getConstant(32, DL, VA.getLocVT()));
4979       LLVM_FALLTHROUGH;
4980     case CCValAssign::AExt:
4981       LLVM_FALLTHROUGH;
4982     case CCValAssign::ZExt:
4983       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4984       break;
4985     }
4986 
4987     InVals.push_back(Val);
4988   }
4989 
4990   return Chain;
4991 }
4992 
4993 /// Return true if the calling convention is one that we can guarantee TCO for.
4994 static bool canGuaranteeTCO(CallingConv::ID CC) {
4995   return CC == CallingConv::Fast;
4996 }
4997 
4998 /// Return true if we might ever do TCO for calls with this calling convention.
4999 static bool mayTailCallThisCC(CallingConv::ID CC) {
5000   switch (CC) {
5001   case CallingConv::C:
5002   case CallingConv::AArch64_SVE_VectorCall:
5003   case CallingConv::PreserveMost:
5004   case CallingConv::Swift:
5005     return true;
5006   default:
5007     return canGuaranteeTCO(CC);
5008   }
5009 }
5010 
5011 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
5012     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
5013     const SmallVectorImpl<ISD::OutputArg> &Outs,
5014     const SmallVectorImpl<SDValue> &OutVals,
5015     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
5016   if (!mayTailCallThisCC(CalleeCC))
5017     return false;
5018 
5019   MachineFunction &MF = DAG.getMachineFunction();
5020   const Function &CallerF = MF.getFunction();
5021   CallingConv::ID CallerCC = CallerF.getCallingConv();
5022 
5023   // If this function uses the C calling convention but has an SVE signature,
5024   // then it preserves more registers and should assume the SVE_VectorCall CC.
5025   // The check for matching callee-saved regs will determine whether it is
5026   // eligible for TCO.
5027   if (CallerCC == CallingConv::C &&
5028       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
5029     CallerCC = CallingConv::AArch64_SVE_VectorCall;
5030 
5031   bool CCMatch = CallerCC == CalleeCC;
5032 
5033   // When using the Windows calling convention on a non-windows OS, we want
5034   // to back up and restore X18 in such functions; we can't do a tail call
5035   // from those functions.
5036   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
5037       CalleeCC != CallingConv::Win64)
5038     return false;
5039 
5040   // Byval parameters hand the function a pointer directly into the stack area
5041   // we want to reuse during a tail call. Working around this *is* possible (see
5042   // X86) but less efficient and uglier in LowerCall.
5043   for (Function::const_arg_iterator i = CallerF.arg_begin(),
5044                                     e = CallerF.arg_end();
5045        i != e; ++i) {
5046     if (i->hasByValAttr())
5047       return false;
5048 
5049     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
5050     // In this case, it is necessary to save/restore X0 in the callee. Tail
5051     // call opt interferes with this. So we disable tail call opt when the
5052     // caller has an argument with "inreg" attribute.
5053 
5054     // FIXME: Check whether the callee also has an "inreg" argument.
5055     if (i->hasInRegAttr())
5056       return false;
5057   }
5058 
5059   if (getTargetMachine().Options.GuaranteedTailCallOpt)
5060     return canGuaranteeTCO(CalleeCC) && CCMatch;
5061 
5062   // Externally-defined functions with weak linkage should not be
5063   // tail-called on AArch64 when the OS does not support dynamic
5064   // pre-emption of symbols, as the AAELF spec requires normal calls
5065   // to undefined weak functions to be replaced with a NOP or jump to the
5066   // next instruction. The behaviour of branch instructions in this
5067   // situation (as used for tail calls) is implementation-defined, so we
5068   // cannot rely on the linker replacing the tail call with a return.
5069   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5070     const GlobalValue *GV = G->getGlobal();
5071     const Triple &TT = getTargetMachine().getTargetTriple();
5072     if (GV->hasExternalWeakLinkage() &&
5073         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
5074       return false;
5075   }
5076 
5077   // Now we search for cases where we can use a tail call without changing the
5078   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
5079   // concept.
5080 
5081   // I want anyone implementing a new calling convention to think long and hard
5082   // about this assert.
5083   assert((!isVarArg || CalleeCC == CallingConv::C) &&
5084          "Unexpected variadic calling convention");
5085 
5086   LLVMContext &C = *DAG.getContext();
5087   if (isVarArg && !Outs.empty()) {
5088     // At least two cases here: if caller is fastcc then we can't have any
5089     // memory arguments (we'd be expected to clean up the stack afterwards). If
5090     // caller is C then we could potentially use its argument area.
5091 
5092     // FIXME: for now we take the most conservative of these in both cases:
5093     // disallow all variadic memory operands.
5094     SmallVector<CCValAssign, 16> ArgLocs;
5095     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5096 
5097     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
5098     for (const CCValAssign &ArgLoc : ArgLocs)
5099       if (!ArgLoc.isRegLoc())
5100         return false;
5101   }
5102 
5103   // Check that the call results are passed in the same way.
5104   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5105                                   CCAssignFnForCall(CalleeCC, isVarArg),
5106                                   CCAssignFnForCall(CallerCC, isVarArg)))
5107     return false;
5108   // The callee has to preserve all registers the caller needs to preserve.
5109   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5110   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5111   if (!CCMatch) {
5112     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5113     if (Subtarget->hasCustomCallingConv()) {
5114       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
5115       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
5116     }
5117     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5118       return false;
5119   }
5120 
5121   // Nothing more to check if the callee is taking no arguments
5122   if (Outs.empty())
5123     return true;
5124 
5125   SmallVector<CCValAssign, 16> ArgLocs;
5126   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5127 
5128   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
5129 
5130   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5131 
5132   // If any of the arguments is passed indirectly, it must be SVE, so the
5133   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
5134   // allocate space on the stack. That is why we determine this explicitly here
5135   // the call cannot be a tailcall.
5136   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
5137         assert((A.getLocInfo() != CCValAssign::Indirect ||
5138                 A.getValVT().isScalableVector()) &&
5139                "Expected value to be scalable");
5140         return A.getLocInfo() == CCValAssign::Indirect;
5141       }))
5142     return false;
5143 
5144   // If the stack arguments for this call do not fit into our own save area then
5145   // the call cannot be made tail.
5146   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
5147     return false;
5148 
5149   const MachineRegisterInfo &MRI = MF.getRegInfo();
5150   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5151     return false;
5152 
5153   return true;
5154 }
5155 
5156 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
5157                                                    SelectionDAG &DAG,
5158                                                    MachineFrameInfo &MFI,
5159                                                    int ClobberedFI) const {
5160   SmallVector<SDValue, 8> ArgChains;
5161   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
5162   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
5163 
5164   // Include the original chain at the beginning of the list. When this is
5165   // used by target LowerCall hooks, this helps legalize find the
5166   // CALLSEQ_BEGIN node.
5167   ArgChains.push_back(Chain);
5168 
5169   // Add a chain value for each stack argument corresponding
5170   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
5171                             UE = DAG.getEntryNode().getNode()->use_end();
5172        U != UE; ++U)
5173     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5174       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5175         if (FI->getIndex() < 0) {
5176           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
5177           int64_t InLastByte = InFirstByte;
5178           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
5179 
5180           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
5181               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
5182             ArgChains.push_back(SDValue(L, 1));
5183         }
5184 
5185   // Build a tokenfactor for all the chains.
5186   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5187 }
5188 
5189 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
5190                                                    bool TailCallOpt) const {
5191   return CallCC == CallingConv::Fast && TailCallOpt;
5192 }
5193 
5194 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
5195 /// and add input and output parameter nodes.
5196 SDValue
5197 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
5198                                  SmallVectorImpl<SDValue> &InVals) const {
5199   SelectionDAG &DAG = CLI.DAG;
5200   SDLoc &DL = CLI.DL;
5201   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
5202   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
5203   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
5204   SDValue Chain = CLI.Chain;
5205   SDValue Callee = CLI.Callee;
5206   bool &IsTailCall = CLI.IsTailCall;
5207   CallingConv::ID CallConv = CLI.CallConv;
5208   bool IsVarArg = CLI.IsVarArg;
5209 
5210   MachineFunction &MF = DAG.getMachineFunction();
5211   MachineFunction::CallSiteInfo CSInfo;
5212   bool IsThisReturn = false;
5213 
5214   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5215   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5216   bool IsSibCall = false;
5217 
5218   // Check callee args/returns for SVE registers and set calling convention
5219   // accordingly.
5220   if (CallConv == CallingConv::C) {
5221     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
5222       return Out.VT.isScalableVector();
5223     });
5224     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
5225       return In.VT.isScalableVector();
5226     });
5227 
5228     if (CalleeInSVE || CalleeOutSVE)
5229       CallConv = CallingConv::AArch64_SVE_VectorCall;
5230   }
5231 
5232   if (IsTailCall) {
5233     // Check if it's really possible to do a tail call.
5234     IsTailCall = isEligibleForTailCallOptimization(
5235         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
5236     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
5237       report_fatal_error("failed to perform tail call elimination on a call "
5238                          "site marked musttail");
5239 
5240     // A sibling call is one where we're under the usual C ABI and not planning
5241     // to change that but can still do a tail call:
5242     if (!TailCallOpt && IsTailCall)
5243       IsSibCall = true;
5244 
5245     if (IsTailCall)
5246       ++NumTailCalls;
5247   }
5248 
5249   // Analyze operands of the call, assigning locations to each operand.
5250   SmallVector<CCValAssign, 16> ArgLocs;
5251   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
5252                  *DAG.getContext());
5253 
5254   if (IsVarArg) {
5255     // Handle fixed and variable vector arguments differently.
5256     // Variable vector arguments always go into memory.
5257     unsigned NumArgs = Outs.size();
5258 
5259     for (unsigned i = 0; i != NumArgs; ++i) {
5260       MVT ArgVT = Outs[i].VT;
5261       if (!Outs[i].IsFixed && ArgVT.isScalableVector())
5262         report_fatal_error("Passing SVE types to variadic functions is "
5263                            "currently not supported");
5264 
5265       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5266       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
5267                                                /*IsVarArg=*/ !Outs[i].IsFixed);
5268       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
5269       assert(!Res && "Call operand has unhandled type");
5270       (void)Res;
5271     }
5272   } else {
5273     // At this point, Outs[].VT may already be promoted to i32. To correctly
5274     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5275     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5276     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
5277     // we use a special version of AnalyzeCallOperands to pass in ValVT and
5278     // LocVT.
5279     unsigned NumArgs = Outs.size();
5280     for (unsigned i = 0; i != NumArgs; ++i) {
5281       MVT ValVT = Outs[i].VT;
5282       // Get type of the original argument.
5283       EVT ActualVT = getValueType(DAG.getDataLayout(),
5284                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
5285                                   /*AllowUnknown*/ true);
5286       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
5287       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5288       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5289       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5290         ValVT = MVT::i8;
5291       else if (ActualMVT == MVT::i16)
5292         ValVT = MVT::i16;
5293 
5294       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
5295       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
5296       assert(!Res && "Call operand has unhandled type");
5297       (void)Res;
5298     }
5299   }
5300 
5301   // Get a count of how many bytes are to be pushed on the stack.
5302   unsigned NumBytes = CCInfo.getNextStackOffset();
5303 
5304   if (IsSibCall) {
5305     // Since we're not changing the ABI to make this a tail call, the memory
5306     // operands are already available in the caller's incoming argument space.
5307     NumBytes = 0;
5308   }
5309 
5310   // FPDiff is the byte offset of the call's argument area from the callee's.
5311   // Stores to callee stack arguments will be placed in FixedStackSlots offset
5312   // by this amount for a tail call. In a sibling call it must be 0 because the
5313   // caller will deallocate the entire stack and the callee still expects its
5314   // arguments to begin at SP+0. Completely unused for non-tail calls.
5315   int FPDiff = 0;
5316 
5317   if (IsTailCall && !IsSibCall) {
5318     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
5319 
5320     // Since callee will pop argument stack as a tail call, we must keep the
5321     // popped size 16-byte aligned.
5322     NumBytes = alignTo(NumBytes, 16);
5323 
5324     // FPDiff will be negative if this tail call requires more space than we
5325     // would automatically have in our incoming argument space. Positive if we
5326     // can actually shrink the stack.
5327     FPDiff = NumReusableBytes - NumBytes;
5328 
5329     // The stack pointer must be 16-byte aligned at all times it's used for a
5330     // memory operation, which in practice means at *all* times and in
5331     // particular across call boundaries. Therefore our own arguments started at
5332     // a 16-byte aligned SP and the delta applied for the tail call should
5333     // satisfy the same constraint.
5334     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
5335   }
5336 
5337   // Adjust the stack pointer for the new arguments...
5338   // These operations are automatically eliminated by the prolog/epilog pass
5339   if (!IsSibCall)
5340     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
5341 
5342   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
5343                                         getPointerTy(DAG.getDataLayout()));
5344 
5345   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5346   SmallSet<unsigned, 8> RegsUsed;
5347   SmallVector<SDValue, 8> MemOpChains;
5348   auto PtrVT = getPointerTy(DAG.getDataLayout());
5349 
5350   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
5351     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
5352     for (const auto &F : Forwards) {
5353       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
5354        RegsToPass.emplace_back(F.PReg, Val);
5355     }
5356   }
5357 
5358   // Walk the register/memloc assignments, inserting copies/loads.
5359   unsigned ExtraArgLocs = 0;
5360   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
5361     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
5362     SDValue Arg = OutVals[i];
5363     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5364 
5365     // Promote the value if needed.
5366     switch (VA.getLocInfo()) {
5367     default:
5368       llvm_unreachable("Unknown loc info!");
5369     case CCValAssign::Full:
5370       break;
5371     case CCValAssign::SExt:
5372       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
5373       break;
5374     case CCValAssign::ZExt:
5375       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5376       break;
5377     case CCValAssign::AExt:
5378       if (Outs[i].ArgVT == MVT::i1) {
5379         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
5380         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5381         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
5382       }
5383       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
5384       break;
5385     case CCValAssign::AExtUpper:
5386       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5387       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
5388       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5389                         DAG.getConstant(32, DL, VA.getLocVT()));
5390       break;
5391     case CCValAssign::BCvt:
5392       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
5393       break;
5394     case CCValAssign::Trunc:
5395       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5396       break;
5397     case CCValAssign::FPExt:
5398       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
5399       break;
5400     case CCValAssign::Indirect:
5401       assert(VA.getValVT().isScalableVector() &&
5402              "Only scalable vectors can be passed indirectly");
5403 
5404       uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
5405       uint64_t PartSize = StoreSize;
5406       unsigned NumParts = 1;
5407       if (Outs[i].Flags.isInConsecutiveRegs()) {
5408         assert(!Outs[i].Flags.isInConsecutiveRegsLast());
5409         while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
5410           ++NumParts;
5411         StoreSize *= NumParts;
5412       }
5413 
5414       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5415       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
5416       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
5417       int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
5418       MFI.setStackID(FI, TargetStackID::ScalableVector);
5419 
5420       MachinePointerInfo MPI =
5421           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
5422       SDValue Ptr = DAG.getFrameIndex(
5423           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
5424       SDValue SpillSlot = Ptr;
5425 
5426       // Ensure we generate all stores for each tuple part, whilst updating the
5427       // pointer after each store correctly using vscale.
5428       while (NumParts) {
5429         Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
5430         NumParts--;
5431         if (NumParts > 0) {
5432           SDValue BytesIncrement = DAG.getVScale(
5433               DL, Ptr.getValueType(),
5434               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
5435           SDNodeFlags Flags;
5436           Flags.setNoUnsignedWrap(true);
5437 
5438           MPI = MachinePointerInfo(MPI.getAddrSpace());
5439           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5440                             BytesIncrement, Flags);
5441           ExtraArgLocs++;
5442           i++;
5443         }
5444       }
5445 
5446       Arg = SpillSlot;
5447       break;
5448     }
5449 
5450     if (VA.isRegLoc()) {
5451       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
5452           Outs[0].VT == MVT::i64) {
5453         assert(VA.getLocVT() == MVT::i64 &&
5454                "unexpected calling convention register assignment");
5455         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
5456                "unexpected use of 'returned'");
5457         IsThisReturn = true;
5458       }
5459       if (RegsUsed.count(VA.getLocReg())) {
5460         // If this register has already been used then we're trying to pack
5461         // parts of an [N x i32] into an X-register. The extension type will
5462         // take care of putting the two halves in the right place but we have to
5463         // combine them.
5464         SDValue &Bits =
5465             llvm::find_if(RegsToPass,
5466                           [=](const std::pair<unsigned, SDValue> &Elt) {
5467                             return Elt.first == VA.getLocReg();
5468                           })
5469                 ->second;
5470         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5471         // Call site info is used for function's parameter entry value
5472         // tracking. For now we track only simple cases when parameter
5473         // is transferred through whole register.
5474         llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
5475           return ArgReg.Reg == VA.getLocReg();
5476         });
5477       } else {
5478         RegsToPass.emplace_back(VA.getLocReg(), Arg);
5479         RegsUsed.insert(VA.getLocReg());
5480         const TargetOptions &Options = DAG.getTarget().Options;
5481         if (Options.EmitCallSiteInfo)
5482           CSInfo.emplace_back(VA.getLocReg(), i);
5483       }
5484     } else {
5485       assert(VA.isMemLoc());
5486 
5487       SDValue DstAddr;
5488       MachinePointerInfo DstInfo;
5489 
5490       // FIXME: This works on big-endian for composite byvals, which are the
5491       // common case. It should also work for fundamental types too.
5492       uint32_t BEAlign = 0;
5493       unsigned OpSize;
5494       if (VA.getLocInfo() == CCValAssign::Indirect)
5495         OpSize = VA.getLocVT().getFixedSizeInBits();
5496       else
5497         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
5498                                  : VA.getValVT().getSizeInBits();
5499       OpSize = (OpSize + 7) / 8;
5500       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
5501           !Flags.isInConsecutiveRegs()) {
5502         if (OpSize < 8)
5503           BEAlign = 8 - OpSize;
5504       }
5505       unsigned LocMemOffset = VA.getLocMemOffset();
5506       int32_t Offset = LocMemOffset + BEAlign;
5507       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5508       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5509 
5510       if (IsTailCall) {
5511         Offset = Offset + FPDiff;
5512         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5513 
5514         DstAddr = DAG.getFrameIndex(FI, PtrVT);
5515         DstInfo =
5516             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
5517 
5518         // Make sure any stack arguments overlapping with where we're storing
5519         // are loaded before this eventual operation. Otherwise they'll be
5520         // clobbered.
5521         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
5522       } else {
5523         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5524 
5525         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5526         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
5527                                                LocMemOffset);
5528       }
5529 
5530       if (Outs[i].Flags.isByVal()) {
5531         SDValue SizeNode =
5532             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
5533         SDValue Cpy = DAG.getMemcpy(
5534             Chain, DL, DstAddr, Arg, SizeNode,
5535             Outs[i].Flags.getNonZeroByValAlign(),
5536             /*isVol = */ false, /*AlwaysInline = */ false,
5537             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
5538 
5539         MemOpChains.push_back(Cpy);
5540       } else {
5541         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
5542         // promoted to a legal register type i32, we should truncate Arg back to
5543         // i1/i8/i16.
5544         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
5545             VA.getValVT() == MVT::i16)
5546           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
5547 
5548         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
5549         MemOpChains.push_back(Store);
5550       }
5551     }
5552   }
5553 
5554   if (!MemOpChains.empty())
5555     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
5556 
5557   // Build a sequence of copy-to-reg nodes chained together with token chain
5558   // and flag operands which copy the outgoing args into the appropriate regs.
5559   SDValue InFlag;
5560   for (auto &RegToPass : RegsToPass) {
5561     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
5562                              RegToPass.second, InFlag);
5563     InFlag = Chain.getValue(1);
5564   }
5565 
5566   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
5567   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
5568   // node so that legalize doesn't hack it.
5569   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5570     auto GV = G->getGlobal();
5571     unsigned OpFlags =
5572         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
5573     if (OpFlags & AArch64II::MO_GOT) {
5574       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
5575       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5576     } else {
5577       const GlobalValue *GV = G->getGlobal();
5578       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
5579     }
5580   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5581     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5582         Subtarget->isTargetMachO()) {
5583       const char *Sym = S->getSymbol();
5584       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
5585       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5586     } else {
5587       const char *Sym = S->getSymbol();
5588       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
5589     }
5590   }
5591 
5592   // We don't usually want to end the call-sequence here because we would tidy
5593   // the frame up *after* the call, however in the ABI-changing tail-call case
5594   // we've carefully laid out the parameters so that when sp is reset they'll be
5595   // in the correct location.
5596   if (IsTailCall && !IsSibCall) {
5597     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5598                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
5599     InFlag = Chain.getValue(1);
5600   }
5601 
5602   std::vector<SDValue> Ops;
5603   Ops.push_back(Chain);
5604   Ops.push_back(Callee);
5605 
5606   if (IsTailCall) {
5607     // Each tail call may have to adjust the stack by a different amount, so
5608     // this information must travel along with the operation for eventual
5609     // consumption by emitEpilogue.
5610     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
5611   }
5612 
5613   // Add argument registers to the end of the list so that they are known live
5614   // into the call.
5615   for (auto &RegToPass : RegsToPass)
5616     Ops.push_back(DAG.getRegister(RegToPass.first,
5617                                   RegToPass.second.getValueType()));
5618 
5619   // Add a register mask operand representing the call-preserved registers.
5620   const uint32_t *Mask;
5621   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5622   if (IsThisReturn) {
5623     // For 'this' returns, use the X0-preserving mask if applicable
5624     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
5625     if (!Mask) {
5626       IsThisReturn = false;
5627       Mask = TRI->getCallPreservedMask(MF, CallConv);
5628     }
5629   } else
5630     Mask = TRI->getCallPreservedMask(MF, CallConv);
5631 
5632   if (Subtarget->hasCustomCallingConv())
5633     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
5634 
5635   if (TRI->isAnyArgRegReserved(MF))
5636     TRI->emitReservedArgRegCallError(MF);
5637 
5638   assert(Mask && "Missing call preserved mask for calling convention");
5639   Ops.push_back(DAG.getRegisterMask(Mask));
5640 
5641   if (InFlag.getNode())
5642     Ops.push_back(InFlag);
5643 
5644   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5645 
5646   // If we're doing a tall call, use a TC_RETURN here rather than an
5647   // actual call instruction.
5648   if (IsTailCall) {
5649     MF.getFrameInfo().setHasTailCall();
5650     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
5651     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
5652     return Ret;
5653   }
5654 
5655   unsigned CallOpc = AArch64ISD::CALL;
5656   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
5657   // be expanded to the call, directly followed by a special marker sequence.
5658   // Use the CALL_RVMARKER to do that.
5659   if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
5660     assert(!IsTailCall &&
5661            "tail calls cannot be marked with clang.arc.attachedcall");
5662     CallOpc = AArch64ISD::CALL_RVMARKER;
5663   }
5664 
5665   // Returns a chain and a flag for retval copy to use.
5666   Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
5667   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5668   InFlag = Chain.getValue(1);
5669   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
5670 
5671   uint64_t CalleePopBytes =
5672       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
5673 
5674   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5675                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
5676                              InFlag, DL);
5677   if (!Ins.empty())
5678     InFlag = Chain.getValue(1);
5679 
5680   // Handle result values, copying them out of physregs into vregs that we
5681   // return.
5682   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
5683                          InVals, IsThisReturn,
5684                          IsThisReturn ? OutVals[0] : SDValue());
5685 }
5686 
5687 bool AArch64TargetLowering::CanLowerReturn(
5688     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
5689     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
5690   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5691   SmallVector<CCValAssign, 16> RVLocs;
5692   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5693   return CCInfo.CheckReturn(Outs, RetCC);
5694 }
5695 
5696 SDValue
5697 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5698                                    bool isVarArg,
5699                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
5700                                    const SmallVectorImpl<SDValue> &OutVals,
5701                                    const SDLoc &DL, SelectionDAG &DAG) const {
5702   auto &MF = DAG.getMachineFunction();
5703   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5704 
5705   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5706   SmallVector<CCValAssign, 16> RVLocs;
5707   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5708                  *DAG.getContext());
5709   CCInfo.AnalyzeReturn(Outs, RetCC);
5710 
5711   // Copy the result values into the output registers.
5712   SDValue Flag;
5713   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
5714   SmallSet<unsigned, 4> RegsUsed;
5715   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
5716        ++i, ++realRVLocIdx) {
5717     CCValAssign &VA = RVLocs[i];
5718     assert(VA.isRegLoc() && "Can only return in registers!");
5719     SDValue Arg = OutVals[realRVLocIdx];
5720 
5721     switch (VA.getLocInfo()) {
5722     default:
5723       llvm_unreachable("Unknown loc info!");
5724     case CCValAssign::Full:
5725       if (Outs[i].ArgVT == MVT::i1) {
5726         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
5727         // value. This is strictly redundant on Darwin (which uses "zeroext
5728         // i1"), but will be optimised out before ISel.
5729         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5730         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5731       }
5732       break;
5733     case CCValAssign::BCvt:
5734       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
5735       break;
5736     case CCValAssign::AExt:
5737     case CCValAssign::ZExt:
5738       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5739       break;
5740     case CCValAssign::AExtUpper:
5741       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5742       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5743       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5744                         DAG.getConstant(32, DL, VA.getLocVT()));
5745       break;
5746     }
5747 
5748     if (RegsUsed.count(VA.getLocReg())) {
5749       SDValue &Bits =
5750           llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
5751             return Elt.first == VA.getLocReg();
5752           })->second;
5753       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5754     } else {
5755       RetVals.emplace_back(VA.getLocReg(), Arg);
5756       RegsUsed.insert(VA.getLocReg());
5757     }
5758   }
5759 
5760   SmallVector<SDValue, 4> RetOps(1, Chain);
5761   for (auto &RetVal : RetVals) {
5762     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
5763     Flag = Chain.getValue(1);
5764     RetOps.push_back(
5765         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
5766   }
5767 
5768   // Windows AArch64 ABIs require that for returning structs by value we copy
5769   // the sret argument into X0 for the return.
5770   // We saved the argument into a virtual register in the entry block,
5771   // so now we copy the value out and into X0.
5772   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
5773     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
5774                                      getPointerTy(MF.getDataLayout()));
5775 
5776     unsigned RetValReg = AArch64::X0;
5777     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
5778     Flag = Chain.getValue(1);
5779 
5780     RetOps.push_back(
5781       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
5782   }
5783 
5784   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5785   const MCPhysReg *I =
5786       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5787   if (I) {
5788     for (; *I; ++I) {
5789       if (AArch64::GPR64RegClass.contains(*I))
5790         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5791       else if (AArch64::FPR64RegClass.contains(*I))
5792         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5793       else
5794         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5795     }
5796   }
5797 
5798   RetOps[0] = Chain; // Update chain.
5799 
5800   // Add the flag if we have it.
5801   if (Flag.getNode())
5802     RetOps.push_back(Flag);
5803 
5804   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
5805 }
5806 
5807 //===----------------------------------------------------------------------===//
5808 //  Other Lowering Code
5809 //===----------------------------------------------------------------------===//
5810 
5811 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
5812                                              SelectionDAG &DAG,
5813                                              unsigned Flag) const {
5814   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
5815                                     N->getOffset(), Flag);
5816 }
5817 
5818 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
5819                                              SelectionDAG &DAG,
5820                                              unsigned Flag) const {
5821   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
5822 }
5823 
5824 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
5825                                              SelectionDAG &DAG,
5826                                              unsigned Flag) const {
5827   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
5828                                    N->getOffset(), Flag);
5829 }
5830 
5831 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
5832                                              SelectionDAG &DAG,
5833                                              unsigned Flag) const {
5834   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
5835 }
5836 
5837 // (loadGOT sym)
5838 template <class NodeTy>
5839 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
5840                                       unsigned Flags) const {
5841   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
5842   SDLoc DL(N);
5843   EVT Ty = getPointerTy(DAG.getDataLayout());
5844   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
5845   // FIXME: Once remat is capable of dealing with instructions with register
5846   // operands, expand this into two nodes instead of using a wrapper node.
5847   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
5848 }
5849 
5850 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
5851 template <class NodeTy>
5852 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
5853                                             unsigned Flags) const {
5854   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
5855   SDLoc DL(N);
5856   EVT Ty = getPointerTy(DAG.getDataLayout());
5857   const unsigned char MO_NC = AArch64II::MO_NC;
5858   return DAG.getNode(
5859       AArch64ISD::WrapperLarge, DL, Ty,
5860       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
5861       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
5862       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
5863       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
5864 }
5865 
5866 // (addlow (adrp %hi(sym)) %lo(sym))
5867 template <class NodeTy>
5868 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
5869                                        unsigned Flags) const {
5870   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
5871   SDLoc DL(N);
5872   EVT Ty = getPointerTy(DAG.getDataLayout());
5873   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
5874   SDValue Lo = getTargetNode(N, Ty, DAG,
5875                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
5876   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
5877   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
5878 }
5879 
5880 // (adr sym)
5881 template <class NodeTy>
5882 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
5883                                            unsigned Flags) const {
5884   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
5885   SDLoc DL(N);
5886   EVT Ty = getPointerTy(DAG.getDataLayout());
5887   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
5888   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
5889 }
5890 
5891 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
5892                                                   SelectionDAG &DAG) const {
5893   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
5894   const GlobalValue *GV = GN->getGlobal();
5895   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5896 
5897   if (OpFlags != AArch64II::MO_NO_FLAG)
5898     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
5899            "unexpected offset in global node");
5900 
5901   // This also catches the large code model case for Darwin, and tiny code
5902   // model with got relocations.
5903   if ((OpFlags & AArch64II::MO_GOT) != 0) {
5904     return getGOT(GN, DAG, OpFlags);
5905   }
5906 
5907   SDValue Result;
5908   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5909     Result = getAddrLarge(GN, DAG, OpFlags);
5910   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5911     Result = getAddrTiny(GN, DAG, OpFlags);
5912   } else {
5913     Result = getAddr(GN, DAG, OpFlags);
5914   }
5915   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5916   SDLoc DL(GN);
5917   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
5918     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
5919                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
5920   return Result;
5921 }
5922 
5923 /// Convert a TLS address reference into the correct sequence of loads
5924 /// and calls to compute the variable's address (for Darwin, currently) and
5925 /// return an SDValue containing the final node.
5926 
5927 /// Darwin only has one TLS scheme which must be capable of dealing with the
5928 /// fully general situation, in the worst case. This means:
5929 ///     + "extern __thread" declaration.
5930 ///     + Defined in a possibly unknown dynamic library.
5931 ///
5932 /// The general system is that each __thread variable has a [3 x i64] descriptor
5933 /// which contains information used by the runtime to calculate the address. The
5934 /// only part of this the compiler needs to know about is the first xword, which
5935 /// contains a function pointer that must be called with the address of the
5936 /// entire descriptor in "x0".
5937 ///
5938 /// Since this descriptor may be in a different unit, in general even the
5939 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5940 /// is:
5941 ///     adrp x0, _var@TLVPPAGE
5942 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5943 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5944 ///                                      ; the function pointer
5945 ///     blr x1                           ; Uses descriptor address in x0
5946 ///     ; Address of _var is now in x0.
5947 ///
5948 /// If the address of _var's descriptor *is* known to the linker, then it can
5949 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5950 /// a slight efficiency gain.
5951 SDValue
5952 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5953                                                    SelectionDAG &DAG) const {
5954   assert(Subtarget->isTargetDarwin() &&
5955          "This function expects a Darwin target");
5956 
5957   SDLoc DL(Op);
5958   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5959   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5960   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5961 
5962   SDValue TLVPAddr =
5963       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5964   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5965 
5966   // The first entry in the descriptor is a function pointer that we must call
5967   // to obtain the address of the variable.
5968   SDValue Chain = DAG.getEntryNode();
5969   SDValue FuncTLVGet = DAG.getLoad(
5970       PtrMemVT, DL, Chain, DescAddr,
5971       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5972       Align(PtrMemVT.getSizeInBits() / 8),
5973       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5974   Chain = FuncTLVGet.getValue(1);
5975 
5976   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5977   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5978 
5979   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5980   MFI.setAdjustsStack(true);
5981 
5982   // TLS calls preserve all registers except those that absolutely must be
5983   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5984   // silly).
5985   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5986   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5987   if (Subtarget->hasCustomCallingConv())
5988     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5989 
5990   // Finally, we can make the call. This is just a degenerate version of a
5991   // normal AArch64 call node: x0 takes the address of the descriptor, and
5992   // returns the address of the variable in this thread.
5993   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5994   Chain =
5995       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5996                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5997                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5998   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5999 }
6000 
6001 /// Convert a thread-local variable reference into a sequence of instructions to
6002 /// compute the variable's address for the local exec TLS model of ELF targets.
6003 /// The sequence depends on the maximum TLS area size.
6004 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
6005                                                     SDValue ThreadBase,
6006                                                     const SDLoc &DL,
6007                                                     SelectionDAG &DAG) const {
6008   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6009   SDValue TPOff, Addr;
6010 
6011   switch (DAG.getTarget().Options.TLSSize) {
6012   default:
6013     llvm_unreachable("Unexpected TLS size");
6014 
6015   case 12: {
6016     // mrs   x0, TPIDR_EL0
6017     // add   x0, x0, :tprel_lo12:a
6018     SDValue Var = DAG.getTargetGlobalAddress(
6019         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
6020     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6021                                       Var,
6022                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6023                    0);
6024   }
6025 
6026   case 24: {
6027     // mrs   x0, TPIDR_EL0
6028     // add   x0, x0, :tprel_hi12:a
6029     // add   x0, x0, :tprel_lo12_nc:a
6030     SDValue HiVar = DAG.getTargetGlobalAddress(
6031         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6032     SDValue LoVar = DAG.getTargetGlobalAddress(
6033         GV, DL, PtrVT, 0,
6034         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6035     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6036                                       HiVar,
6037                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6038                    0);
6039     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
6040                                       LoVar,
6041                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6042                    0);
6043   }
6044 
6045   case 32: {
6046     // mrs   x1, TPIDR_EL0
6047     // movz  x0, #:tprel_g1:a
6048     // movk  x0, #:tprel_g0_nc:a
6049     // add   x0, x1, x0
6050     SDValue HiVar = DAG.getTargetGlobalAddress(
6051         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
6052     SDValue LoVar = DAG.getTargetGlobalAddress(
6053         GV, DL, PtrVT, 0,
6054         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6055     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6056                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6057                     0);
6058     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6059                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6060                     0);
6061     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6062   }
6063 
6064   case 48: {
6065     // mrs   x1, TPIDR_EL0
6066     // movz  x0, #:tprel_g2:a
6067     // movk  x0, #:tprel_g1_nc:a
6068     // movk  x0, #:tprel_g0_nc:a
6069     // add   x0, x1, x0
6070     SDValue HiVar = DAG.getTargetGlobalAddress(
6071         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
6072     SDValue MiVar = DAG.getTargetGlobalAddress(
6073         GV, DL, PtrVT, 0,
6074         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
6075     SDValue LoVar = DAG.getTargetGlobalAddress(
6076         GV, DL, PtrVT, 0,
6077         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6078     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6079                                        DAG.getTargetConstant(32, DL, MVT::i32)),
6080                     0);
6081     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
6082                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6083                     0);
6084     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6085                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6086                     0);
6087     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6088   }
6089   }
6090 }
6091 
6092 /// When accessing thread-local variables under either the general-dynamic or
6093 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
6094 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
6095 /// is a function pointer to carry out the resolution.
6096 ///
6097 /// The sequence is:
6098 ///    adrp  x0, :tlsdesc:var
6099 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
6100 ///    add   x0, x0, #:tlsdesc_lo12:var
6101 ///    .tlsdesccall var
6102 ///    blr   x1
6103 ///    (TPIDR_EL0 offset now in x0)
6104 ///
6105 ///  The above sequence must be produced unscheduled, to enable the linker to
6106 ///  optimize/relax this sequence.
6107 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
6108 ///  above sequence, and expanded really late in the compilation flow, to ensure
6109 ///  the sequence is produced as per above.
6110 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
6111                                                       const SDLoc &DL,
6112                                                       SelectionDAG &DAG) const {
6113   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6114 
6115   SDValue Chain = DAG.getEntryNode();
6116   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6117 
6118   Chain =
6119       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
6120   SDValue Glue = Chain.getValue(1);
6121 
6122   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
6123 }
6124 
6125 SDValue
6126 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
6127                                                 SelectionDAG &DAG) const {
6128   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
6129 
6130   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6131 
6132   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
6133 
6134   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
6135     if (Model == TLSModel::LocalDynamic)
6136       Model = TLSModel::GeneralDynamic;
6137   }
6138 
6139   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6140       Model != TLSModel::LocalExec)
6141     report_fatal_error("ELF TLS only supported in small memory model or "
6142                        "in local exec TLS model");
6143   // Different choices can be made for the maximum size of the TLS area for a
6144   // module. For the small address model, the default TLS size is 16MiB and the
6145   // maximum TLS size is 4GiB.
6146   // FIXME: add tiny and large code model support for TLS access models other
6147   // than local exec. We currently generate the same code as small for tiny,
6148   // which may be larger than needed.
6149 
6150   SDValue TPOff;
6151   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6152   SDLoc DL(Op);
6153   const GlobalValue *GV = GA->getGlobal();
6154 
6155   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
6156 
6157   if (Model == TLSModel::LocalExec) {
6158     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
6159   } else if (Model == TLSModel::InitialExec) {
6160     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6161     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
6162   } else if (Model == TLSModel::LocalDynamic) {
6163     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
6164     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
6165     // the beginning of the module's TLS region, followed by a DTPREL offset
6166     // calculation.
6167 
6168     // These accesses will need deduplicating if there's more than one.
6169     AArch64FunctionInfo *MFI =
6170         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6171     MFI->incNumLocalDynamicTLSAccesses();
6172 
6173     // The call needs a relocation too for linker relaxation. It doesn't make
6174     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6175     // the address.
6176     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
6177                                                   AArch64II::MO_TLS);
6178 
6179     // Now we can calculate the offset from TPIDR_EL0 to this module's
6180     // thread-local area.
6181     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6182 
6183     // Now use :dtprel_whatever: operations to calculate this variable's offset
6184     // in its thread-storage area.
6185     SDValue HiVar = DAG.getTargetGlobalAddress(
6186         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6187     SDValue LoVar = DAG.getTargetGlobalAddress(
6188         GV, DL, MVT::i64, 0,
6189         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6190 
6191     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
6192                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6193                     0);
6194     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
6195                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6196                     0);
6197   } else if (Model == TLSModel::GeneralDynamic) {
6198     // The call needs a relocation too for linker relaxation. It doesn't make
6199     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6200     // the address.
6201     SDValue SymAddr =
6202         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6203 
6204     // Finally we can make a call to calculate the offset from tpidr_el0.
6205     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6206   } else
6207     llvm_unreachable("Unsupported ELF TLS access model");
6208 
6209   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6210 }
6211 
6212 SDValue
6213 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
6214                                                     SelectionDAG &DAG) const {
6215   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
6216 
6217   SDValue Chain = DAG.getEntryNode();
6218   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6219   SDLoc DL(Op);
6220 
6221   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
6222 
6223   // Load the ThreadLocalStoragePointer from the TEB
6224   // A pointer to the TLS array is located at offset 0x58 from the TEB.
6225   SDValue TLSArray =
6226       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
6227   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
6228   Chain = TLSArray.getValue(1);
6229 
6230   // Load the TLS index from the C runtime;
6231   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
6232   // This also does the same as LOADgot, but using a generic i32 load,
6233   // while LOADgot only loads i64.
6234   SDValue TLSIndexHi =
6235       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
6236   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
6237       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6238   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
6239   SDValue TLSIndex =
6240       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
6241   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
6242   Chain = TLSIndex.getValue(1);
6243 
6244   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
6245   // offset into the TLSArray.
6246   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
6247   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
6248                              DAG.getConstant(3, DL, PtrVT));
6249   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
6250                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
6251                             MachinePointerInfo());
6252   Chain = TLS.getValue(1);
6253 
6254   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6255   const GlobalValue *GV = GA->getGlobal();
6256   SDValue TGAHi = DAG.getTargetGlobalAddress(
6257       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6258   SDValue TGALo = DAG.getTargetGlobalAddress(
6259       GV, DL, PtrVT, 0,
6260       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6261 
6262   // Add the offset from the start of the .tls section (section base).
6263   SDValue Addr =
6264       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
6265                                  DAG.getTargetConstant(0, DL, MVT::i32)),
6266               0);
6267   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
6268   return Addr;
6269 }
6270 
6271 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
6272                                                      SelectionDAG &DAG) const {
6273   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6274   if (DAG.getTarget().useEmulatedTLS())
6275     return LowerToTLSEmulatedModel(GA, DAG);
6276 
6277   if (Subtarget->isTargetDarwin())
6278     return LowerDarwinGlobalTLSAddress(Op, DAG);
6279   if (Subtarget->isTargetELF())
6280     return LowerELFGlobalTLSAddress(Op, DAG);
6281   if (Subtarget->isTargetWindows())
6282     return LowerWindowsGlobalTLSAddress(Op, DAG);
6283 
6284   llvm_unreachable("Unexpected platform trying to use TLS");
6285 }
6286 
6287 // Looks through \param Val to determine the bit that can be used to
6288 // check the sign of the value. It returns the unextended value and
6289 // the sign bit position.
6290 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
6291   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
6292     return {Val.getOperand(0),
6293             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
6294                 1};
6295 
6296   if (Val.getOpcode() == ISD::SIGN_EXTEND)
6297     return {Val.getOperand(0),
6298             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
6299 
6300   return {Val, Val.getValueSizeInBits() - 1};
6301 }
6302 
6303 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
6304   SDValue Chain = Op.getOperand(0);
6305   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
6306   SDValue LHS = Op.getOperand(2);
6307   SDValue RHS = Op.getOperand(3);
6308   SDValue Dest = Op.getOperand(4);
6309   SDLoc dl(Op);
6310 
6311   MachineFunction &MF = DAG.getMachineFunction();
6312   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
6313   // will not be produced, as they are conditional branch instructions that do
6314   // not set flags.
6315   bool ProduceNonFlagSettingCondBr =
6316       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
6317 
6318   // Handle f128 first, since lowering it will result in comparing the return
6319   // value of a libcall against zero, which is just what the rest of LowerBR_CC
6320   // is expecting to deal with.
6321   if (LHS.getValueType() == MVT::f128) {
6322     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6323 
6324     // If softenSetCCOperands returned a scalar, we need to compare the result
6325     // against zero to select between true and false values.
6326     if (!RHS.getNode()) {
6327       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6328       CC = ISD::SETNE;
6329     }
6330   }
6331 
6332   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
6333   // instruction.
6334   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
6335       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6336     // Only lower legal XALUO ops.
6337     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
6338       return SDValue();
6339 
6340     // The actual operation with overflow check.
6341     AArch64CC::CondCode OFCC;
6342     SDValue Value, Overflow;
6343     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
6344 
6345     if (CC == ISD::SETNE)
6346       OFCC = getInvertedCondCode(OFCC);
6347     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
6348 
6349     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
6350                        Overflow);
6351   }
6352 
6353   if (LHS.getValueType().isInteger()) {
6354     assert((LHS.getValueType() == RHS.getValueType()) &&
6355            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
6356 
6357     // If the RHS of the comparison is zero, we can potentially fold this
6358     // to a specialized branch.
6359     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
6360     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
6361       if (CC == ISD::SETEQ) {
6362         // See if we can use a TBZ to fold in an AND as well.
6363         // TBZ has a smaller branch displacement than CBZ.  If the offset is
6364         // out of bounds, a late MI-layer pass rewrites branches.
6365         // 403.gcc is an example that hits this case.
6366         if (LHS.getOpcode() == ISD::AND &&
6367             isa<ConstantSDNode>(LHS.getOperand(1)) &&
6368             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
6369           SDValue Test = LHS.getOperand(0);
6370           uint64_t Mask = LHS.getConstantOperandVal(1);
6371           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
6372                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
6373                              Dest);
6374         }
6375 
6376         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
6377       } else if (CC == ISD::SETNE) {
6378         // See if we can use a TBZ to fold in an AND as well.
6379         // TBZ has a smaller branch displacement than CBZ.  If the offset is
6380         // out of bounds, a late MI-layer pass rewrites branches.
6381         // 403.gcc is an example that hits this case.
6382         if (LHS.getOpcode() == ISD::AND &&
6383             isa<ConstantSDNode>(LHS.getOperand(1)) &&
6384             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
6385           SDValue Test = LHS.getOperand(0);
6386           uint64_t Mask = LHS.getConstantOperandVal(1);
6387           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
6388                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
6389                              Dest);
6390         }
6391 
6392         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
6393       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
6394         // Don't combine AND since emitComparison converts the AND to an ANDS
6395         // (a.k.a. TST) and the test in the test bit and branch instruction
6396         // becomes redundant.  This would also increase register pressure.
6397         uint64_t SignBitPos;
6398         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
6399         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
6400                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
6401       }
6402     }
6403     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
6404         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
6405       // Don't combine AND since emitComparison converts the AND to an ANDS
6406       // (a.k.a. TST) and the test in the test bit and branch instruction
6407       // becomes redundant.  This would also increase register pressure.
6408       uint64_t SignBitPos;
6409       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
6410       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
6411                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
6412     }
6413 
6414     SDValue CCVal;
6415     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6416     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
6417                        Cmp);
6418   }
6419 
6420   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
6421          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
6422 
6423   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6424   // clean.  Some of them require two branches to implement.
6425   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6426   AArch64CC::CondCode CC1, CC2;
6427   changeFPCCToAArch64CC(CC, CC1, CC2);
6428   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6429   SDValue BR1 =
6430       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
6431   if (CC2 != AArch64CC::AL) {
6432     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6433     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
6434                        Cmp);
6435   }
6436 
6437   return BR1;
6438 }
6439 
6440 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
6441                                               SelectionDAG &DAG) const {
6442   EVT VT = Op.getValueType();
6443   SDLoc DL(Op);
6444 
6445   SDValue In1 = Op.getOperand(0);
6446   SDValue In2 = Op.getOperand(1);
6447   EVT SrcVT = In2.getValueType();
6448 
6449   if (SrcVT.bitsLT(VT))
6450     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
6451   else if (SrcVT.bitsGT(VT))
6452     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
6453 
6454   EVT VecVT;
6455   uint64_t EltMask;
6456   SDValue VecVal1, VecVal2;
6457 
6458   auto setVecVal = [&] (int Idx) {
6459     if (!VT.isVector()) {
6460       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
6461                                           DAG.getUNDEF(VecVT), In1);
6462       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
6463                                           DAG.getUNDEF(VecVT), In2);
6464     } else {
6465       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
6466       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
6467     }
6468   };
6469 
6470   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
6471     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
6472     EltMask = 0x80000000ULL;
6473     setVecVal(AArch64::ssub);
6474   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
6475     VecVT = MVT::v2i64;
6476 
6477     // We want to materialize a mask with the high bit set, but the AdvSIMD
6478     // immediate moves cannot materialize that in a single instruction for
6479     // 64-bit elements. Instead, materialize zero and then negate it.
6480     EltMask = 0;
6481 
6482     setVecVal(AArch64::dsub);
6483   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
6484     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
6485     EltMask = 0x8000ULL;
6486     setVecVal(AArch64::hsub);
6487   } else {
6488     llvm_unreachable("Invalid type for copysign!");
6489   }
6490 
6491   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
6492 
6493   // If we couldn't materialize the mask above, then the mask vector will be
6494   // the zero vector, and we need to negate it here.
6495   if (VT == MVT::f64 || VT == MVT::v2f64) {
6496     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
6497     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
6498     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
6499   }
6500 
6501   SDValue Sel =
6502       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
6503 
6504   if (VT == MVT::f16)
6505     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
6506   if (VT == MVT::f32)
6507     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
6508   else if (VT == MVT::f64)
6509     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
6510   else
6511     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
6512 }
6513 
6514 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
6515   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
6516           Attribute::NoImplicitFloat))
6517     return SDValue();
6518 
6519   if (!Subtarget->hasNEON())
6520     return SDValue();
6521 
6522   // While there is no integer popcount instruction, it can
6523   // be more efficiently lowered to the following sequence that uses
6524   // AdvSIMD registers/instructions as long as the copies to/from
6525   // the AdvSIMD registers are cheap.
6526   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
6527   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
6528   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
6529   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
6530   SDValue Val = Op.getOperand(0);
6531   SDLoc DL(Op);
6532   EVT VT = Op.getValueType();
6533 
6534   if (VT == MVT::i32 || VT == MVT::i64) {
6535     if (VT == MVT::i32)
6536       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
6537     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
6538 
6539     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
6540     SDValue UaddLV = DAG.getNode(
6541         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6542         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6543 
6544     if (VT == MVT::i64)
6545       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
6546     return UaddLV;
6547   } else if (VT == MVT::i128) {
6548     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
6549 
6550     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
6551     SDValue UaddLV = DAG.getNode(
6552         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6553         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6554 
6555     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
6556   }
6557 
6558   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
6559     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
6560 
6561   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6562           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6563          "Unexpected type for custom ctpop lowering");
6564 
6565   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6566   Val = DAG.getBitcast(VT8Bit, Val);
6567   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
6568 
6569   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6570   unsigned EltSize = 8;
6571   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6572   while (EltSize != VT.getScalarSizeInBits()) {
6573     EltSize *= 2;
6574     NumElts /= 2;
6575     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6576     Val = DAG.getNode(
6577         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
6578         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
6579   }
6580 
6581   return Val;
6582 }
6583 
6584 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
6585   EVT VT = Op.getValueType();
6586   assert(VT.isScalableVector() ||
6587          useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
6588 
6589   SDLoc DL(Op);
6590   SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
6591   return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
6592 }
6593 
6594 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6595 
6596   if (Op.getValueType().isVector())
6597     return LowerVSETCC(Op, DAG);
6598 
6599   bool IsStrict = Op->isStrictFPOpcode();
6600   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
6601   unsigned OpNo = IsStrict ? 1 : 0;
6602   SDValue Chain;
6603   if (IsStrict)
6604     Chain = Op.getOperand(0);
6605   SDValue LHS = Op.getOperand(OpNo + 0);
6606   SDValue RHS = Op.getOperand(OpNo + 1);
6607   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
6608   SDLoc dl(Op);
6609 
6610   // We chose ZeroOrOneBooleanContents, so use zero and one.
6611   EVT VT = Op.getValueType();
6612   SDValue TVal = DAG.getConstant(1, dl, VT);
6613   SDValue FVal = DAG.getConstant(0, dl, VT);
6614 
6615   // Handle f128 first, since one possible outcome is a normal integer
6616   // comparison which gets picked up by the next if statement.
6617   if (LHS.getValueType() == MVT::f128) {
6618     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
6619                         IsSignaling);
6620 
6621     // If softenSetCCOperands returned a scalar, use it.
6622     if (!RHS.getNode()) {
6623       assert(LHS.getValueType() == Op.getValueType() &&
6624              "Unexpected setcc expansion!");
6625       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
6626     }
6627   }
6628 
6629   if (LHS.getValueType().isInteger()) {
6630     SDValue CCVal;
6631     SDValue Cmp = getAArch64Cmp(
6632         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
6633 
6634     // Note that we inverted the condition above, so we reverse the order of
6635     // the true and false operands here.  This will allow the setcc to be
6636     // matched to a single CSINC instruction.
6637     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
6638     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
6639   }
6640 
6641   // Now we know we're dealing with FP values.
6642   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6643          LHS.getValueType() == MVT::f64);
6644 
6645   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
6646   // and do the comparison.
6647   SDValue Cmp;
6648   if (IsStrict)
6649     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
6650   else
6651     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6652 
6653   AArch64CC::CondCode CC1, CC2;
6654   changeFPCCToAArch64CC(CC, CC1, CC2);
6655   SDValue Res;
6656   if (CC2 == AArch64CC::AL) {
6657     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
6658                           CC2);
6659     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6660 
6661     // Note that we inverted the condition above, so we reverse the order of
6662     // the true and false operands here.  This will allow the setcc to be
6663     // matched to a single CSINC instruction.
6664     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
6665   } else {
6666     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
6667     // totally clean.  Some of them require two CSELs to implement.  As is in
6668     // this case, we emit the first CSEL and then emit a second using the output
6669     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
6670 
6671     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
6672     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6673     SDValue CS1 =
6674         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6675 
6676     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6677     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6678   }
6679   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
6680 }
6681 
6682 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
6683                                               SDValue RHS, SDValue TVal,
6684                                               SDValue FVal, const SDLoc &dl,
6685                                               SelectionDAG &DAG) const {
6686   // Handle f128 first, because it will result in a comparison of some RTLIB
6687   // call result against zero.
6688   if (LHS.getValueType() == MVT::f128) {
6689     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6690 
6691     // If softenSetCCOperands returned a scalar, we need to compare the result
6692     // against zero to select between true and false values.
6693     if (!RHS.getNode()) {
6694       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6695       CC = ISD::SETNE;
6696     }
6697   }
6698 
6699   // Also handle f16, for which we need to do a f32 comparison.
6700   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
6701     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
6702     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
6703   }
6704 
6705   // Next, handle integers.
6706   if (LHS.getValueType().isInteger()) {
6707     assert((LHS.getValueType() == RHS.getValueType()) &&
6708            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
6709 
6710     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
6711     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
6712     ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
6713     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
6714     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
6715     // supported types.
6716     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnesValue() && CTVal && CFVal &&
6717         CTVal->isOne() && CFVal->isAllOnesValue() &&
6718         LHS.getValueType() == TVal.getValueType()) {
6719       EVT VT = LHS.getValueType();
6720       SDValue Shift =
6721           DAG.getNode(ISD::SRA, dl, VT, LHS,
6722                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
6723       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
6724     }
6725 
6726     unsigned Opcode = AArch64ISD::CSEL;
6727 
6728     // If both the TVal and the FVal are constants, see if we can swap them in
6729     // order to for a CSINV or CSINC out of them.
6730     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
6731       std::swap(TVal, FVal);
6732       std::swap(CTVal, CFVal);
6733       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6734     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
6735       std::swap(TVal, FVal);
6736       std::swap(CTVal, CFVal);
6737       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6738     } else if (TVal.getOpcode() == ISD::XOR) {
6739       // If TVal is a NOT we want to swap TVal and FVal so that we can match
6740       // with a CSINV rather than a CSEL.
6741       if (isAllOnesConstant(TVal.getOperand(1))) {
6742         std::swap(TVal, FVal);
6743         std::swap(CTVal, CFVal);
6744         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6745       }
6746     } else if (TVal.getOpcode() == ISD::SUB) {
6747       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
6748       // that we can match with a CSNEG rather than a CSEL.
6749       if (isNullConstant(TVal.getOperand(0))) {
6750         std::swap(TVal, FVal);
6751         std::swap(CTVal, CFVal);
6752         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6753       }
6754     } else if (CTVal && CFVal) {
6755       const int64_t TrueVal = CTVal->getSExtValue();
6756       const int64_t FalseVal = CFVal->getSExtValue();
6757       bool Swap = false;
6758 
6759       // If both TVal and FVal are constants, see if FVal is the
6760       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
6761       // instead of a CSEL in that case.
6762       if (TrueVal == ~FalseVal) {
6763         Opcode = AArch64ISD::CSINV;
6764       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
6765                  TrueVal == -FalseVal) {
6766         Opcode = AArch64ISD::CSNEG;
6767       } else if (TVal.getValueType() == MVT::i32) {
6768         // If our operands are only 32-bit wide, make sure we use 32-bit
6769         // arithmetic for the check whether we can use CSINC. This ensures that
6770         // the addition in the check will wrap around properly in case there is
6771         // an overflow (which would not be the case if we do the check with
6772         // 64-bit arithmetic).
6773         const uint32_t TrueVal32 = CTVal->getZExtValue();
6774         const uint32_t FalseVal32 = CFVal->getZExtValue();
6775 
6776         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
6777           Opcode = AArch64ISD::CSINC;
6778 
6779           if (TrueVal32 > FalseVal32) {
6780             Swap = true;
6781           }
6782         }
6783         // 64-bit check whether we can use CSINC.
6784       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
6785         Opcode = AArch64ISD::CSINC;
6786 
6787         if (TrueVal > FalseVal) {
6788           Swap = true;
6789         }
6790       }
6791 
6792       // Swap TVal and FVal if necessary.
6793       if (Swap) {
6794         std::swap(TVal, FVal);
6795         std::swap(CTVal, CFVal);
6796         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6797       }
6798 
6799       if (Opcode != AArch64ISD::CSEL) {
6800         // Drop FVal since we can get its value by simply inverting/negating
6801         // TVal.
6802         FVal = TVal;
6803       }
6804     }
6805 
6806     // Avoid materializing a constant when possible by reusing a known value in
6807     // a register.  However, don't perform this optimization if the known value
6808     // is one, zero or negative one in the case of a CSEL.  We can always
6809     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
6810     // FVal, respectively.
6811     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
6812     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
6813         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
6814       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6815       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
6816       // "a != C ? x : a" to avoid materializing C.
6817       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
6818         TVal = LHS;
6819       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
6820         FVal = LHS;
6821     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
6822       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
6823       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
6824       // avoid materializing C.
6825       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6826       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
6827         Opcode = AArch64ISD::CSINV;
6828         TVal = LHS;
6829         FVal = DAG.getConstant(0, dl, FVal.getValueType());
6830       }
6831     }
6832 
6833     SDValue CCVal;
6834     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6835     EVT VT = TVal.getValueType();
6836     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
6837   }
6838 
6839   // Now we know we're dealing with FP values.
6840   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6841          LHS.getValueType() == MVT::f64);
6842   assert(LHS.getValueType() == RHS.getValueType());
6843   EVT VT = TVal.getValueType();
6844   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6845 
6846   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6847   // clean.  Some of them require two CSELs to implement.
6848   AArch64CC::CondCode CC1, CC2;
6849   changeFPCCToAArch64CC(CC, CC1, CC2);
6850 
6851   if (DAG.getTarget().Options.UnsafeFPMath) {
6852     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
6853     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
6854     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
6855     if (RHSVal && RHSVal->isZero()) {
6856       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
6857       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
6858 
6859       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
6860           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
6861         TVal = LHS;
6862       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
6863                CFVal && CFVal->isZero() &&
6864                FVal.getValueType() == LHS.getValueType())
6865         FVal = LHS;
6866     }
6867   }
6868 
6869   // Emit first, and possibly only, CSEL.
6870   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6871   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6872 
6873   // If we need a second CSEL, emit it, using the output of the first as the
6874   // RHS.  We're effectively OR'ing the two CC's together.
6875   if (CC2 != AArch64CC::AL) {
6876     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6877     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6878   }
6879 
6880   // Otherwise, return the output of the first CSEL.
6881   return CS1;
6882 }
6883 
6884 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
6885                                               SelectionDAG &DAG) const {
6886   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6887   SDValue LHS = Op.getOperand(0);
6888   SDValue RHS = Op.getOperand(1);
6889   SDValue TVal = Op.getOperand(2);
6890   SDValue FVal = Op.getOperand(3);
6891   SDLoc DL(Op);
6892   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6893 }
6894 
6895 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
6896                                            SelectionDAG &DAG) const {
6897   SDValue CCVal = Op->getOperand(0);
6898   SDValue TVal = Op->getOperand(1);
6899   SDValue FVal = Op->getOperand(2);
6900   SDLoc DL(Op);
6901 
6902   EVT Ty = Op.getValueType();
6903   if (Ty.isScalableVector()) {
6904     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
6905     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
6906     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
6907     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
6908   }
6909 
6910   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
6911   // instruction.
6912   if (ISD::isOverflowIntrOpRes(CCVal)) {
6913     // Only lower legal XALUO ops.
6914     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
6915       return SDValue();
6916 
6917     AArch64CC::CondCode OFCC;
6918     SDValue Value, Overflow;
6919     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
6920     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
6921 
6922     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
6923                        CCVal, Overflow);
6924   }
6925 
6926   // Lower it the same way as we would lower a SELECT_CC node.
6927   ISD::CondCode CC;
6928   SDValue LHS, RHS;
6929   if (CCVal.getOpcode() == ISD::SETCC) {
6930     LHS = CCVal.getOperand(0);
6931     RHS = CCVal.getOperand(1);
6932     CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
6933   } else {
6934     LHS = CCVal;
6935     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
6936     CC = ISD::SETNE;
6937   }
6938   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6939 }
6940 
6941 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
6942                                               SelectionDAG &DAG) const {
6943   // Jump table entries as PC relative offsets. No additional tweaking
6944   // is necessary here. Just get the address of the jump table.
6945   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6946 
6947   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6948       !Subtarget->isTargetMachO()) {
6949     return getAddrLarge(JT, DAG);
6950   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6951     return getAddrTiny(JT, DAG);
6952   }
6953   return getAddr(JT, DAG);
6954 }
6955 
6956 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
6957                                           SelectionDAG &DAG) const {
6958   // Jump table entries as PC relative offsets. No additional tweaking
6959   // is necessary here. Just get the address of the jump table.
6960   SDLoc DL(Op);
6961   SDValue JT = Op.getOperand(1);
6962   SDValue Entry = Op.getOperand(2);
6963   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
6964 
6965   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6966   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
6967 
6968   SDNode *Dest =
6969       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
6970                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
6971   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
6972                      SDValue(Dest, 0));
6973 }
6974 
6975 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6976                                                  SelectionDAG &DAG) const {
6977   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6978 
6979   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6980     // Use the GOT for the large code model on iOS.
6981     if (Subtarget->isTargetMachO()) {
6982       return getGOT(CP, DAG);
6983     }
6984     return getAddrLarge(CP, DAG);
6985   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6986     return getAddrTiny(CP, DAG);
6987   } else {
6988     return getAddr(CP, DAG);
6989   }
6990 }
6991 
6992 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6993                                                SelectionDAG &DAG) const {
6994   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6995   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6996       !Subtarget->isTargetMachO()) {
6997     return getAddrLarge(BA, DAG);
6998   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6999     return getAddrTiny(BA, DAG);
7000   }
7001   return getAddr(BA, DAG);
7002 }
7003 
7004 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
7005                                                  SelectionDAG &DAG) const {
7006   AArch64FunctionInfo *FuncInfo =
7007       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7008 
7009   SDLoc DL(Op);
7010   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
7011                                  getPointerTy(DAG.getDataLayout()));
7012   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
7013   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7014   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7015                       MachinePointerInfo(SV));
7016 }
7017 
7018 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
7019                                                   SelectionDAG &DAG) const {
7020   AArch64FunctionInfo *FuncInfo =
7021       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7022 
7023   SDLoc DL(Op);
7024   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
7025                                      ? FuncInfo->getVarArgsGPRIndex()
7026                                      : FuncInfo->getVarArgsStackIndex(),
7027                                  getPointerTy(DAG.getDataLayout()));
7028   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7029   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7030                       MachinePointerInfo(SV));
7031 }
7032 
7033 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
7034                                                   SelectionDAG &DAG) const {
7035   // The layout of the va_list struct is specified in the AArch64 Procedure Call
7036   // Standard, section B.3.
7037   MachineFunction &MF = DAG.getMachineFunction();
7038   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7039   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
7040   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
7041   auto PtrVT = getPointerTy(DAG.getDataLayout());
7042   SDLoc DL(Op);
7043 
7044   SDValue Chain = Op.getOperand(0);
7045   SDValue VAList = Op.getOperand(1);
7046   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7047   SmallVector<SDValue, 4> MemOps;
7048 
7049   // void *__stack at offset 0
7050   unsigned Offset = 0;
7051   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
7052   Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
7053   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
7054                                 MachinePointerInfo(SV), Align(PtrSize)));
7055 
7056   // void *__gr_top at offset 8 (4 on ILP32)
7057   Offset += PtrSize;
7058   int GPRSize = FuncInfo->getVarArgsGPRSize();
7059   if (GPRSize > 0) {
7060     SDValue GRTop, GRTopAddr;
7061 
7062     GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7063                             DAG.getConstant(Offset, DL, PtrVT));
7064 
7065     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
7066     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
7067                         DAG.getConstant(GPRSize, DL, PtrVT));
7068     GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
7069 
7070     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
7071                                   MachinePointerInfo(SV, Offset),
7072                                   Align(PtrSize)));
7073   }
7074 
7075   // void *__vr_top at offset 16 (8 on ILP32)
7076   Offset += PtrSize;
7077   int FPRSize = FuncInfo->getVarArgsFPRSize();
7078   if (FPRSize > 0) {
7079     SDValue VRTop, VRTopAddr;
7080     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7081                             DAG.getConstant(Offset, DL, PtrVT));
7082 
7083     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
7084     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
7085                         DAG.getConstant(FPRSize, DL, PtrVT));
7086     VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
7087 
7088     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
7089                                   MachinePointerInfo(SV, Offset),
7090                                   Align(PtrSize)));
7091   }
7092 
7093   // int __gr_offs at offset 24 (12 on ILP32)
7094   Offset += PtrSize;
7095   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7096                                    DAG.getConstant(Offset, DL, PtrVT));
7097   MemOps.push_back(
7098       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
7099                    GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7100 
7101   // int __vr_offs at offset 28 (16 on ILP32)
7102   Offset += 4;
7103   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7104                                    DAG.getConstant(Offset, DL, PtrVT));
7105   MemOps.push_back(
7106       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
7107                    VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7108 
7109   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
7110 }
7111 
7112 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
7113                                             SelectionDAG &DAG) const {
7114   MachineFunction &MF = DAG.getMachineFunction();
7115 
7116   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
7117     return LowerWin64_VASTART(Op, DAG);
7118   else if (Subtarget->isTargetDarwin())
7119     return LowerDarwin_VASTART(Op, DAG);
7120   else
7121     return LowerAAPCS_VASTART(Op, DAG);
7122 }
7123 
7124 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
7125                                            SelectionDAG &DAG) const {
7126   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
7127   // pointer.
7128   SDLoc DL(Op);
7129   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
7130   unsigned VaListSize =
7131       (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
7132           ? PtrSize
7133           : Subtarget->isTargetILP32() ? 20 : 32;
7134   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7135   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7136 
7137   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
7138                        DAG.getConstant(VaListSize, DL, MVT::i32),
7139                        Align(PtrSize), false, false, false,
7140                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
7141 }
7142 
7143 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7144   assert(Subtarget->isTargetDarwin() &&
7145          "automatic va_arg instruction only works on Darwin");
7146 
7147   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7148   EVT VT = Op.getValueType();
7149   SDLoc DL(Op);
7150   SDValue Chain = Op.getOperand(0);
7151   SDValue Addr = Op.getOperand(1);
7152   MaybeAlign Align(Op.getConstantOperandVal(3));
7153   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
7154   auto PtrVT = getPointerTy(DAG.getDataLayout());
7155   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
7156   SDValue VAList =
7157       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
7158   Chain = VAList.getValue(1);
7159   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
7160 
7161   if (VT.isScalableVector())
7162     report_fatal_error("Passing SVE types to variadic functions is "
7163                        "currently not supported");
7164 
7165   if (Align && *Align > MinSlotSize) {
7166     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7167                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
7168     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
7169                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
7170   }
7171 
7172   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7173   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
7174 
7175   // Scalar integer and FP values smaller than 64 bits are implicitly extended
7176   // up to 64 bits.  At the very least, we have to increase the striding of the
7177   // vaargs list to match this, and for FP values we need to introduce
7178   // FP_ROUND nodes as well.
7179   if (VT.isInteger() && !VT.isVector())
7180     ArgSize = std::max(ArgSize, MinSlotSize);
7181   bool NeedFPTrunc = false;
7182   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
7183     ArgSize = 8;
7184     NeedFPTrunc = true;
7185   }
7186 
7187   // Increment the pointer, VAList, to the next vaarg
7188   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7189                                DAG.getConstant(ArgSize, DL, PtrVT));
7190   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
7191 
7192   // Store the incremented VAList to the legalized pointer
7193   SDValue APStore =
7194       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
7195 
7196   // Load the actual argument out of the pointer VAList
7197   if (NeedFPTrunc) {
7198     // Load the value as an f64.
7199     SDValue WideFP =
7200         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
7201     // Round the value down to an f32.
7202     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
7203                                    DAG.getIntPtrConstant(1, DL));
7204     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
7205     // Merge the rounded value with the chain output of the load.
7206     return DAG.getMergeValues(Ops, DL);
7207   }
7208 
7209   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
7210 }
7211 
7212 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
7213                                               SelectionDAG &DAG) const {
7214   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7215   MFI.setFrameAddressIsTaken(true);
7216 
7217   EVT VT = Op.getValueType();
7218   SDLoc DL(Op);
7219   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7220   SDValue FrameAddr =
7221       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
7222   while (Depth--)
7223     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
7224                             MachinePointerInfo());
7225 
7226   if (Subtarget->isTargetILP32())
7227     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
7228                             DAG.getValueType(VT));
7229 
7230   return FrameAddr;
7231 }
7232 
7233 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
7234                                               SelectionDAG &DAG) const {
7235   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7236 
7237   EVT VT = getPointerTy(DAG.getDataLayout());
7238   SDLoc DL(Op);
7239   int FI = MFI.CreateFixedObject(4, 0, false);
7240   return DAG.getFrameIndex(FI, VT);
7241 }
7242 
7243 #define GET_REGISTER_MATCHER
7244 #include "AArch64GenAsmMatcher.inc"
7245 
7246 // FIXME? Maybe this could be a TableGen attribute on some registers and
7247 // this table could be generated automatically from RegInfo.
7248 Register AArch64TargetLowering::
7249 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
7250   Register Reg = MatchRegisterName(RegName);
7251   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
7252     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
7253     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
7254     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
7255       Reg = 0;
7256   }
7257   if (Reg)
7258     return Reg;
7259   report_fatal_error(Twine("Invalid register name \""
7260                               + StringRef(RegName)  + "\"."));
7261 }
7262 
7263 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
7264                                                      SelectionDAG &DAG) const {
7265   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
7266 
7267   EVT VT = Op.getValueType();
7268   SDLoc DL(Op);
7269 
7270   SDValue FrameAddr =
7271       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
7272   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
7273 
7274   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
7275 }
7276 
7277 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
7278                                                SelectionDAG &DAG) const {
7279   MachineFunction &MF = DAG.getMachineFunction();
7280   MachineFrameInfo &MFI = MF.getFrameInfo();
7281   MFI.setReturnAddressIsTaken(true);
7282 
7283   EVT VT = Op.getValueType();
7284   SDLoc DL(Op);
7285   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7286   SDValue ReturnAddress;
7287   if (Depth) {
7288     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7289     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
7290     ReturnAddress = DAG.getLoad(
7291         VT, DL, DAG.getEntryNode(),
7292         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
7293   } else {
7294     // Return LR, which contains the return address. Mark it an implicit
7295     // live-in.
7296     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
7297     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
7298   }
7299 
7300   // The XPACLRI instruction assembles to a hint-space instruction before
7301   // Armv8.3-A therefore this instruction can be safely used for any pre
7302   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
7303   // that instead.
7304   SDNode *St;
7305   if (Subtarget->hasPAuth()) {
7306     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
7307   } else {
7308     // XPACLRI operates on LR therefore we must move the operand accordingly.
7309     SDValue Chain =
7310         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
7311     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
7312   }
7313   return SDValue(St, 0);
7314 }
7315 
7316 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
7317 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
7318 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
7319                                                     SelectionDAG &DAG) const {
7320   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7321   EVT VT = Op.getValueType();
7322   unsigned VTBits = VT.getSizeInBits();
7323   SDLoc dl(Op);
7324   SDValue ShOpLo = Op.getOperand(0);
7325   SDValue ShOpHi = Op.getOperand(1);
7326   SDValue ShAmt = Op.getOperand(2);
7327   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
7328 
7329   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
7330 
7331   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
7332                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
7333   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
7334 
7335   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
7336   // is "undef". We wanted 0, so CSEL it directly.
7337   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
7338                                ISD::SETEQ, dl, DAG);
7339   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
7340   HiBitsForLo =
7341       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
7342                   HiBitsForLo, CCVal, Cmp);
7343 
7344   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
7345                                    DAG.getConstant(VTBits, dl, MVT::i64));
7346 
7347   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
7348   SDValue LoForNormalShift =
7349       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
7350 
7351   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
7352                        dl, DAG);
7353   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
7354   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
7355   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
7356                            LoForNormalShift, CCVal, Cmp);
7357 
7358   // AArch64 shifts larger than the register width are wrapped rather than
7359   // clamped, so we can't just emit "hi >> x".
7360   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
7361   SDValue HiForBigShift =
7362       Opc == ISD::SRA
7363           ? DAG.getNode(Opc, dl, VT, ShOpHi,
7364                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
7365           : DAG.getConstant(0, dl, VT);
7366   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
7367                            HiForNormalShift, CCVal, Cmp);
7368 
7369   SDValue Ops[2] = { Lo, Hi };
7370   return DAG.getMergeValues(Ops, dl);
7371 }
7372 
7373 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
7374 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
7375 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
7376                                                    SelectionDAG &DAG) const {
7377   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7378   EVT VT = Op.getValueType();
7379   unsigned VTBits = VT.getSizeInBits();
7380   SDLoc dl(Op);
7381   SDValue ShOpLo = Op.getOperand(0);
7382   SDValue ShOpHi = Op.getOperand(1);
7383   SDValue ShAmt = Op.getOperand(2);
7384 
7385   assert(Op.getOpcode() == ISD::SHL_PARTS);
7386   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
7387                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
7388   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
7389 
7390   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
7391   // is "undef". We wanted 0, so CSEL it directly.
7392   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
7393                                ISD::SETEQ, dl, DAG);
7394   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
7395   LoBitsForHi =
7396       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
7397                   LoBitsForHi, CCVal, Cmp);
7398 
7399   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
7400                                    DAG.getConstant(VTBits, dl, MVT::i64));
7401   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
7402   SDValue HiForNormalShift =
7403       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
7404 
7405   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
7406 
7407   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
7408                        dl, DAG);
7409   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
7410   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
7411                            HiForNormalShift, CCVal, Cmp);
7412 
7413   // AArch64 shifts of larger than register sizes are wrapped rather than
7414   // clamped, so we can't just emit "lo << a" if a is too big.
7415   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
7416   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7417   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
7418                            LoForNormalShift, CCVal, Cmp);
7419 
7420   SDValue Ops[2] = { Lo, Hi };
7421   return DAG.getMergeValues(Ops, dl);
7422 }
7423 
7424 bool AArch64TargetLowering::isOffsetFoldingLegal(
7425     const GlobalAddressSDNode *GA) const {
7426   // Offsets are folded in the DAG combine rather than here so that we can
7427   // intelligently choose an offset based on the uses.
7428   return false;
7429 }
7430 
7431 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
7432                                          bool OptForSize) const {
7433   bool IsLegal = false;
7434   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
7435   // 16-bit case when target has full fp16 support.
7436   // FIXME: We should be able to handle f128 as well with a clever lowering.
7437   const APInt ImmInt = Imm.bitcastToAPInt();
7438   if (VT == MVT::f64)
7439     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
7440   else if (VT == MVT::f32)
7441     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
7442   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
7443     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
7444   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
7445   //       generate that fmov.
7446 
7447   // If we can not materialize in immediate field for fmov, check if the
7448   // value can be encoded as the immediate operand of a logical instruction.
7449   // The immediate value will be created with either MOVZ, MOVN, or ORR.
7450   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
7451     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
7452     // however the mov+fmov sequence is always better because of the reduced
7453     // cache pressure. The timings are still the same if you consider
7454     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
7455     // movw+movk is fused). So we limit up to 2 instrdduction at most.
7456     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
7457     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
7458 			      Insn);
7459     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
7460     IsLegal = Insn.size() <= Limit;
7461   }
7462 
7463   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
7464                     << " imm value: "; Imm.dump(););
7465   return IsLegal;
7466 }
7467 
7468 //===----------------------------------------------------------------------===//
7469 //                          AArch64 Optimization Hooks
7470 //===----------------------------------------------------------------------===//
7471 
7472 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
7473                            SDValue Operand, SelectionDAG &DAG,
7474                            int &ExtraSteps) {
7475   EVT VT = Operand.getValueType();
7476   if (ST->hasNEON() &&
7477       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
7478        VT == MVT::f32 || VT == MVT::v1f32 ||
7479        VT == MVT::v2f32 || VT == MVT::v4f32)) {
7480     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
7481       // For the reciprocal estimates, convergence is quadratic, so the number
7482       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
7483       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
7484       // the result for float (23 mantissa bits) is 2 and for double (52
7485       // mantissa bits) is 3.
7486       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
7487 
7488     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
7489   }
7490 
7491   return SDValue();
7492 }
7493 
7494 SDValue
7495 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
7496                                         const DenormalMode &Mode) const {
7497   SDLoc DL(Op);
7498   EVT VT = Op.getValueType();
7499   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7500   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7501   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
7502 }
7503 
7504 SDValue
7505 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
7506                                                    SelectionDAG &DAG) const {
7507   return Op;
7508 }
7509 
7510 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
7511                                                SelectionDAG &DAG, int Enabled,
7512                                                int &ExtraSteps,
7513                                                bool &UseOneConst,
7514                                                bool Reciprocal) const {
7515   if (Enabled == ReciprocalEstimate::Enabled ||
7516       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
7517     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
7518                                        DAG, ExtraSteps)) {
7519       SDLoc DL(Operand);
7520       EVT VT = Operand.getValueType();
7521 
7522       SDNodeFlags Flags;
7523       Flags.setAllowReassociation(true);
7524 
7525       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
7526       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
7527       for (int i = ExtraSteps; i > 0; --i) {
7528         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
7529                                    Flags);
7530         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
7531         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
7532       }
7533       if (!Reciprocal)
7534         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
7535 
7536       ExtraSteps = 0;
7537       return Estimate;
7538     }
7539 
7540   return SDValue();
7541 }
7542 
7543 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
7544                                                 SelectionDAG &DAG, int Enabled,
7545                                                 int &ExtraSteps) const {
7546   if (Enabled == ReciprocalEstimate::Enabled)
7547     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
7548                                        DAG, ExtraSteps)) {
7549       SDLoc DL(Operand);
7550       EVT VT = Operand.getValueType();
7551 
7552       SDNodeFlags Flags;
7553       Flags.setAllowReassociation(true);
7554 
7555       // Newton reciprocal iteration: E * (2 - X * E)
7556       // AArch64 reciprocal iteration instruction: (2 - M * N)
7557       for (int i = ExtraSteps; i > 0; --i) {
7558         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
7559                                    Estimate, Flags);
7560         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
7561       }
7562 
7563       ExtraSteps = 0;
7564       return Estimate;
7565     }
7566 
7567   return SDValue();
7568 }
7569 
7570 //===----------------------------------------------------------------------===//
7571 //                          AArch64 Inline Assembly Support
7572 //===----------------------------------------------------------------------===//
7573 
7574 // Table of Constraints
7575 // TODO: This is the current set of constraints supported by ARM for the
7576 // compiler, not all of them may make sense.
7577 //
7578 // r - A general register
7579 // w - An FP/SIMD register of some size in the range v0-v31
7580 // x - An FP/SIMD register of some size in the range v0-v15
7581 // I - Constant that can be used with an ADD instruction
7582 // J - Constant that can be used with a SUB instruction
7583 // K - Constant that can be used with a 32-bit logical instruction
7584 // L - Constant that can be used with a 64-bit logical instruction
7585 // M - Constant that can be used as a 32-bit MOV immediate
7586 // N - Constant that can be used as a 64-bit MOV immediate
7587 // Q - A memory reference with base register and no offset
7588 // S - A symbolic address
7589 // Y - Floating point constant zero
7590 // Z - Integer constant zero
7591 //
7592 //   Note that general register operands will be output using their 64-bit x
7593 // register name, whatever the size of the variable, unless the asm operand
7594 // is prefixed by the %w modifier. Floating-point and SIMD register operands
7595 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
7596 // %q modifier.
7597 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
7598   // At this point, we have to lower this constraint to something else, so we
7599   // lower it to an "r" or "w". However, by doing this we will force the result
7600   // to be in register, while the X constraint is much more permissive.
7601   //
7602   // Although we are correct (we are free to emit anything, without
7603   // constraints), we might break use cases that would expect us to be more
7604   // efficient and emit something else.
7605   if (!Subtarget->hasFPARMv8())
7606     return "r";
7607 
7608   if (ConstraintVT.isFloatingPoint())
7609     return "w";
7610 
7611   if (ConstraintVT.isVector() &&
7612      (ConstraintVT.getSizeInBits() == 64 ||
7613       ConstraintVT.getSizeInBits() == 128))
7614     return "w";
7615 
7616   return "r";
7617 }
7618 
7619 enum PredicateConstraint {
7620   Upl,
7621   Upa,
7622   Invalid
7623 };
7624 
7625 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
7626   PredicateConstraint P = PredicateConstraint::Invalid;
7627   if (Constraint == "Upa")
7628     P = PredicateConstraint::Upa;
7629   if (Constraint == "Upl")
7630     P = PredicateConstraint::Upl;
7631   return P;
7632 }
7633 
7634 /// getConstraintType - Given a constraint letter, return the type of
7635 /// constraint it is for this target.
7636 AArch64TargetLowering::ConstraintType
7637 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
7638   if (Constraint.size() == 1) {
7639     switch (Constraint[0]) {
7640     default:
7641       break;
7642     case 'x':
7643     case 'w':
7644     case 'y':
7645       return C_RegisterClass;
7646     // An address with a single base register. Due to the way we
7647     // currently handle addresses it is the same as 'r'.
7648     case 'Q':
7649       return C_Memory;
7650     case 'I':
7651     case 'J':
7652     case 'K':
7653     case 'L':
7654     case 'M':
7655     case 'N':
7656     case 'Y':
7657     case 'Z':
7658       return C_Immediate;
7659     case 'z':
7660     case 'S': // A symbolic address
7661       return C_Other;
7662     }
7663   } else if (parsePredicateConstraint(Constraint) !=
7664              PredicateConstraint::Invalid)
7665       return C_RegisterClass;
7666   return TargetLowering::getConstraintType(Constraint);
7667 }
7668 
7669 /// Examine constraint type and operand type and determine a weight value.
7670 /// This object must already have been set up with the operand type
7671 /// and the current alternative constraint selected.
7672 TargetLowering::ConstraintWeight
7673 AArch64TargetLowering::getSingleConstraintMatchWeight(
7674     AsmOperandInfo &info, const char *constraint) const {
7675   ConstraintWeight weight = CW_Invalid;
7676   Value *CallOperandVal = info.CallOperandVal;
7677   // If we don't have a value, we can't do a match,
7678   // but allow it at the lowest weight.
7679   if (!CallOperandVal)
7680     return CW_Default;
7681   Type *type = CallOperandVal->getType();
7682   // Look at the constraint type.
7683   switch (*constraint) {
7684   default:
7685     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7686     break;
7687   case 'x':
7688   case 'w':
7689   case 'y':
7690     if (type->isFloatingPointTy() || type->isVectorTy())
7691       weight = CW_Register;
7692     break;
7693   case 'z':
7694     weight = CW_Constant;
7695     break;
7696   case 'U':
7697     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
7698       weight = CW_Register;
7699     break;
7700   }
7701   return weight;
7702 }
7703 
7704 std::pair<unsigned, const TargetRegisterClass *>
7705 AArch64TargetLowering::getRegForInlineAsmConstraint(
7706     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
7707   if (Constraint.size() == 1) {
7708     switch (Constraint[0]) {
7709     case 'r':
7710       if (VT.isScalableVector())
7711         return std::make_pair(0U, nullptr);
7712       if (VT.getFixedSizeInBits() == 64)
7713         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
7714       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
7715     case 'w': {
7716       if (!Subtarget->hasFPARMv8())
7717         break;
7718       if (VT.isScalableVector()) {
7719         if (VT.getVectorElementType() != MVT::i1)
7720           return std::make_pair(0U, &AArch64::ZPRRegClass);
7721         return std::make_pair(0U, nullptr);
7722       }
7723       uint64_t VTSize = VT.getFixedSizeInBits();
7724       if (VTSize == 16)
7725         return std::make_pair(0U, &AArch64::FPR16RegClass);
7726       if (VTSize == 32)
7727         return std::make_pair(0U, &AArch64::FPR32RegClass);
7728       if (VTSize == 64)
7729         return std::make_pair(0U, &AArch64::FPR64RegClass);
7730       if (VTSize == 128)
7731         return std::make_pair(0U, &AArch64::FPR128RegClass);
7732       break;
7733     }
7734     // The instructions that this constraint is designed for can
7735     // only take 128-bit registers so just use that regclass.
7736     case 'x':
7737       if (!Subtarget->hasFPARMv8())
7738         break;
7739       if (VT.isScalableVector())
7740         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
7741       if (VT.getSizeInBits() == 128)
7742         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
7743       break;
7744     case 'y':
7745       if (!Subtarget->hasFPARMv8())
7746         break;
7747       if (VT.isScalableVector())
7748         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
7749       break;
7750     }
7751   } else {
7752     PredicateConstraint PC = parsePredicateConstraint(Constraint);
7753     if (PC != PredicateConstraint::Invalid) {
7754       if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
7755         return std::make_pair(0U, nullptr);
7756       bool restricted = (PC == PredicateConstraint::Upl);
7757       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
7758                         : std::make_pair(0U, &AArch64::PPRRegClass);
7759     }
7760   }
7761   if (StringRef("{cc}").equals_lower(Constraint))
7762     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
7763 
7764   // Use the default implementation in TargetLowering to convert the register
7765   // constraint into a member of a register class.
7766   std::pair<unsigned, const TargetRegisterClass *> Res;
7767   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7768 
7769   // Not found as a standard register?
7770   if (!Res.second) {
7771     unsigned Size = Constraint.size();
7772     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
7773         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
7774       int RegNo;
7775       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
7776       if (!Failed && RegNo >= 0 && RegNo <= 31) {
7777         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
7778         // By default we'll emit v0-v31 for this unless there's a modifier where
7779         // we'll emit the correct register as well.
7780         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
7781           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
7782           Res.second = &AArch64::FPR64RegClass;
7783         } else {
7784           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
7785           Res.second = &AArch64::FPR128RegClass;
7786         }
7787       }
7788     }
7789   }
7790 
7791   if (Res.second && !Subtarget->hasFPARMv8() &&
7792       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
7793       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
7794     return std::make_pair(0U, nullptr);
7795 
7796   return Res;
7797 }
7798 
7799 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7800 /// vector.  If it is invalid, don't add anything to Ops.
7801 void AArch64TargetLowering::LowerAsmOperandForConstraint(
7802     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
7803     SelectionDAG &DAG) const {
7804   SDValue Result;
7805 
7806   // Currently only support length 1 constraints.
7807   if (Constraint.length() != 1)
7808     return;
7809 
7810   char ConstraintLetter = Constraint[0];
7811   switch (ConstraintLetter) {
7812   default:
7813     break;
7814 
7815   // This set of constraints deal with valid constants for various instructions.
7816   // Validate and return a target constant for them if we can.
7817   case 'z': {
7818     // 'z' maps to xzr or wzr so it needs an input of 0.
7819     if (!isNullConstant(Op))
7820       return;
7821 
7822     if (Op.getValueType() == MVT::i64)
7823       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
7824     else
7825       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
7826     break;
7827   }
7828   case 'S': {
7829     // An absolute symbolic address or label reference.
7830     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
7831       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
7832                                           GA->getValueType(0));
7833     } else if (const BlockAddressSDNode *BA =
7834                    dyn_cast<BlockAddressSDNode>(Op)) {
7835       Result =
7836           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
7837     } else if (const ExternalSymbolSDNode *ES =
7838                    dyn_cast<ExternalSymbolSDNode>(Op)) {
7839       Result =
7840           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
7841     } else
7842       return;
7843     break;
7844   }
7845 
7846   case 'I':
7847   case 'J':
7848   case 'K':
7849   case 'L':
7850   case 'M':
7851   case 'N':
7852     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7853     if (!C)
7854       return;
7855 
7856     // Grab the value and do some validation.
7857     uint64_t CVal = C->getZExtValue();
7858     switch (ConstraintLetter) {
7859     // The I constraint applies only to simple ADD or SUB immediate operands:
7860     // i.e. 0 to 4095 with optional shift by 12
7861     // The J constraint applies only to ADD or SUB immediates that would be
7862     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
7863     // instruction [or vice versa], in other words -1 to -4095 with optional
7864     // left shift by 12.
7865     case 'I':
7866       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
7867         break;
7868       return;
7869     case 'J': {
7870       uint64_t NVal = -C->getSExtValue();
7871       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
7872         CVal = C->getSExtValue();
7873         break;
7874       }
7875       return;
7876     }
7877     // The K and L constraints apply *only* to logical immediates, including
7878     // what used to be the MOVI alias for ORR (though the MOVI alias has now
7879     // been removed and MOV should be used). So these constraints have to
7880     // distinguish between bit patterns that are valid 32-bit or 64-bit
7881     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
7882     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
7883     // versa.
7884     case 'K':
7885       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7886         break;
7887       return;
7888     case 'L':
7889       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7890         break;
7891       return;
7892     // The M and N constraints are a superset of K and L respectively, for use
7893     // with the MOV (immediate) alias. As well as the logical immediates they
7894     // also match 32 or 64-bit immediates that can be loaded either using a
7895     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
7896     // (M) or 64-bit 0x1234000000000000 (N) etc.
7897     // As a note some of this code is liberally stolen from the asm parser.
7898     case 'M': {
7899       if (!isUInt<32>(CVal))
7900         return;
7901       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7902         break;
7903       if ((CVal & 0xFFFF) == CVal)
7904         break;
7905       if ((CVal & 0xFFFF0000ULL) == CVal)
7906         break;
7907       uint64_t NCVal = ~(uint32_t)CVal;
7908       if ((NCVal & 0xFFFFULL) == NCVal)
7909         break;
7910       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7911         break;
7912       return;
7913     }
7914     case 'N': {
7915       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7916         break;
7917       if ((CVal & 0xFFFFULL) == CVal)
7918         break;
7919       if ((CVal & 0xFFFF0000ULL) == CVal)
7920         break;
7921       if ((CVal & 0xFFFF00000000ULL) == CVal)
7922         break;
7923       if ((CVal & 0xFFFF000000000000ULL) == CVal)
7924         break;
7925       uint64_t NCVal = ~CVal;
7926       if ((NCVal & 0xFFFFULL) == NCVal)
7927         break;
7928       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7929         break;
7930       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
7931         break;
7932       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
7933         break;
7934       return;
7935     }
7936     default:
7937       return;
7938     }
7939 
7940     // All assembler immediates are 64-bit integers.
7941     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
7942     break;
7943   }
7944 
7945   if (Result.getNode()) {
7946     Ops.push_back(Result);
7947     return;
7948   }
7949 
7950   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7951 }
7952 
7953 //===----------------------------------------------------------------------===//
7954 //                     AArch64 Advanced SIMD Support
7955 //===----------------------------------------------------------------------===//
7956 
7957 /// WidenVector - Given a value in the V64 register class, produce the
7958 /// equivalent value in the V128 register class.
7959 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
7960   EVT VT = V64Reg.getValueType();
7961   unsigned NarrowSize = VT.getVectorNumElements();
7962   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7963   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
7964   SDLoc DL(V64Reg);
7965 
7966   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
7967                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
7968 }
7969 
7970 /// getExtFactor - Determine the adjustment factor for the position when
7971 /// generating an "extract from vector registers" instruction.
7972 static unsigned getExtFactor(SDValue &V) {
7973   EVT EltType = V.getValueType().getVectorElementType();
7974   return EltType.getSizeInBits() / 8;
7975 }
7976 
7977 /// NarrowVector - Given a value in the V128 register class, produce the
7978 /// equivalent value in the V64 register class.
7979 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
7980   EVT VT = V128Reg.getValueType();
7981   unsigned WideSize = VT.getVectorNumElements();
7982   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7983   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
7984   SDLoc DL(V128Reg);
7985 
7986   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
7987 }
7988 
7989 // Gather data to see if the operation can be modelled as a
7990 // shuffle in combination with VEXTs.
7991 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
7992                                                   SelectionDAG &DAG) const {
7993   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7994   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
7995   SDLoc dl(Op);
7996   EVT VT = Op.getValueType();
7997   assert(!VT.isScalableVector() &&
7998          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
7999   unsigned NumElts = VT.getVectorNumElements();
8000 
8001   struct ShuffleSourceInfo {
8002     SDValue Vec;
8003     unsigned MinElt;
8004     unsigned MaxElt;
8005 
8006     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8007     // be compatible with the shuffle we intend to construct. As a result
8008     // ShuffleVec will be some sliding window into the original Vec.
8009     SDValue ShuffleVec;
8010 
8011     // Code should guarantee that element i in Vec starts at element "WindowBase
8012     // + i * WindowScale in ShuffleVec".
8013     int WindowBase;
8014     int WindowScale;
8015 
8016     ShuffleSourceInfo(SDValue Vec)
8017       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
8018           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
8019 
8020     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8021   };
8022 
8023   // First gather all vectors used as an immediate source for this BUILD_VECTOR
8024   // node.
8025   SmallVector<ShuffleSourceInfo, 2> Sources;
8026   for (unsigned i = 0; i < NumElts; ++i) {
8027     SDValue V = Op.getOperand(i);
8028     if (V.isUndef())
8029       continue;
8030     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8031              !isa<ConstantSDNode>(V.getOperand(1))) {
8032       LLVM_DEBUG(
8033           dbgs() << "Reshuffle failed: "
8034                     "a shuffle can only come from building a vector from "
8035                     "various elements of other vectors, provided their "
8036                     "indices are constant\n");
8037       return SDValue();
8038     }
8039 
8040     // Add this element source to the list if it's not already there.
8041     SDValue SourceVec = V.getOperand(0);
8042     auto Source = find(Sources, SourceVec);
8043     if (Source == Sources.end())
8044       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8045 
8046     // Update the minimum and maximum lane number seen.
8047     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
8048     Source->MinElt = std::min(Source->MinElt, EltNo);
8049     Source->MaxElt = std::max(Source->MaxElt, EltNo);
8050   }
8051 
8052   if (Sources.size() > 2) {
8053     LLVM_DEBUG(
8054         dbgs() << "Reshuffle failed: currently only do something sane when at "
8055                   "most two source vectors are involved\n");
8056     return SDValue();
8057   }
8058 
8059   // Find out the smallest element size among result and two sources, and use
8060   // it as element size to build the shuffle_vector.
8061   EVT SmallestEltTy = VT.getVectorElementType();
8062   for (auto &Source : Sources) {
8063     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8064     if (SrcEltTy.bitsLT(SmallestEltTy)) {
8065       SmallestEltTy = SrcEltTy;
8066     }
8067   }
8068   unsigned ResMultiplier =
8069       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8070   uint64_t VTSize = VT.getFixedSizeInBits();
8071   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
8072   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8073 
8074   // If the source vector is too wide or too narrow, we may nevertheless be able
8075   // to construct a compatible shuffle either by concatenating it with UNDEF or
8076   // extracting a suitable range of elements.
8077   for (auto &Src : Sources) {
8078     EVT SrcVT = Src.ShuffleVec.getValueType();
8079 
8080     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8081     if (SrcVTSize == VTSize)
8082       continue;
8083 
8084     // This stage of the search produces a source with the same element type as
8085     // the original, but with a total width matching the BUILD_VECTOR output.
8086     EVT EltVT = SrcVT.getVectorElementType();
8087     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8088     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8089 
8090     if (SrcVTSize < VTSize) {
8091       assert(2 * SrcVTSize == VTSize);
8092       // We can pad out the smaller vector for free, so if it's part of a
8093       // shuffle...
8094       Src.ShuffleVec =
8095           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8096                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8097       continue;
8098     }
8099 
8100     if (SrcVTSize != 2 * VTSize) {
8101       LLVM_DEBUG(
8102           dbgs() << "Reshuffle failed: result vector too small to extract\n");
8103       return SDValue();
8104     }
8105 
8106     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8107       LLVM_DEBUG(
8108           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
8109       return SDValue();
8110     }
8111 
8112     if (Src.MinElt >= NumSrcElts) {
8113       // The extraction can just take the second half
8114       Src.ShuffleVec =
8115           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8116                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8117       Src.WindowBase = -NumSrcElts;
8118     } else if (Src.MaxElt < NumSrcElts) {
8119       // The extraction can just take the first half
8120       Src.ShuffleVec =
8121           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8122                       DAG.getConstant(0, dl, MVT::i64));
8123     } else {
8124       // An actual VEXT is needed
8125       SDValue VEXTSrc1 =
8126           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8127                       DAG.getConstant(0, dl, MVT::i64));
8128       SDValue VEXTSrc2 =
8129           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8130                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8131       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
8132 
8133       if (!SrcVT.is64BitVector()) {
8134         LLVM_DEBUG(
8135           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
8136                     "for SVE vectors.");
8137         return SDValue();
8138       }
8139 
8140       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
8141                                    VEXTSrc2,
8142                                    DAG.getConstant(Imm, dl, MVT::i32));
8143       Src.WindowBase = -Src.MinElt;
8144     }
8145   }
8146 
8147   // Another possible incompatibility occurs from the vector element types. We
8148   // can fix this by bitcasting the source vectors to the same type we intend
8149   // for the shuffle.
8150   for (auto &Src : Sources) {
8151     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8152     if (SrcEltTy == SmallestEltTy)
8153       continue;
8154     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8155     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
8156     Src.WindowScale =
8157         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8158     Src.WindowBase *= Src.WindowScale;
8159   }
8160 
8161   // Final sanity check before we try to actually produce a shuffle.
8162   LLVM_DEBUG(for (auto Src
8163                   : Sources)
8164                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
8165 
8166   // The stars all align, our next step is to produce the mask for the shuffle.
8167   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8168   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8169   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8170     SDValue Entry = Op.getOperand(i);
8171     if (Entry.isUndef())
8172       continue;
8173 
8174     auto Src = find(Sources, Entry.getOperand(0));
8175     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8176 
8177     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8178     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8179     // segment.
8180     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8181     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8182                                VT.getScalarSizeInBits());
8183     int LanesDefined = BitsDefined / BitsPerShuffleLane;
8184 
8185     // This source is expected to fill ResMultiplier lanes of the final shuffle,
8186     // starting at the appropriate offset.
8187     int *LaneMask = &Mask[i * ResMultiplier];
8188 
8189     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8190     ExtractBase += NumElts * (Src - Sources.begin());
8191     for (int j = 0; j < LanesDefined; ++j)
8192       LaneMask[j] = ExtractBase + j;
8193   }
8194 
8195   // Final check before we try to produce nonsense...
8196   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
8197     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
8198     return SDValue();
8199   }
8200 
8201   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8202   for (unsigned i = 0; i < Sources.size(); ++i)
8203     ShuffleOps[i] = Sources[i].ShuffleVec;
8204 
8205   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8206                                          ShuffleOps[1], Mask);
8207   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
8208 
8209   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
8210              dbgs() << "Reshuffle, creating node: "; V.dump(););
8211 
8212   return V;
8213 }
8214 
8215 // check if an EXT instruction can handle the shuffle mask when the
8216 // vector sources of the shuffle are the same.
8217 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
8218   unsigned NumElts = VT.getVectorNumElements();
8219 
8220   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
8221   if (M[0] < 0)
8222     return false;
8223 
8224   Imm = M[0];
8225 
8226   // If this is a VEXT shuffle, the immediate value is the index of the first
8227   // element.  The other shuffle indices must be the successive elements after
8228   // the first one.
8229   unsigned ExpectedElt = Imm;
8230   for (unsigned i = 1; i < NumElts; ++i) {
8231     // Increment the expected index.  If it wraps around, just follow it
8232     // back to index zero and keep going.
8233     ++ExpectedElt;
8234     if (ExpectedElt == NumElts)
8235       ExpectedElt = 0;
8236 
8237     if (M[i] < 0)
8238       continue; // ignore UNDEF indices
8239     if (ExpectedElt != static_cast<unsigned>(M[i]))
8240       return false;
8241   }
8242 
8243   return true;
8244 }
8245 
8246 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
8247 /// element width than the vector lane type. If that is the case the function
8248 /// returns true and writes the value of the DUP instruction lane operand into
8249 /// DupLaneOp
8250 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
8251                           unsigned &DupLaneOp) {
8252   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
8253          "Only possible block sizes for wide DUP are: 16, 32, 64");
8254 
8255   if (BlockSize <= VT.getScalarSizeInBits())
8256     return false;
8257   if (BlockSize % VT.getScalarSizeInBits() != 0)
8258     return false;
8259   if (VT.getSizeInBits() % BlockSize != 0)
8260     return false;
8261 
8262   size_t SingleVecNumElements = VT.getVectorNumElements();
8263   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
8264   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
8265 
8266   // We are looking for masks like
8267   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
8268   // might be replaced by 'undefined'. BlockIndices will eventually contain
8269   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
8270   // for the above examples)
8271   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
8272   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
8273     for (size_t I = 0; I < NumEltsPerBlock; I++) {
8274       int Elt = M[BlockIndex * NumEltsPerBlock + I];
8275       if (Elt < 0)
8276         continue;
8277       // For now we don't support shuffles that use the second operand
8278       if ((unsigned)Elt >= SingleVecNumElements)
8279         return false;
8280       if (BlockElts[I] < 0)
8281         BlockElts[I] = Elt;
8282       else if (BlockElts[I] != Elt)
8283         return false;
8284     }
8285 
8286   // We found a candidate block (possibly with some undefs). It must be a
8287   // sequence of consecutive integers starting with a value divisible by
8288   // NumEltsPerBlock with some values possibly replaced by undef-s.
8289 
8290   // Find first non-undef element
8291   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
8292   assert(FirstRealEltIter != BlockElts.end() &&
8293          "Shuffle with all-undefs must have been caught by previous cases, "
8294          "e.g. isSplat()");
8295   if (FirstRealEltIter == BlockElts.end()) {
8296     DupLaneOp = 0;
8297     return true;
8298   }
8299 
8300   // Index of FirstRealElt in BlockElts
8301   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
8302 
8303   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
8304     return false;
8305   // BlockElts[0] must have the following value if it isn't undef:
8306   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
8307 
8308   // Check the first element
8309   if (Elt0 % NumEltsPerBlock != 0)
8310     return false;
8311   // Check that the sequence indeed consists of consecutive integers (modulo
8312   // undefs)
8313   for (size_t I = 0; I < NumEltsPerBlock; I++)
8314     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
8315       return false;
8316 
8317   DupLaneOp = Elt0 / NumEltsPerBlock;
8318   return true;
8319 }
8320 
8321 // check if an EXT instruction can handle the shuffle mask when the
8322 // vector sources of the shuffle are different.
8323 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
8324                       unsigned &Imm) {
8325   // Look for the first non-undef element.
8326   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
8327 
8328   // Benefit form APInt to handle overflow when calculating expected element.
8329   unsigned NumElts = VT.getVectorNumElements();
8330   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
8331   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
8332   // The following shuffle indices must be the successive elements after the
8333   // first real element.
8334   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
8335       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
8336   if (FirstWrongElt != M.end())
8337     return false;
8338 
8339   // The index of an EXT is the first element if it is not UNDEF.
8340   // Watch out for the beginning UNDEFs. The EXT index should be the expected
8341   // value of the first element.  E.g.
8342   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
8343   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
8344   // ExpectedElt is the last mask index plus 1.
8345   Imm = ExpectedElt.getZExtValue();
8346 
8347   // There are two difference cases requiring to reverse input vectors.
8348   // For example, for vector <4 x i32> we have the following cases,
8349   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
8350   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
8351   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
8352   // to reverse two input vectors.
8353   if (Imm < NumElts)
8354     ReverseEXT = true;
8355   else
8356     Imm -= NumElts;
8357 
8358   return true;
8359 }
8360 
8361 /// isREVMask - Check if a vector shuffle corresponds to a REV
8362 /// instruction with the specified blocksize.  (The order of the elements
8363 /// within each block of the vector is reversed.)
8364 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
8365   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
8366          "Only possible block sizes for REV are: 16, 32, 64");
8367 
8368   unsigned EltSz = VT.getScalarSizeInBits();
8369   if (EltSz == 64)
8370     return false;
8371 
8372   unsigned NumElts = VT.getVectorNumElements();
8373   unsigned BlockElts = M[0] + 1;
8374   // If the first shuffle index is UNDEF, be optimistic.
8375   if (M[0] < 0)
8376     BlockElts = BlockSize / EltSz;
8377 
8378   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
8379     return false;
8380 
8381   for (unsigned i = 0; i < NumElts; ++i) {
8382     if (M[i] < 0)
8383       continue; // ignore UNDEF indices
8384     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
8385       return false;
8386   }
8387 
8388   return true;
8389 }
8390 
8391 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8392   unsigned NumElts = VT.getVectorNumElements();
8393   if (NumElts % 2 != 0)
8394     return false;
8395   WhichResult = (M[0] == 0 ? 0 : 1);
8396   unsigned Idx = WhichResult * NumElts / 2;
8397   for (unsigned i = 0; i != NumElts; i += 2) {
8398     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
8399         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
8400       return false;
8401     Idx += 1;
8402   }
8403 
8404   return true;
8405 }
8406 
8407 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8408   unsigned NumElts = VT.getVectorNumElements();
8409   WhichResult = (M[0] == 0 ? 0 : 1);
8410   for (unsigned i = 0; i != NumElts; ++i) {
8411     if (M[i] < 0)
8412       continue; // ignore UNDEF indices
8413     if ((unsigned)M[i] != 2 * i + WhichResult)
8414       return false;
8415   }
8416 
8417   return true;
8418 }
8419 
8420 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8421   unsigned NumElts = VT.getVectorNumElements();
8422   if (NumElts % 2 != 0)
8423     return false;
8424   WhichResult = (M[0] == 0 ? 0 : 1);
8425   for (unsigned i = 0; i < NumElts; i += 2) {
8426     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
8427         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
8428       return false;
8429   }
8430   return true;
8431 }
8432 
8433 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
8434 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8435 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
8436 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8437   unsigned NumElts = VT.getVectorNumElements();
8438   if (NumElts % 2 != 0)
8439     return false;
8440   WhichResult = (M[0] == 0 ? 0 : 1);
8441   unsigned Idx = WhichResult * NumElts / 2;
8442   for (unsigned i = 0; i != NumElts; i += 2) {
8443     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
8444         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
8445       return false;
8446     Idx += 1;
8447   }
8448 
8449   return true;
8450 }
8451 
8452 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
8453 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8454 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
8455 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8456   unsigned Half = VT.getVectorNumElements() / 2;
8457   WhichResult = (M[0] == 0 ? 0 : 1);
8458   for (unsigned j = 0; j != 2; ++j) {
8459     unsigned Idx = WhichResult;
8460     for (unsigned i = 0; i != Half; ++i) {
8461       int MIdx = M[i + j * Half];
8462       if (MIdx >= 0 && (unsigned)MIdx != Idx)
8463         return false;
8464       Idx += 2;
8465     }
8466   }
8467 
8468   return true;
8469 }
8470 
8471 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
8472 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8473 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
8474 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8475   unsigned NumElts = VT.getVectorNumElements();
8476   if (NumElts % 2 != 0)
8477     return false;
8478   WhichResult = (M[0] == 0 ? 0 : 1);
8479   for (unsigned i = 0; i < NumElts; i += 2) {
8480     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
8481         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
8482       return false;
8483   }
8484   return true;
8485 }
8486 
8487 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
8488                       bool &DstIsLeft, int &Anomaly) {
8489   if (M.size() != static_cast<size_t>(NumInputElements))
8490     return false;
8491 
8492   int NumLHSMatch = 0, NumRHSMatch = 0;
8493   int LastLHSMismatch = -1, LastRHSMismatch = -1;
8494 
8495   for (int i = 0; i < NumInputElements; ++i) {
8496     if (M[i] == -1) {
8497       ++NumLHSMatch;
8498       ++NumRHSMatch;
8499       continue;
8500     }
8501 
8502     if (M[i] == i)
8503       ++NumLHSMatch;
8504     else
8505       LastLHSMismatch = i;
8506 
8507     if (M[i] == i + NumInputElements)
8508       ++NumRHSMatch;
8509     else
8510       LastRHSMismatch = i;
8511   }
8512 
8513   if (NumLHSMatch == NumInputElements - 1) {
8514     DstIsLeft = true;
8515     Anomaly = LastLHSMismatch;
8516     return true;
8517   } else if (NumRHSMatch == NumInputElements - 1) {
8518     DstIsLeft = false;
8519     Anomaly = LastRHSMismatch;
8520     return true;
8521   }
8522 
8523   return false;
8524 }
8525 
8526 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
8527   if (VT.getSizeInBits() != 128)
8528     return false;
8529 
8530   unsigned NumElts = VT.getVectorNumElements();
8531 
8532   for (int I = 0, E = NumElts / 2; I != E; I++) {
8533     if (Mask[I] != I)
8534       return false;
8535   }
8536 
8537   int Offset = NumElts / 2;
8538   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
8539     if (Mask[I] != I + SplitLHS * Offset)
8540       return false;
8541   }
8542 
8543   return true;
8544 }
8545 
8546 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
8547   SDLoc DL(Op);
8548   EVT VT = Op.getValueType();
8549   SDValue V0 = Op.getOperand(0);
8550   SDValue V1 = Op.getOperand(1);
8551   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
8552 
8553   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
8554       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
8555     return SDValue();
8556 
8557   bool SplitV0 = V0.getValueSizeInBits() == 128;
8558 
8559   if (!isConcatMask(Mask, VT, SplitV0))
8560     return SDValue();
8561 
8562   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8563   if (SplitV0) {
8564     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
8565                      DAG.getConstant(0, DL, MVT::i64));
8566   }
8567   if (V1.getValueSizeInBits() == 128) {
8568     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
8569                      DAG.getConstant(0, DL, MVT::i64));
8570   }
8571   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
8572 }
8573 
8574 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8575 /// the specified operations to build the shuffle.
8576 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8577                                       SDValue RHS, SelectionDAG &DAG,
8578                                       const SDLoc &dl) {
8579   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8580   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
8581   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
8582 
8583   enum {
8584     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8585     OP_VREV,
8586     OP_VDUP0,
8587     OP_VDUP1,
8588     OP_VDUP2,
8589     OP_VDUP3,
8590     OP_VEXT1,
8591     OP_VEXT2,
8592     OP_VEXT3,
8593     OP_VUZPL, // VUZP, left result
8594     OP_VUZPR, // VUZP, right result
8595     OP_VZIPL, // VZIP, left result
8596     OP_VZIPR, // VZIP, right result
8597     OP_VTRNL, // VTRN, left result
8598     OP_VTRNR  // VTRN, right result
8599   };
8600 
8601   if (OpNum == OP_COPY) {
8602     if (LHSID == (1 * 9 + 2) * 9 + 3)
8603       return LHS;
8604     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
8605     return RHS;
8606   }
8607 
8608   SDValue OpLHS, OpRHS;
8609   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8610   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8611   EVT VT = OpLHS.getValueType();
8612 
8613   switch (OpNum) {
8614   default:
8615     llvm_unreachable("Unknown shuffle opcode!");
8616   case OP_VREV:
8617     // VREV divides the vector in half and swaps within the half.
8618     if (VT.getVectorElementType() == MVT::i32 ||
8619         VT.getVectorElementType() == MVT::f32)
8620       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
8621     // vrev <4 x i16> -> REV32
8622     if (VT.getVectorElementType() == MVT::i16 ||
8623         VT.getVectorElementType() == MVT::f16 ||
8624         VT.getVectorElementType() == MVT::bf16)
8625       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
8626     // vrev <4 x i8> -> REV16
8627     assert(VT.getVectorElementType() == MVT::i8);
8628     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
8629   case OP_VDUP0:
8630   case OP_VDUP1:
8631   case OP_VDUP2:
8632   case OP_VDUP3: {
8633     EVT EltTy = VT.getVectorElementType();
8634     unsigned Opcode;
8635     if (EltTy == MVT::i8)
8636       Opcode = AArch64ISD::DUPLANE8;
8637     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
8638       Opcode = AArch64ISD::DUPLANE16;
8639     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
8640       Opcode = AArch64ISD::DUPLANE32;
8641     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
8642       Opcode = AArch64ISD::DUPLANE64;
8643     else
8644       llvm_unreachable("Invalid vector element type?");
8645 
8646     if (VT.getSizeInBits() == 64)
8647       OpLHS = WidenVector(OpLHS, DAG);
8648     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
8649     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
8650   }
8651   case OP_VEXT1:
8652   case OP_VEXT2:
8653   case OP_VEXT3: {
8654     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
8655     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
8656                        DAG.getConstant(Imm, dl, MVT::i32));
8657   }
8658   case OP_VUZPL:
8659     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
8660                        OpRHS);
8661   case OP_VUZPR:
8662     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
8663                        OpRHS);
8664   case OP_VZIPL:
8665     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
8666                        OpRHS);
8667   case OP_VZIPR:
8668     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
8669                        OpRHS);
8670   case OP_VTRNL:
8671     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
8672                        OpRHS);
8673   case OP_VTRNR:
8674     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
8675                        OpRHS);
8676   }
8677 }
8678 
8679 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
8680                            SelectionDAG &DAG) {
8681   // Check to see if we can use the TBL instruction.
8682   SDValue V1 = Op.getOperand(0);
8683   SDValue V2 = Op.getOperand(1);
8684   SDLoc DL(Op);
8685 
8686   EVT EltVT = Op.getValueType().getVectorElementType();
8687   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
8688 
8689   SmallVector<SDValue, 8> TBLMask;
8690   for (int Val : ShuffleMask) {
8691     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
8692       unsigned Offset = Byte + Val * BytesPerElt;
8693       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
8694     }
8695   }
8696 
8697   MVT IndexVT = MVT::v8i8;
8698   unsigned IndexLen = 8;
8699   if (Op.getValueSizeInBits() == 128) {
8700     IndexVT = MVT::v16i8;
8701     IndexLen = 16;
8702   }
8703 
8704   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
8705   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
8706 
8707   SDValue Shuffle;
8708   if (V2.getNode()->isUndef()) {
8709     if (IndexLen == 8)
8710       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
8711     Shuffle = DAG.getNode(
8712         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8713         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8714         DAG.getBuildVector(IndexVT, DL,
8715                            makeArrayRef(TBLMask.data(), IndexLen)));
8716   } else {
8717     if (IndexLen == 8) {
8718       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
8719       Shuffle = DAG.getNode(
8720           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8721           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8722           DAG.getBuildVector(IndexVT, DL,
8723                              makeArrayRef(TBLMask.data(), IndexLen)));
8724     } else {
8725       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
8726       // cannot currently represent the register constraints on the input
8727       // table registers.
8728       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
8729       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
8730       //                   IndexLen));
8731       Shuffle = DAG.getNode(
8732           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8733           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
8734           V2Cst, DAG.getBuildVector(IndexVT, DL,
8735                                     makeArrayRef(TBLMask.data(), IndexLen)));
8736     }
8737   }
8738   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
8739 }
8740 
8741 static unsigned getDUPLANEOp(EVT EltType) {
8742   if (EltType == MVT::i8)
8743     return AArch64ISD::DUPLANE8;
8744   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
8745     return AArch64ISD::DUPLANE16;
8746   if (EltType == MVT::i32 || EltType == MVT::f32)
8747     return AArch64ISD::DUPLANE32;
8748   if (EltType == MVT::i64 || EltType == MVT::f64)
8749     return AArch64ISD::DUPLANE64;
8750 
8751   llvm_unreachable("Invalid vector element type?");
8752 }
8753 
8754 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
8755                             unsigned Opcode, SelectionDAG &DAG) {
8756   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
8757   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
8758     // Match: dup (bitcast (extract_subv X, C)), LaneC
8759     if (BitCast.getOpcode() != ISD::BITCAST ||
8760         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
8761       return false;
8762 
8763     // The extract index must align in the destination type. That may not
8764     // happen if the bitcast is from narrow to wide type.
8765     SDValue Extract = BitCast.getOperand(0);
8766     unsigned ExtIdx = Extract.getConstantOperandVal(1);
8767     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
8768     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
8769     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
8770     if (ExtIdxInBits % CastedEltBitWidth != 0)
8771       return false;
8772 
8773     // Update the lane value by offsetting with the scaled extract index.
8774     LaneC += ExtIdxInBits / CastedEltBitWidth;
8775 
8776     // Determine the casted vector type of the wide vector input.
8777     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
8778     // Examples:
8779     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
8780     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
8781     unsigned SrcVecNumElts =
8782         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
8783     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
8784                               SrcVecNumElts);
8785     return true;
8786   };
8787   MVT CastVT;
8788   if (getScaledOffsetDup(V, Lane, CastVT)) {
8789     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
8790   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8791     // The lane is incremented by the index of the extract.
8792     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
8793     Lane += V.getConstantOperandVal(1);
8794     V = V.getOperand(0);
8795   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
8796     // The lane is decremented if we are splatting from the 2nd operand.
8797     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
8798     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
8799     Lane -= Idx * VT.getVectorNumElements() / 2;
8800     V = WidenVector(V.getOperand(Idx), DAG);
8801   } else if (VT.getSizeInBits() == 64) {
8802     // Widen the operand to 128-bit register with undef.
8803     V = WidenVector(V, DAG);
8804   }
8805   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
8806 }
8807 
8808 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8809                                                    SelectionDAG &DAG) const {
8810   SDLoc dl(Op);
8811   EVT VT = Op.getValueType();
8812 
8813   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8814 
8815   // Convert shuffles that are directly supported on NEON to target-specific
8816   // DAG nodes, instead of keeping them as shuffles and matching them again
8817   // during code selection.  This is more efficient and avoids the possibility
8818   // of inconsistencies between legalization and selection.
8819   ArrayRef<int> ShuffleMask = SVN->getMask();
8820 
8821   SDValue V1 = Op.getOperand(0);
8822   SDValue V2 = Op.getOperand(1);
8823 
8824   if (SVN->isSplat()) {
8825     int Lane = SVN->getSplatIndex();
8826     // If this is undef splat, generate it via "just" vdup, if possible.
8827     if (Lane == -1)
8828       Lane = 0;
8829 
8830     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
8831       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
8832                          V1.getOperand(0));
8833     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
8834     // constant. If so, we can just reference the lane's definition directly.
8835     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
8836         !isa<ConstantSDNode>(V1.getOperand(Lane)))
8837       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
8838 
8839     // Otherwise, duplicate from the lane of the input vector.
8840     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
8841     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
8842   }
8843 
8844   // Check if the mask matches a DUP for a wider element
8845   for (unsigned LaneSize : {64U, 32U, 16U}) {
8846     unsigned Lane = 0;
8847     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
8848       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
8849                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
8850                                                         : AArch64ISD::DUPLANE16;
8851       // Cast V1 to an integer vector with required lane size
8852       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
8853       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
8854       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
8855       V1 = DAG.getBitcast(NewVecTy, V1);
8856       // Constuct the DUP instruction
8857       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
8858       // Cast back to the original type
8859       return DAG.getBitcast(VT, V1);
8860     }
8861   }
8862 
8863   if (isREVMask(ShuffleMask, VT, 64))
8864     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
8865   if (isREVMask(ShuffleMask, VT, 32))
8866     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
8867   if (isREVMask(ShuffleMask, VT, 16))
8868     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
8869 
8870   bool ReverseEXT = false;
8871   unsigned Imm;
8872   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
8873     if (ReverseEXT)
8874       std::swap(V1, V2);
8875     Imm *= getExtFactor(V1);
8876     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
8877                        DAG.getConstant(Imm, dl, MVT::i32));
8878   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
8879     Imm *= getExtFactor(V1);
8880     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
8881                        DAG.getConstant(Imm, dl, MVT::i32));
8882   }
8883 
8884   unsigned WhichResult;
8885   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
8886     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8887     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8888   }
8889   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
8890     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8891     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8892   }
8893   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
8894     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8895     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8896   }
8897 
8898   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8899     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8900     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8901   }
8902   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8903     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8904     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8905   }
8906   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8907     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8908     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8909   }
8910 
8911   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
8912     return Concat;
8913 
8914   bool DstIsLeft;
8915   int Anomaly;
8916   int NumInputElements = V1.getValueType().getVectorNumElements();
8917   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
8918     SDValue DstVec = DstIsLeft ? V1 : V2;
8919     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
8920 
8921     SDValue SrcVec = V1;
8922     int SrcLane = ShuffleMask[Anomaly];
8923     if (SrcLane >= NumInputElements) {
8924       SrcVec = V2;
8925       SrcLane -= VT.getVectorNumElements();
8926     }
8927     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
8928 
8929     EVT ScalarVT = VT.getVectorElementType();
8930 
8931     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
8932       ScalarVT = MVT::i32;
8933 
8934     return DAG.getNode(
8935         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8936         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
8937         DstLaneV);
8938   }
8939 
8940   // If the shuffle is not directly supported and it has 4 elements, use
8941   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8942   unsigned NumElts = VT.getVectorNumElements();
8943   if (NumElts == 4) {
8944     unsigned PFIndexes[4];
8945     for (unsigned i = 0; i != 4; ++i) {
8946       if (ShuffleMask[i] < 0)
8947         PFIndexes[i] = 8;
8948       else
8949         PFIndexes[i] = ShuffleMask[i];
8950     }
8951 
8952     // Compute the index in the perfect shuffle table.
8953     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8954                             PFIndexes[2] * 9 + PFIndexes[3];
8955     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8956     unsigned Cost = (PFEntry >> 30);
8957 
8958     if (Cost <= 4)
8959       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8960   }
8961 
8962   return GenerateTBL(Op, ShuffleMask, DAG);
8963 }
8964 
8965 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
8966                                                  SelectionDAG &DAG) const {
8967   SDLoc dl(Op);
8968   EVT VT = Op.getValueType();
8969   EVT ElemVT = VT.getScalarType();
8970   SDValue SplatVal = Op.getOperand(0);
8971 
8972   if (useSVEForFixedLengthVectorVT(VT))
8973     return LowerToScalableOp(Op, DAG);
8974 
8975   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
8976   // FPRs don't have this restriction.
8977   switch (ElemVT.getSimpleVT().SimpleTy) {
8978   case MVT::i1: {
8979     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
8980     // lowering code.
8981     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
8982       if (ConstVal->isOne())
8983         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
8984       // TODO: Add special case for constant false
8985     }
8986     // The general case of i1.  There isn't any natural way to do this,
8987     // so we use some trickery with whilelo.
8988     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8989     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
8990                            DAG.getValueType(MVT::i1));
8991     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
8992                                        MVT::i64);
8993     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
8994                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
8995   }
8996   case MVT::i8:
8997   case MVT::i16:
8998   case MVT::i32:
8999     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
9000     break;
9001   case MVT::i64:
9002     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
9003     break;
9004   case MVT::f16:
9005   case MVT::bf16:
9006   case MVT::f32:
9007   case MVT::f64:
9008     // Fine as is
9009     break;
9010   default:
9011     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
9012   }
9013 
9014   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
9015 }
9016 
9017 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
9018                                              SelectionDAG &DAG) const {
9019   SDLoc DL(Op);
9020 
9021   EVT VT = Op.getValueType();
9022   if (!isTypeLegal(VT) || !VT.isScalableVector())
9023     return SDValue();
9024 
9025   // Current lowering only supports the SVE-ACLE types.
9026   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
9027     return SDValue();
9028 
9029   // The DUPQ operation is indepedent of element type so normalise to i64s.
9030   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
9031   SDValue Idx128 = Op.getOperand(2);
9032 
9033   // DUPQ can be used when idx is in range.
9034   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
9035   if (CIdx && (CIdx->getZExtValue() <= 3)) {
9036     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
9037     SDNode *DUPQ =
9038         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
9039     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
9040   }
9041 
9042   // The ACLE says this must produce the same result as:
9043   //   svtbl(data, svadd_x(svptrue_b64(),
9044   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
9045   //                       index * 2))
9046   SDValue One = DAG.getConstant(1, DL, MVT::i64);
9047   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
9048 
9049   // create the vector 0,1,0,1,...
9050   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
9051   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
9052                            DL, MVT::nxv2i64, Zero, One);
9053   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
9054 
9055   // create the vector idx64,idx64+1,idx64,idx64+1,...
9056   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
9057   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
9058   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
9059 
9060   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
9061   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
9062   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
9063 }
9064 
9065 
9066 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
9067                                APInt &UndefBits) {
9068   EVT VT = BVN->getValueType(0);
9069   APInt SplatBits, SplatUndef;
9070   unsigned SplatBitSize;
9071   bool HasAnyUndefs;
9072   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9073     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
9074 
9075     for (unsigned i = 0; i < NumSplats; ++i) {
9076       CnstBits <<= SplatBitSize;
9077       UndefBits <<= SplatBitSize;
9078       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
9079       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
9080     }
9081 
9082     return true;
9083   }
9084 
9085   return false;
9086 }
9087 
9088 // Try 64-bit splatted SIMD immediate.
9089 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9090                                  const APInt &Bits) {
9091   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9092     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9093     EVT VT = Op.getValueType();
9094     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
9095 
9096     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
9097       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
9098 
9099       SDLoc dl(Op);
9100       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9101                                 DAG.getConstant(Value, dl, MVT::i32));
9102       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9103     }
9104   }
9105 
9106   return SDValue();
9107 }
9108 
9109 // Try 32-bit splatted SIMD immediate.
9110 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9111                                   const APInt &Bits,
9112                                   const SDValue *LHS = nullptr) {
9113   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9114     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9115     EVT VT = Op.getValueType();
9116     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
9117     bool isAdvSIMDModImm = false;
9118     uint64_t Shift;
9119 
9120     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
9121       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
9122       Shift = 0;
9123     }
9124     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
9125       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
9126       Shift = 8;
9127     }
9128     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
9129       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
9130       Shift = 16;
9131     }
9132     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
9133       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
9134       Shift = 24;
9135     }
9136 
9137     if (isAdvSIMDModImm) {
9138       SDLoc dl(Op);
9139       SDValue Mov;
9140 
9141       if (LHS)
9142         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
9143                           DAG.getConstant(Value, dl, MVT::i32),
9144                           DAG.getConstant(Shift, dl, MVT::i32));
9145       else
9146         Mov = DAG.getNode(NewOp, dl, MovTy,
9147                           DAG.getConstant(Value, dl, MVT::i32),
9148                           DAG.getConstant(Shift, dl, MVT::i32));
9149 
9150       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9151     }
9152   }
9153 
9154   return SDValue();
9155 }
9156 
9157 // Try 16-bit splatted SIMD immediate.
9158 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9159                                   const APInt &Bits,
9160                                   const SDValue *LHS = nullptr) {
9161   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9162     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9163     EVT VT = Op.getValueType();
9164     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
9165     bool isAdvSIMDModImm = false;
9166     uint64_t Shift;
9167 
9168     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
9169       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
9170       Shift = 0;
9171     }
9172     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
9173       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
9174       Shift = 8;
9175     }
9176 
9177     if (isAdvSIMDModImm) {
9178       SDLoc dl(Op);
9179       SDValue Mov;
9180 
9181       if (LHS)
9182         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
9183                           DAG.getConstant(Value, dl, MVT::i32),
9184                           DAG.getConstant(Shift, dl, MVT::i32));
9185       else
9186         Mov = DAG.getNode(NewOp, dl, MovTy,
9187                           DAG.getConstant(Value, dl, MVT::i32),
9188                           DAG.getConstant(Shift, dl, MVT::i32));
9189 
9190       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9191     }
9192   }
9193 
9194   return SDValue();
9195 }
9196 
9197 // Try 32-bit splatted SIMD immediate with shifted ones.
9198 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
9199                                     SelectionDAG &DAG, const APInt &Bits) {
9200   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9201     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9202     EVT VT = Op.getValueType();
9203     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
9204     bool isAdvSIMDModImm = false;
9205     uint64_t Shift;
9206 
9207     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
9208       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
9209       Shift = 264;
9210     }
9211     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
9212       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
9213       Shift = 272;
9214     }
9215 
9216     if (isAdvSIMDModImm) {
9217       SDLoc dl(Op);
9218       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9219                                 DAG.getConstant(Value, dl, MVT::i32),
9220                                 DAG.getConstant(Shift, dl, MVT::i32));
9221       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9222     }
9223   }
9224 
9225   return SDValue();
9226 }
9227 
9228 // Try 8-bit splatted SIMD immediate.
9229 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9230                                  const APInt &Bits) {
9231   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9232     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9233     EVT VT = Op.getValueType();
9234     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
9235 
9236     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
9237       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
9238 
9239       SDLoc dl(Op);
9240       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9241                                 DAG.getConstant(Value, dl, MVT::i32));
9242       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9243     }
9244   }
9245 
9246   return SDValue();
9247 }
9248 
9249 // Try FP splatted SIMD immediate.
9250 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9251                                   const APInt &Bits) {
9252   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9253     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9254     EVT VT = Op.getValueType();
9255     bool isWide = (VT.getSizeInBits() == 128);
9256     MVT MovTy;
9257     bool isAdvSIMDModImm = false;
9258 
9259     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
9260       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
9261       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
9262     }
9263     else if (isWide &&
9264              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
9265       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
9266       MovTy = MVT::v2f64;
9267     }
9268 
9269     if (isAdvSIMDModImm) {
9270       SDLoc dl(Op);
9271       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9272                                 DAG.getConstant(Value, dl, MVT::i32));
9273       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9274     }
9275   }
9276 
9277   return SDValue();
9278 }
9279 
9280 // Specialized code to quickly find if PotentialBVec is a BuildVector that
9281 // consists of only the same constant int value, returned in reference arg
9282 // ConstVal
9283 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
9284                                      uint64_t &ConstVal) {
9285   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
9286   if (!Bvec)
9287     return false;
9288   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
9289   if (!FirstElt)
9290     return false;
9291   EVT VT = Bvec->getValueType(0);
9292   unsigned NumElts = VT.getVectorNumElements();
9293   for (unsigned i = 1; i < NumElts; ++i)
9294     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
9295       return false;
9296   ConstVal = FirstElt->getZExtValue();
9297   return true;
9298 }
9299 
9300 static unsigned getIntrinsicID(const SDNode *N) {
9301   unsigned Opcode = N->getOpcode();
9302   switch (Opcode) {
9303   default:
9304     return Intrinsic::not_intrinsic;
9305   case ISD::INTRINSIC_WO_CHAIN: {
9306     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9307     if (IID < Intrinsic::num_intrinsics)
9308       return IID;
9309     return Intrinsic::not_intrinsic;
9310   }
9311   }
9312 }
9313 
9314 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
9315 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
9316 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
9317 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
9318 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
9319 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
9320 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
9321   EVT VT = N->getValueType(0);
9322 
9323   if (!VT.isVector())
9324     return SDValue();
9325 
9326   SDLoc DL(N);
9327 
9328   SDValue And;
9329   SDValue Shift;
9330 
9331   SDValue FirstOp = N->getOperand(0);
9332   unsigned FirstOpc = FirstOp.getOpcode();
9333   SDValue SecondOp = N->getOperand(1);
9334   unsigned SecondOpc = SecondOp.getOpcode();
9335 
9336   // Is one of the operands an AND or a BICi? The AND may have been optimised to
9337   // a BICi in order to use an immediate instead of a register.
9338   // Is the other operand an shl or lshr? This will have been turned into:
9339   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
9340   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
9341       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
9342     And = FirstOp;
9343     Shift = SecondOp;
9344 
9345   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
9346              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
9347     And = SecondOp;
9348     Shift = FirstOp;
9349   } else
9350     return SDValue();
9351 
9352   bool IsAnd = And.getOpcode() == ISD::AND;
9353   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
9354 
9355   // Is the shift amount constant?
9356   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9357   if (!C2node)
9358     return SDValue();
9359 
9360   uint64_t C1;
9361   if (IsAnd) {
9362     // Is the and mask vector all constant?
9363     if (!isAllConstantBuildVector(And.getOperand(1), C1))
9364       return SDValue();
9365   } else {
9366     // Reconstruct the corresponding AND immediate from the two BICi immediates.
9367     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
9368     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
9369     assert(C1nodeImm && C1nodeShift);
9370     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
9371   }
9372 
9373   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
9374   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
9375   // how much one can shift elements of a particular size?
9376   uint64_t C2 = C2node->getZExtValue();
9377   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
9378   if (C2 > ElemSizeInBits)
9379     return SDValue();
9380 
9381   APInt C1AsAPInt(ElemSizeInBits, C1);
9382   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
9383                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
9384   if (C1AsAPInt != RequiredC1)
9385     return SDValue();
9386 
9387   SDValue X = And.getOperand(0);
9388   SDValue Y = Shift.getOperand(0);
9389 
9390   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
9391   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
9392 
9393   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
9394   LLVM_DEBUG(N->dump(&DAG));
9395   LLVM_DEBUG(dbgs() << "into: \n");
9396   LLVM_DEBUG(ResultSLI->dump(&DAG));
9397 
9398   ++NumShiftInserts;
9399   return ResultSLI;
9400 }
9401 
9402 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
9403                                              SelectionDAG &DAG) const {
9404   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
9405     return LowerToScalableOp(Op, DAG);
9406 
9407   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
9408   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
9409     return Res;
9410 
9411   EVT VT = Op.getValueType();
9412 
9413   SDValue LHS = Op.getOperand(0);
9414   BuildVectorSDNode *BVN =
9415       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
9416   if (!BVN) {
9417     // OR commutes, so try swapping the operands.
9418     LHS = Op.getOperand(1);
9419     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
9420   }
9421   if (!BVN)
9422     return Op;
9423 
9424   APInt DefBits(VT.getSizeInBits(), 0);
9425   APInt UndefBits(VT.getSizeInBits(), 0);
9426   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9427     SDValue NewOp;
9428 
9429     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
9430                                     DefBits, &LHS)) ||
9431         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
9432                                     DefBits, &LHS)))
9433       return NewOp;
9434 
9435     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
9436                                     UndefBits, &LHS)) ||
9437         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
9438                                     UndefBits, &LHS)))
9439       return NewOp;
9440   }
9441 
9442   // We can always fall back to a non-immediate OR.
9443   return Op;
9444 }
9445 
9446 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
9447 // be truncated to fit element width.
9448 static SDValue NormalizeBuildVector(SDValue Op,
9449                                     SelectionDAG &DAG) {
9450   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
9451   SDLoc dl(Op);
9452   EVT VT = Op.getValueType();
9453   EVT EltTy= VT.getVectorElementType();
9454 
9455   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
9456     return Op;
9457 
9458   SmallVector<SDValue, 16> Ops;
9459   for (SDValue Lane : Op->ops()) {
9460     // For integer vectors, type legalization would have promoted the
9461     // operands already. Otherwise, if Op is a floating-point splat
9462     // (with operands cast to integers), then the only possibilities
9463     // are constants and UNDEFs.
9464     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
9465       APInt LowBits(EltTy.getSizeInBits(),
9466                     CstLane->getZExtValue());
9467       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
9468     } else if (Lane.getNode()->isUndef()) {
9469       Lane = DAG.getUNDEF(MVT::i32);
9470     } else {
9471       assert(Lane.getValueType() == MVT::i32 &&
9472              "Unexpected BUILD_VECTOR operand type");
9473     }
9474     Ops.push_back(Lane);
9475   }
9476   return DAG.getBuildVector(VT, dl, Ops);
9477 }
9478 
9479 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
9480   EVT VT = Op.getValueType();
9481 
9482   APInt DefBits(VT.getSizeInBits(), 0);
9483   APInt UndefBits(VT.getSizeInBits(), 0);
9484   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
9485   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9486     SDValue NewOp;
9487     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
9488         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9489         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
9490         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9491         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
9492         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
9493       return NewOp;
9494 
9495     DefBits = ~DefBits;
9496     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
9497         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
9498         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
9499       return NewOp;
9500 
9501     DefBits = UndefBits;
9502     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
9503         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9504         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
9505         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9506         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
9507         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
9508       return NewOp;
9509 
9510     DefBits = ~UndefBits;
9511     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
9512         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
9513         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
9514       return NewOp;
9515   }
9516 
9517   return SDValue();
9518 }
9519 
9520 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
9521                                                  SelectionDAG &DAG) const {
9522   EVT VT = Op.getValueType();
9523 
9524   // Try to build a simple constant vector.
9525   Op = NormalizeBuildVector(Op, DAG);
9526   if (VT.isInteger()) {
9527     // Certain vector constants, used to express things like logical NOT and
9528     // arithmetic NEG, are passed through unmodified.  This allows special
9529     // patterns for these operations to match, which will lower these constants
9530     // to whatever is proven necessary.
9531     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
9532     if (BVN->isConstant())
9533       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
9534         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
9535         APInt Val(BitSize,
9536                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
9537         if (Val.isNullValue() || Val.isAllOnesValue())
9538           return Op;
9539       }
9540   }
9541 
9542   if (SDValue V = ConstantBuildVector(Op, DAG))
9543     return V;
9544 
9545   // Scan through the operands to find some interesting properties we can
9546   // exploit:
9547   //   1) If only one value is used, we can use a DUP, or
9548   //   2) if only the low element is not undef, we can just insert that, or
9549   //   3) if only one constant value is used (w/ some non-constant lanes),
9550   //      we can splat the constant value into the whole vector then fill
9551   //      in the non-constant lanes.
9552   //   4) FIXME: If different constant values are used, but we can intelligently
9553   //             select the values we'll be overwriting for the non-constant
9554   //             lanes such that we can directly materialize the vector
9555   //             some other way (MOVI, e.g.), we can be sneaky.
9556   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
9557   SDLoc dl(Op);
9558   unsigned NumElts = VT.getVectorNumElements();
9559   bool isOnlyLowElement = true;
9560   bool usesOnlyOneValue = true;
9561   bool usesOnlyOneConstantValue = true;
9562   bool isConstant = true;
9563   bool AllLanesExtractElt = true;
9564   unsigned NumConstantLanes = 0;
9565   unsigned NumDifferentLanes = 0;
9566   unsigned NumUndefLanes = 0;
9567   SDValue Value;
9568   SDValue ConstantValue;
9569   for (unsigned i = 0; i < NumElts; ++i) {
9570     SDValue V = Op.getOperand(i);
9571     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9572       AllLanesExtractElt = false;
9573     if (V.isUndef()) {
9574       ++NumUndefLanes;
9575       continue;
9576     }
9577     if (i > 0)
9578       isOnlyLowElement = false;
9579     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
9580       isConstant = false;
9581 
9582     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
9583       ++NumConstantLanes;
9584       if (!ConstantValue.getNode())
9585         ConstantValue = V;
9586       else if (ConstantValue != V)
9587         usesOnlyOneConstantValue = false;
9588     }
9589 
9590     if (!Value.getNode())
9591       Value = V;
9592     else if (V != Value) {
9593       usesOnlyOneValue = false;
9594       ++NumDifferentLanes;
9595     }
9596   }
9597 
9598   if (!Value.getNode()) {
9599     LLVM_DEBUG(
9600         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
9601     return DAG.getUNDEF(VT);
9602   }
9603 
9604   // Convert BUILD_VECTOR where all elements but the lowest are undef into
9605   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
9606   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
9607   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
9608     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
9609                          "SCALAR_TO_VECTOR node\n");
9610     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
9611   }
9612 
9613   if (AllLanesExtractElt) {
9614     SDNode *Vector = nullptr;
9615     bool Even = false;
9616     bool Odd = false;
9617     // Check whether the extract elements match the Even pattern <0,2,4,...> or
9618     // the Odd pattern <1,3,5,...>.
9619     for (unsigned i = 0; i < NumElts; ++i) {
9620       SDValue V = Op.getOperand(i);
9621       const SDNode *N = V.getNode();
9622       if (!isa<ConstantSDNode>(N->getOperand(1)))
9623         break;
9624       SDValue N0 = N->getOperand(0);
9625 
9626       // All elements are extracted from the same vector.
9627       if (!Vector) {
9628         Vector = N0.getNode();
9629         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
9630         // BUILD_VECTOR.
9631         if (VT.getVectorElementType() !=
9632             N0.getValueType().getVectorElementType())
9633           break;
9634       } else if (Vector != N0.getNode()) {
9635         Odd = false;
9636         Even = false;
9637         break;
9638       }
9639 
9640       // Extracted values are either at Even indices <0,2,4,...> or at Odd
9641       // indices <1,3,5,...>.
9642       uint64_t Val = N->getConstantOperandVal(1);
9643       if (Val == 2 * i) {
9644         Even = true;
9645         continue;
9646       }
9647       if (Val - 1 == 2 * i) {
9648         Odd = true;
9649         continue;
9650       }
9651 
9652       // Something does not match: abort.
9653       Odd = false;
9654       Even = false;
9655       break;
9656     }
9657     if (Even || Odd) {
9658       SDValue LHS =
9659           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9660                       DAG.getConstant(0, dl, MVT::i64));
9661       SDValue RHS =
9662           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9663                       DAG.getConstant(NumElts, dl, MVT::i64));
9664 
9665       if (Even && !Odd)
9666         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
9667                            RHS);
9668       if (Odd && !Even)
9669         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
9670                            RHS);
9671     }
9672   }
9673 
9674   // Use DUP for non-constant splats. For f32 constant splats, reduce to
9675   // i32 and try again.
9676   if (usesOnlyOneValue) {
9677     if (!isConstant) {
9678       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9679           Value.getValueType() != VT) {
9680         LLVM_DEBUG(
9681             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
9682         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
9683       }
9684 
9685       // This is actually a DUPLANExx operation, which keeps everything vectory.
9686 
9687       SDValue Lane = Value.getOperand(1);
9688       Value = Value.getOperand(0);
9689       if (Value.getValueSizeInBits() == 64) {
9690         LLVM_DEBUG(
9691             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
9692                       "widening it\n");
9693         Value = WidenVector(Value, DAG);
9694       }
9695 
9696       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
9697       return DAG.getNode(Opcode, dl, VT, Value, Lane);
9698     }
9699 
9700     if (VT.getVectorElementType().isFloatingPoint()) {
9701       SmallVector<SDValue, 8> Ops;
9702       EVT EltTy = VT.getVectorElementType();
9703       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
9704                EltTy == MVT::f64) && "Unsupported floating-point vector type");
9705       LLVM_DEBUG(
9706           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
9707                     "BITCASTS, and try again\n");
9708       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
9709       for (unsigned i = 0; i < NumElts; ++i)
9710         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
9711       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
9712       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
9713       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
9714                  Val.dump(););
9715       Val = LowerBUILD_VECTOR(Val, DAG);
9716       if (Val.getNode())
9717         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9718     }
9719   }
9720 
9721   // If we need to insert a small number of different non-constant elements and
9722   // the vector width is sufficiently large, prefer using DUP with the common
9723   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
9724   // skip the constant lane handling below.
9725   bool PreferDUPAndInsert =
9726       !isConstant && NumDifferentLanes >= 1 &&
9727       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
9728       NumDifferentLanes >= NumConstantLanes;
9729 
9730   // If there was only one constant value used and for more than one lane,
9731   // start by splatting that value, then replace the non-constant lanes. This
9732   // is better than the default, which will perform a separate initialization
9733   // for each lane.
9734   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
9735     // Firstly, try to materialize the splat constant.
9736     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
9737             Val = ConstantBuildVector(Vec, DAG);
9738     if (!Val) {
9739       // Otherwise, materialize the constant and splat it.
9740       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
9741       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
9742     }
9743 
9744     // Now insert the non-constant lanes.
9745     for (unsigned i = 0; i < NumElts; ++i) {
9746       SDValue V = Op.getOperand(i);
9747       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9748       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
9749         // Note that type legalization likely mucked about with the VT of the
9750         // source operand, so we may have to convert it here before inserting.
9751         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
9752     }
9753     return Val;
9754   }
9755 
9756   // This will generate a load from the constant pool.
9757   if (isConstant) {
9758     LLVM_DEBUG(
9759         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
9760                   "expansion\n");
9761     return SDValue();
9762   }
9763 
9764   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
9765   if (NumElts >= 4) {
9766     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
9767       return shuffle;
9768   }
9769 
9770   if (PreferDUPAndInsert) {
9771     // First, build a constant vector with the common element.
9772     SmallVector<SDValue, 8> Ops(NumElts, Value);
9773     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
9774     // Next, insert the elements that do not match the common value.
9775     for (unsigned I = 0; I < NumElts; ++I)
9776       if (Op.getOperand(I) != Value)
9777         NewVector =
9778             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
9779                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
9780 
9781     return NewVector;
9782   }
9783 
9784   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
9785   // know the default expansion would otherwise fall back on something even
9786   // worse. For a vector with one or two non-undef values, that's
9787   // scalar_to_vector for the elements followed by a shuffle (provided the
9788   // shuffle is valid for the target) and materialization element by element
9789   // on the stack followed by a load for everything else.
9790   if (!isConstant && !usesOnlyOneValue) {
9791     LLVM_DEBUG(
9792         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
9793                   "of INSERT_VECTOR_ELT\n");
9794 
9795     SDValue Vec = DAG.getUNDEF(VT);
9796     SDValue Op0 = Op.getOperand(0);
9797     unsigned i = 0;
9798 
9799     // Use SCALAR_TO_VECTOR for lane zero to
9800     // a) Avoid a RMW dependency on the full vector register, and
9801     // b) Allow the register coalescer to fold away the copy if the
9802     //    value is already in an S or D register, and we're forced to emit an
9803     //    INSERT_SUBREG that we can't fold anywhere.
9804     //
9805     // We also allow types like i8 and i16 which are illegal scalar but legal
9806     // vector element types. After type-legalization the inserted value is
9807     // extended (i32) and it is safe to cast them to the vector type by ignoring
9808     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
9809     if (!Op0.isUndef()) {
9810       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
9811       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
9812       ++i;
9813     }
9814     LLVM_DEBUG(if (i < NumElts) dbgs()
9815                    << "Creating nodes for the other vector elements:\n";);
9816     for (; i < NumElts; ++i) {
9817       SDValue V = Op.getOperand(i);
9818       if (V.isUndef())
9819         continue;
9820       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9821       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
9822     }
9823     return Vec;
9824   }
9825 
9826   LLVM_DEBUG(
9827       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
9828                 "better alternative\n");
9829   return SDValue();
9830 }
9831 
9832 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
9833                                                    SelectionDAG &DAG) const {
9834   assert(Op.getValueType().isScalableVector() &&
9835          isTypeLegal(Op.getValueType()) &&
9836          "Expected legal scalable vector type!");
9837 
9838   if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2)
9839     return Op;
9840 
9841   return SDValue();
9842 }
9843 
9844 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9845                                                       SelectionDAG &DAG) const {
9846   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
9847 
9848   // Check for non-constant or out of range lane.
9849   EVT VT = Op.getOperand(0).getValueType();
9850   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9851   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9852     return SDValue();
9853 
9854 
9855   // Insertion/extraction are legal for V128 types.
9856   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9857       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9858       VT == MVT::v8f16 || VT == MVT::v8bf16)
9859     return Op;
9860 
9861   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9862       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9863       VT != MVT::v4bf16)
9864     return SDValue();
9865 
9866   // For V64 types, we perform insertion by expanding the value
9867   // to a V128 type and perform the insertion on that.
9868   SDLoc DL(Op);
9869   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9870   EVT WideTy = WideVec.getValueType();
9871 
9872   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
9873                              Op.getOperand(1), Op.getOperand(2));
9874   // Re-narrow the resultant vector.
9875   return NarrowVector(Node, DAG);
9876 }
9877 
9878 SDValue
9879 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9880                                                SelectionDAG &DAG) const {
9881   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
9882 
9883   // Check for non-constant or out of range lane.
9884   EVT VT = Op.getOperand(0).getValueType();
9885   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9886   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9887     return SDValue();
9888 
9889 
9890   // Insertion/extraction are legal for V128 types.
9891   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9892       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9893       VT == MVT::v8f16 || VT == MVT::v8bf16)
9894     return Op;
9895 
9896   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9897       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9898       VT != MVT::v4bf16)
9899     return SDValue();
9900 
9901   // For V64 types, we perform extraction by expanding the value
9902   // to a V128 type and perform the extraction on that.
9903   SDLoc DL(Op);
9904   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9905   EVT WideTy = WideVec.getValueType();
9906 
9907   EVT ExtrTy = WideTy.getVectorElementType();
9908   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
9909     ExtrTy = MVT::i32;
9910 
9911   // For extractions, we just return the result directly.
9912   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
9913                      Op.getOperand(1));
9914 }
9915 
9916 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
9917                                                       SelectionDAG &DAG) const {
9918   assert(Op.getValueType().isFixedLengthVector() &&
9919          "Only cases that extract a fixed length vector are supported!");
9920 
9921   EVT InVT = Op.getOperand(0).getValueType();
9922   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9923   unsigned Size = Op.getValueSizeInBits();
9924 
9925   if (InVT.isScalableVector()) {
9926     // This will be matched by custom code during ISelDAGToDAG.
9927     if (Idx == 0 && isPackedVectorType(InVT, DAG))
9928       return Op;
9929 
9930     return SDValue();
9931   }
9932 
9933   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
9934   if (Idx == 0 && InVT.getSizeInBits() <= 128)
9935     return Op;
9936 
9937   // If this is extracting the upper 64-bits of a 128-bit vector, we match
9938   // that directly.
9939   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
9940       InVT.getSizeInBits() == 128)
9941     return Op;
9942 
9943   return SDValue();
9944 }
9945 
9946 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
9947                                                      SelectionDAG &DAG) const {
9948   assert(Op.getValueType().isScalableVector() &&
9949          "Only expect to lower inserts into scalable vectors!");
9950 
9951   EVT InVT = Op.getOperand(1).getValueType();
9952   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9953 
9954   if (InVT.isScalableVector()) {
9955     SDLoc DL(Op);
9956     EVT VT = Op.getValueType();
9957 
9958     if (!isTypeLegal(VT) || !VT.isInteger())
9959       return SDValue();
9960 
9961     SDValue Vec0 = Op.getOperand(0);
9962     SDValue Vec1 = Op.getOperand(1);
9963 
9964     // Ensure the subvector is half the size of the main vector.
9965     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
9966       return SDValue();
9967 
9968     // Extend elements of smaller vector...
9969     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
9970     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
9971 
9972     if (Idx == 0) {
9973       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
9974       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
9975     } else if (Idx == InVT.getVectorMinNumElements()) {
9976       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
9977       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
9978     }
9979 
9980     return SDValue();
9981   }
9982 
9983   // This will be matched by custom code during ISelDAGToDAG.
9984   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
9985     return Op;
9986 
9987   return SDValue();
9988 }
9989 
9990 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
9991   EVT VT = Op.getValueType();
9992 
9993   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
9994     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
9995 
9996   assert(VT.isScalableVector() && "Expected a scalable vector.");
9997 
9998   bool Signed = Op.getOpcode() == ISD::SDIV;
9999   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
10000 
10001   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
10002     return LowerToPredicatedOp(Op, DAG, PredOpcode);
10003 
10004   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
10005   // operations, and truncate the result.
10006   EVT WidenedVT;
10007   if (VT == MVT::nxv16i8)
10008     WidenedVT = MVT::nxv8i16;
10009   else if (VT == MVT::nxv8i16)
10010     WidenedVT = MVT::nxv4i32;
10011   else
10012     llvm_unreachable("Unexpected Custom DIV operation");
10013 
10014   SDLoc dl(Op);
10015   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
10016   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
10017   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
10018   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
10019   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
10020   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
10021   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
10022   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
10023   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
10024 }
10025 
10026 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
10027   // Currently no fixed length shuffles that require SVE are legal.
10028   if (useSVEForFixedLengthVectorVT(VT))
10029     return false;
10030 
10031   if (VT.getVectorNumElements() == 4 &&
10032       (VT.is128BitVector() || VT.is64BitVector())) {
10033     unsigned PFIndexes[4];
10034     for (unsigned i = 0; i != 4; ++i) {
10035       if (M[i] < 0)
10036         PFIndexes[i] = 8;
10037       else
10038         PFIndexes[i] = M[i];
10039     }
10040 
10041     // Compute the index in the perfect shuffle table.
10042     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10043                             PFIndexes[2] * 9 + PFIndexes[3];
10044     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10045     unsigned Cost = (PFEntry >> 30);
10046 
10047     if (Cost <= 4)
10048       return true;
10049   }
10050 
10051   bool DummyBool;
10052   int DummyInt;
10053   unsigned DummyUnsigned;
10054 
10055   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
10056           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
10057           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
10058           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
10059           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
10060           isZIPMask(M, VT, DummyUnsigned) ||
10061           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
10062           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
10063           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
10064           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
10065           isConcatMask(M, VT, VT.getSizeInBits() == 128));
10066 }
10067 
10068 /// getVShiftImm - Check if this is a valid build_vector for the immediate
10069 /// operand of a vector shift operation, where all the elements of the
10070 /// build_vector must have the same constant integer value.
10071 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10072   // Ignore bit_converts.
10073   while (Op.getOpcode() == ISD::BITCAST)
10074     Op = Op.getOperand(0);
10075   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10076   APInt SplatBits, SplatUndef;
10077   unsigned SplatBitSize;
10078   bool HasAnyUndefs;
10079   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10080                                     HasAnyUndefs, ElementBits) ||
10081       SplatBitSize > ElementBits)
10082     return false;
10083   Cnt = SplatBits.getSExtValue();
10084   return true;
10085 }
10086 
10087 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10088 /// operand of a vector shift left operation.  That value must be in the range:
10089 ///   0 <= Value < ElementBits for a left shift; or
10090 ///   0 <= Value <= ElementBits for a long left shift.
10091 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10092   assert(VT.isVector() && "vector shift count is not a vector type");
10093   int64_t ElementBits = VT.getScalarSizeInBits();
10094   if (!getVShiftImm(Op, ElementBits, Cnt))
10095     return false;
10096   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
10097 }
10098 
10099 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10100 /// operand of a vector shift right operation. The value must be in the range:
10101 ///   1 <= Value <= ElementBits for a right shift; or
10102 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
10103   assert(VT.isVector() && "vector shift count is not a vector type");
10104   int64_t ElementBits = VT.getScalarSizeInBits();
10105   if (!getVShiftImm(Op, ElementBits, Cnt))
10106     return false;
10107   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
10108 }
10109 
10110 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
10111                                              SelectionDAG &DAG) const {
10112   EVT VT = Op.getValueType();
10113 
10114   if (VT.getScalarType() == MVT::i1) {
10115     // Lower i1 truncate to `(x & 1) != 0`.
10116     SDLoc dl(Op);
10117     EVT OpVT = Op.getOperand(0).getValueType();
10118     SDValue Zero = DAG.getConstant(0, dl, OpVT);
10119     SDValue One = DAG.getConstant(1, dl, OpVT);
10120     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
10121     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
10122   }
10123 
10124   if (!VT.isVector() || VT.isScalableVector())
10125     return SDValue();
10126 
10127   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
10128     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
10129 
10130   return SDValue();
10131 }
10132 
10133 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
10134                                                       SelectionDAG &DAG) const {
10135   EVT VT = Op.getValueType();
10136   SDLoc DL(Op);
10137   int64_t Cnt;
10138 
10139   if (!Op.getOperand(1).getValueType().isVector())
10140     return Op;
10141   unsigned EltSize = VT.getScalarSizeInBits();
10142 
10143   switch (Op.getOpcode()) {
10144   default:
10145     llvm_unreachable("unexpected shift opcode");
10146 
10147   case ISD::SHL:
10148     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
10149       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
10150 
10151     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
10152       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
10153                          DAG.getConstant(Cnt, DL, MVT::i32));
10154     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10155                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
10156                                        MVT::i32),
10157                        Op.getOperand(0), Op.getOperand(1));
10158   case ISD::SRA:
10159   case ISD::SRL:
10160     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
10161       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
10162                                                 : AArch64ISD::SRL_PRED;
10163       return LowerToPredicatedOp(Op, DAG, Opc);
10164     }
10165 
10166     // Right shift immediate
10167     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
10168       unsigned Opc =
10169           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
10170       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
10171                          DAG.getConstant(Cnt, DL, MVT::i32));
10172     }
10173 
10174     // Right shift register.  Note, there is not a shift right register
10175     // instruction, but the shift left register instruction takes a signed
10176     // value, where negative numbers specify a right shift.
10177     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
10178                                                 : Intrinsic::aarch64_neon_ushl;
10179     // negate the shift amount
10180     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
10181     SDValue NegShiftLeft =
10182         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10183                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
10184                     NegShift);
10185     return NegShiftLeft;
10186   }
10187 
10188   return SDValue();
10189 }
10190 
10191 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
10192                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
10193                                     const SDLoc &dl, SelectionDAG &DAG) {
10194   EVT SrcVT = LHS.getValueType();
10195   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
10196          "function only supposed to emit natural comparisons");
10197 
10198   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
10199   APInt CnstBits(VT.getSizeInBits(), 0);
10200   APInt UndefBits(VT.getSizeInBits(), 0);
10201   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
10202   bool IsZero = IsCnst && (CnstBits == 0);
10203 
10204   if (SrcVT.getVectorElementType().isFloatingPoint()) {
10205     switch (CC) {
10206     default:
10207       return SDValue();
10208     case AArch64CC::NE: {
10209       SDValue Fcmeq;
10210       if (IsZero)
10211         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
10212       else
10213         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
10214       return DAG.getNOT(dl, Fcmeq, VT);
10215     }
10216     case AArch64CC::EQ:
10217       if (IsZero)
10218         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
10219       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
10220     case AArch64CC::GE:
10221       if (IsZero)
10222         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
10223       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
10224     case AArch64CC::GT:
10225       if (IsZero)
10226         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
10227       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
10228     case AArch64CC::LS:
10229       if (IsZero)
10230         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
10231       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
10232     case AArch64CC::LT:
10233       if (!NoNans)
10234         return SDValue();
10235       // If we ignore NaNs then we can use to the MI implementation.
10236       LLVM_FALLTHROUGH;
10237     case AArch64CC::MI:
10238       if (IsZero)
10239         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
10240       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
10241     }
10242   }
10243 
10244   switch (CC) {
10245   default:
10246     return SDValue();
10247   case AArch64CC::NE: {
10248     SDValue Cmeq;
10249     if (IsZero)
10250       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
10251     else
10252       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
10253     return DAG.getNOT(dl, Cmeq, VT);
10254   }
10255   case AArch64CC::EQ:
10256     if (IsZero)
10257       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
10258     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
10259   case AArch64CC::GE:
10260     if (IsZero)
10261       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
10262     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
10263   case AArch64CC::GT:
10264     if (IsZero)
10265       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
10266     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
10267   case AArch64CC::LE:
10268     if (IsZero)
10269       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
10270     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
10271   case AArch64CC::LS:
10272     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
10273   case AArch64CC::LO:
10274     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
10275   case AArch64CC::LT:
10276     if (IsZero)
10277       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
10278     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
10279   case AArch64CC::HI:
10280     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
10281   case AArch64CC::HS:
10282     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
10283   }
10284 }
10285 
10286 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
10287                                            SelectionDAG &DAG) const {
10288   if (Op.getValueType().isScalableVector()) {
10289     if (Op.getOperand(0).getValueType().isFloatingPoint())
10290       return Op;
10291     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
10292   }
10293 
10294   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
10295     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
10296 
10297   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10298   SDValue LHS = Op.getOperand(0);
10299   SDValue RHS = Op.getOperand(1);
10300   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
10301   SDLoc dl(Op);
10302 
10303   if (LHS.getValueType().getVectorElementType().isInteger()) {
10304     assert(LHS.getValueType() == RHS.getValueType());
10305     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
10306     SDValue Cmp =
10307         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
10308     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
10309   }
10310 
10311   const bool FullFP16 =
10312     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
10313 
10314   // Make v4f16 (only) fcmp operations utilise vector instructions
10315   // v8f16 support will be a litle more complicated
10316   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
10317     if (LHS.getValueType().getVectorNumElements() == 4) {
10318       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
10319       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
10320       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
10321       DAG.ReplaceAllUsesWith(Op, NewSetcc);
10322       CmpVT = MVT::v4i32;
10323     } else
10324       return SDValue();
10325   }
10326 
10327   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
10328           LHS.getValueType().getVectorElementType() != MVT::f128);
10329 
10330   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
10331   // clean.  Some of them require two branches to implement.
10332   AArch64CC::CondCode CC1, CC2;
10333   bool ShouldInvert;
10334   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
10335 
10336   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
10337   SDValue Cmp =
10338       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
10339   if (!Cmp.getNode())
10340     return SDValue();
10341 
10342   if (CC2 != AArch64CC::AL) {
10343     SDValue Cmp2 =
10344         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
10345     if (!Cmp2.getNode())
10346       return SDValue();
10347 
10348     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
10349   }
10350 
10351   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
10352 
10353   if (ShouldInvert)
10354     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
10355 
10356   return Cmp;
10357 }
10358 
10359 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
10360                                   SelectionDAG &DAG) {
10361   SDValue VecOp = ScalarOp.getOperand(0);
10362   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
10363   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
10364                      DAG.getConstant(0, DL, MVT::i64));
10365 }
10366 
10367 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
10368                                               SelectionDAG &DAG) const {
10369   SDValue Src = Op.getOperand(0);
10370 
10371   // Try to lower fixed length reductions to SVE.
10372   EVT SrcVT = Src.getValueType();
10373   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
10374                       Op.getOpcode() == ISD::VECREDUCE_OR ||
10375                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
10376                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
10377                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
10378                        SrcVT.getVectorElementType() == MVT::i64);
10379   if (SrcVT.isScalableVector() ||
10380       useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
10381 
10382     if (SrcVT.getVectorElementType() == MVT::i1)
10383       return LowerPredReductionToSVE(Op, DAG);
10384 
10385     switch (Op.getOpcode()) {
10386     case ISD::VECREDUCE_ADD:
10387       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
10388     case ISD::VECREDUCE_AND:
10389       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
10390     case ISD::VECREDUCE_OR:
10391       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
10392     case ISD::VECREDUCE_SMAX:
10393       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
10394     case ISD::VECREDUCE_SMIN:
10395       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
10396     case ISD::VECREDUCE_UMAX:
10397       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
10398     case ISD::VECREDUCE_UMIN:
10399       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
10400     case ISD::VECREDUCE_XOR:
10401       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
10402     case ISD::VECREDUCE_FADD:
10403       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
10404     case ISD::VECREDUCE_FMAX:
10405       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
10406     case ISD::VECREDUCE_FMIN:
10407       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
10408     default:
10409       llvm_unreachable("Unhandled fixed length reduction");
10410     }
10411   }
10412 
10413   // Lower NEON reductions.
10414   SDLoc dl(Op);
10415   switch (Op.getOpcode()) {
10416   case ISD::VECREDUCE_ADD:
10417     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
10418   case ISD::VECREDUCE_SMAX:
10419     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
10420   case ISD::VECREDUCE_SMIN:
10421     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
10422   case ISD::VECREDUCE_UMAX:
10423     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
10424   case ISD::VECREDUCE_UMIN:
10425     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
10426   case ISD::VECREDUCE_FMAX: {
10427     return DAG.getNode(
10428         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
10429         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
10430         Src);
10431   }
10432   case ISD::VECREDUCE_FMIN: {
10433     return DAG.getNode(
10434         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
10435         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
10436         Src);
10437   }
10438   default:
10439     llvm_unreachable("Unhandled reduction");
10440   }
10441 }
10442 
10443 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
10444                                                     SelectionDAG &DAG) const {
10445   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
10446   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
10447     return SDValue();
10448 
10449   // LSE has an atomic load-add instruction, but not a load-sub.
10450   SDLoc dl(Op);
10451   MVT VT = Op.getSimpleValueType();
10452   SDValue RHS = Op.getOperand(2);
10453   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
10454   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
10455   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
10456                        Op.getOperand(0), Op.getOperand(1), RHS,
10457                        AN->getMemOperand());
10458 }
10459 
10460 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
10461                                                     SelectionDAG &DAG) const {
10462   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
10463   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
10464     return SDValue();
10465 
10466   // LSE has an atomic load-clear instruction, but not a load-and.
10467   SDLoc dl(Op);
10468   MVT VT = Op.getSimpleValueType();
10469   SDValue RHS = Op.getOperand(2);
10470   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
10471   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
10472   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
10473                        Op.getOperand(0), Op.getOperand(1), RHS,
10474                        AN->getMemOperand());
10475 }
10476 
10477 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
10478     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
10479   SDLoc dl(Op);
10480   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10481   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
10482 
10483   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10484   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
10485   if (Subtarget->hasCustomCallingConv())
10486     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
10487 
10488   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
10489                      DAG.getConstant(4, dl, MVT::i64));
10490   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
10491   Chain =
10492       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
10493                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
10494                   DAG.getRegisterMask(Mask), Chain.getValue(1));
10495   // To match the actual intent better, we should read the output from X15 here
10496   // again (instead of potentially spilling it to the stack), but rereading Size
10497   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
10498   // here.
10499 
10500   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
10501                      DAG.getConstant(4, dl, MVT::i64));
10502   return Chain;
10503 }
10504 
10505 SDValue
10506 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10507                                                SelectionDAG &DAG) const {
10508   assert(Subtarget->isTargetWindows() &&
10509          "Only Windows alloca probing supported");
10510   SDLoc dl(Op);
10511   // Get the inputs.
10512   SDNode *Node = Op.getNode();
10513   SDValue Chain = Op.getOperand(0);
10514   SDValue Size = Op.getOperand(1);
10515   MaybeAlign Align =
10516       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
10517   EVT VT = Node->getValueType(0);
10518 
10519   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
10520           "no-stack-arg-probe")) {
10521     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
10522     Chain = SP.getValue(1);
10523     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
10524     if (Align)
10525       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10526                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
10527     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
10528     SDValue Ops[2] = {SP, Chain};
10529     return DAG.getMergeValues(Ops, dl);
10530   }
10531 
10532   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
10533 
10534   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
10535 
10536   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
10537   Chain = SP.getValue(1);
10538   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
10539   if (Align)
10540     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10541                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
10542   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
10543 
10544   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
10545                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
10546 
10547   SDValue Ops[2] = {SP, Chain};
10548   return DAG.getMergeValues(Ops, dl);
10549 }
10550 
10551 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
10552                                            SelectionDAG &DAG) const {
10553   EVT VT = Op.getValueType();
10554   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
10555 
10556   SDLoc DL(Op);
10557   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
10558   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
10559                             DL, VT);
10560 }
10561 
10562 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
10563 template <unsigned NumVecs>
10564 static bool
10565 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
10566               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
10567   Info.opc = ISD::INTRINSIC_VOID;
10568   // Retrieve EC from first vector argument.
10569   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
10570   ElementCount EC = VT.getVectorElementCount();
10571 #ifndef NDEBUG
10572   // Check the assumption that all input vectors are the same type.
10573   for (unsigned I = 0; I < NumVecs; ++I)
10574     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
10575            "Invalid type.");
10576 #endif
10577   // memVT is `NumVecs * VT`.
10578   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
10579                                 EC * NumVecs);
10580   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
10581   Info.offset = 0;
10582   Info.align.reset();
10583   Info.flags = MachineMemOperand::MOStore;
10584   return true;
10585 }
10586 
10587 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10588 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10589 /// specified in the intrinsic calls.
10590 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10591                                                const CallInst &I,
10592                                                MachineFunction &MF,
10593                                                unsigned Intrinsic) const {
10594   auto &DL = I.getModule()->getDataLayout();
10595   switch (Intrinsic) {
10596   case Intrinsic::aarch64_sve_st2:
10597     return setInfoSVEStN<2>(*this, DL, Info, I);
10598   case Intrinsic::aarch64_sve_st3:
10599     return setInfoSVEStN<3>(*this, DL, Info, I);
10600   case Intrinsic::aarch64_sve_st4:
10601     return setInfoSVEStN<4>(*this, DL, Info, I);
10602   case Intrinsic::aarch64_neon_ld2:
10603   case Intrinsic::aarch64_neon_ld3:
10604   case Intrinsic::aarch64_neon_ld4:
10605   case Intrinsic::aarch64_neon_ld1x2:
10606   case Intrinsic::aarch64_neon_ld1x3:
10607   case Intrinsic::aarch64_neon_ld1x4:
10608   case Intrinsic::aarch64_neon_ld2lane:
10609   case Intrinsic::aarch64_neon_ld3lane:
10610   case Intrinsic::aarch64_neon_ld4lane:
10611   case Intrinsic::aarch64_neon_ld2r:
10612   case Intrinsic::aarch64_neon_ld3r:
10613   case Intrinsic::aarch64_neon_ld4r: {
10614     Info.opc = ISD::INTRINSIC_W_CHAIN;
10615     // Conservatively set memVT to the entire set of vectors loaded.
10616     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
10617     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10618     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10619     Info.offset = 0;
10620     Info.align.reset();
10621     // volatile loads with NEON intrinsics not supported
10622     Info.flags = MachineMemOperand::MOLoad;
10623     return true;
10624   }
10625   case Intrinsic::aarch64_neon_st2:
10626   case Intrinsic::aarch64_neon_st3:
10627   case Intrinsic::aarch64_neon_st4:
10628   case Intrinsic::aarch64_neon_st1x2:
10629   case Intrinsic::aarch64_neon_st1x3:
10630   case Intrinsic::aarch64_neon_st1x4:
10631   case Intrinsic::aarch64_neon_st2lane:
10632   case Intrinsic::aarch64_neon_st3lane:
10633   case Intrinsic::aarch64_neon_st4lane: {
10634     Info.opc = ISD::INTRINSIC_VOID;
10635     // Conservatively set memVT to the entire set of vectors stored.
10636     unsigned NumElts = 0;
10637     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10638       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10639       if (!ArgTy->isVectorTy())
10640         break;
10641       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
10642     }
10643     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10644     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10645     Info.offset = 0;
10646     Info.align.reset();
10647     // volatile stores with NEON intrinsics not supported
10648     Info.flags = MachineMemOperand::MOStore;
10649     return true;
10650   }
10651   case Intrinsic::aarch64_ldaxr:
10652   case Intrinsic::aarch64_ldxr: {
10653     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10654     Info.opc = ISD::INTRINSIC_W_CHAIN;
10655     Info.memVT = MVT::getVT(PtrTy->getElementType());
10656     Info.ptrVal = I.getArgOperand(0);
10657     Info.offset = 0;
10658     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10659     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10660     return true;
10661   }
10662   case Intrinsic::aarch64_stlxr:
10663   case Intrinsic::aarch64_stxr: {
10664     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10665     Info.opc = ISD::INTRINSIC_W_CHAIN;
10666     Info.memVT = MVT::getVT(PtrTy->getElementType());
10667     Info.ptrVal = I.getArgOperand(1);
10668     Info.offset = 0;
10669     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10670     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10671     return true;
10672   }
10673   case Intrinsic::aarch64_ldaxp:
10674   case Intrinsic::aarch64_ldxp:
10675     Info.opc = ISD::INTRINSIC_W_CHAIN;
10676     Info.memVT = MVT::i128;
10677     Info.ptrVal = I.getArgOperand(0);
10678     Info.offset = 0;
10679     Info.align = Align(16);
10680     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10681     return true;
10682   case Intrinsic::aarch64_stlxp:
10683   case Intrinsic::aarch64_stxp:
10684     Info.opc = ISD::INTRINSIC_W_CHAIN;
10685     Info.memVT = MVT::i128;
10686     Info.ptrVal = I.getArgOperand(2);
10687     Info.offset = 0;
10688     Info.align = Align(16);
10689     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10690     return true;
10691   case Intrinsic::aarch64_sve_ldnt1: {
10692     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10693     Info.opc = ISD::INTRINSIC_W_CHAIN;
10694     Info.memVT = MVT::getVT(I.getType());
10695     Info.ptrVal = I.getArgOperand(1);
10696     Info.offset = 0;
10697     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10698     Info.flags = MachineMemOperand::MOLoad;
10699     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
10700       Info.flags |= MachineMemOperand::MONonTemporal;
10701     return true;
10702   }
10703   case Intrinsic::aarch64_sve_stnt1: {
10704     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
10705     Info.opc = ISD::INTRINSIC_W_CHAIN;
10706     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
10707     Info.ptrVal = I.getArgOperand(2);
10708     Info.offset = 0;
10709     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10710     Info.flags = MachineMemOperand::MOStore;
10711     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
10712       Info.flags |= MachineMemOperand::MONonTemporal;
10713     return true;
10714   }
10715   default:
10716     break;
10717   }
10718 
10719   return false;
10720 }
10721 
10722 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
10723                                                   ISD::LoadExtType ExtTy,
10724                                                   EVT NewVT) const {
10725   // TODO: This may be worth removing. Check regression tests for diffs.
10726   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
10727     return false;
10728 
10729   // If we're reducing the load width in order to avoid having to use an extra
10730   // instruction to do extension then it's probably a good idea.
10731   if (ExtTy != ISD::NON_EXTLOAD)
10732     return true;
10733   // Don't reduce load width if it would prevent us from combining a shift into
10734   // the offset.
10735   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
10736   assert(Mem);
10737   const SDValue &Base = Mem->getBasePtr();
10738   if (Base.getOpcode() == ISD::ADD &&
10739       Base.getOperand(1).getOpcode() == ISD::SHL &&
10740       Base.getOperand(1).hasOneUse() &&
10741       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
10742     // The shift can be combined if it matches the size of the value being
10743     // loaded (and so reducing the width would make it not match).
10744     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
10745     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
10746     if (ShiftAmount == Log2_32(LoadBytes))
10747       return false;
10748   }
10749   // We have no reason to disallow reducing the load width, so allow it.
10750   return true;
10751 }
10752 
10753 // Truncations from 64-bit GPR to 32-bit GPR is free.
10754 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10755   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10756     return false;
10757   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
10758   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
10759   return NumBits1 > NumBits2;
10760 }
10761 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10762   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10763     return false;
10764   uint64_t NumBits1 = VT1.getFixedSizeInBits();
10765   uint64_t NumBits2 = VT2.getFixedSizeInBits();
10766   return NumBits1 > NumBits2;
10767 }
10768 
10769 /// Check if it is profitable to hoist instruction in then/else to if.
10770 /// Not profitable if I and it's user can form a FMA instruction
10771 /// because we prefer FMSUB/FMADD.
10772 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
10773   if (I->getOpcode() != Instruction::FMul)
10774     return true;
10775 
10776   if (!I->hasOneUse())
10777     return true;
10778 
10779   Instruction *User = I->user_back();
10780 
10781   if (User &&
10782       !(User->getOpcode() == Instruction::FSub ||
10783         User->getOpcode() == Instruction::FAdd))
10784     return true;
10785 
10786   const TargetOptions &Options = getTargetMachine().Options;
10787   const Function *F = I->getFunction();
10788   const DataLayout &DL = F->getParent()->getDataLayout();
10789   Type *Ty = User->getOperand(0)->getType();
10790 
10791   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
10792            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
10793            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
10794             Options.UnsafeFPMath));
10795 }
10796 
10797 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
10798 // 64-bit GPR.
10799 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10800   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10801     return false;
10802   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10803   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10804   return NumBits1 == 32 && NumBits2 == 64;
10805 }
10806 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10807   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10808     return false;
10809   unsigned NumBits1 = VT1.getSizeInBits();
10810   unsigned NumBits2 = VT2.getSizeInBits();
10811   return NumBits1 == 32 && NumBits2 == 64;
10812 }
10813 
10814 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10815   EVT VT1 = Val.getValueType();
10816   if (isZExtFree(VT1, VT2)) {
10817     return true;
10818   }
10819 
10820   if (Val.getOpcode() != ISD::LOAD)
10821     return false;
10822 
10823   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
10824   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
10825           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
10826           VT1.getSizeInBits() <= 32);
10827 }
10828 
10829 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
10830   if (isa<FPExtInst>(Ext))
10831     return false;
10832 
10833   // Vector types are not free.
10834   if (Ext->getType()->isVectorTy())
10835     return false;
10836 
10837   for (const Use &U : Ext->uses()) {
10838     // The extension is free if we can fold it with a left shift in an
10839     // addressing mode or an arithmetic operation: add, sub, and cmp.
10840 
10841     // Is there a shift?
10842     const Instruction *Instr = cast<Instruction>(U.getUser());
10843 
10844     // Is this a constant shift?
10845     switch (Instr->getOpcode()) {
10846     case Instruction::Shl:
10847       if (!isa<ConstantInt>(Instr->getOperand(1)))
10848         return false;
10849       break;
10850     case Instruction::GetElementPtr: {
10851       gep_type_iterator GTI = gep_type_begin(Instr);
10852       auto &DL = Ext->getModule()->getDataLayout();
10853       std::advance(GTI, U.getOperandNo()-1);
10854       Type *IdxTy = GTI.getIndexedType();
10855       // This extension will end up with a shift because of the scaling factor.
10856       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
10857       // Get the shift amount based on the scaling factor:
10858       // log2(sizeof(IdxTy)) - log2(8).
10859       uint64_t ShiftAmt =
10860         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
10861       // Is the constant foldable in the shift of the addressing mode?
10862       // I.e., shift amount is between 1 and 4 inclusive.
10863       if (ShiftAmt == 0 || ShiftAmt > 4)
10864         return false;
10865       break;
10866     }
10867     case Instruction::Trunc:
10868       // Check if this is a noop.
10869       // trunc(sext ty1 to ty2) to ty1.
10870       if (Instr->getType() == Ext->getOperand(0)->getType())
10871         continue;
10872       LLVM_FALLTHROUGH;
10873     default:
10874       return false;
10875     }
10876 
10877     // At this point we can use the bfm family, so this extension is free
10878     // for that use.
10879   }
10880   return true;
10881 }
10882 
10883 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
10884 /// or upper half of the vector elements.
10885 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
10886   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
10887     auto *FullTy = FullV->getType();
10888     auto *HalfTy = HalfV->getType();
10889     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
10890            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
10891   };
10892 
10893   auto extractHalf = [](Value *FullV, Value *HalfV) {
10894     auto *FullVT = cast<FixedVectorType>(FullV->getType());
10895     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
10896     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
10897   };
10898 
10899   ArrayRef<int> M1, M2;
10900   Value *S1Op1, *S2Op1;
10901   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
10902       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
10903     return false;
10904 
10905   // Check that the operands are half as wide as the result and we extract
10906   // half of the elements of the input vectors.
10907   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
10908       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
10909     return false;
10910 
10911   // Check the mask extracts either the lower or upper half of vector
10912   // elements.
10913   int M1Start = -1;
10914   int M2Start = -1;
10915   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
10916   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
10917       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
10918       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
10919     return false;
10920 
10921   return true;
10922 }
10923 
10924 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
10925 /// of the vector elements.
10926 static bool areExtractExts(Value *Ext1, Value *Ext2) {
10927   auto areExtDoubled = [](Instruction *Ext) {
10928     return Ext->getType()->getScalarSizeInBits() ==
10929            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
10930   };
10931 
10932   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
10933       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
10934       !areExtDoubled(cast<Instruction>(Ext1)) ||
10935       !areExtDoubled(cast<Instruction>(Ext2)))
10936     return false;
10937 
10938   return true;
10939 }
10940 
10941 /// Check if Op could be used with vmull_high_p64 intrinsic.
10942 static bool isOperandOfVmullHighP64(Value *Op) {
10943   Value *VectorOperand = nullptr;
10944   ConstantInt *ElementIndex = nullptr;
10945   return match(Op, m_ExtractElt(m_Value(VectorOperand),
10946                                 m_ConstantInt(ElementIndex))) &&
10947          ElementIndex->getValue() == 1 &&
10948          isa<FixedVectorType>(VectorOperand->getType()) &&
10949          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
10950 }
10951 
10952 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
10953 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
10954   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
10955 }
10956 
10957 /// Check if sinking \p I's operands to I's basic block is profitable, because
10958 /// the operands can be folded into a target instruction, e.g.
10959 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
10960 bool AArch64TargetLowering::shouldSinkOperands(
10961     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
10962   if (!I->getType()->isVectorTy())
10963     return false;
10964 
10965   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
10966     switch (II->getIntrinsicID()) {
10967     case Intrinsic::aarch64_neon_umull:
10968       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
10969         return false;
10970       Ops.push_back(&II->getOperandUse(0));
10971       Ops.push_back(&II->getOperandUse(1));
10972       return true;
10973 
10974     case Intrinsic::aarch64_neon_pmull64:
10975       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
10976                                      II->getArgOperand(1)))
10977         return false;
10978       Ops.push_back(&II->getArgOperandUse(0));
10979       Ops.push_back(&II->getArgOperandUse(1));
10980       return true;
10981 
10982     default:
10983       return false;
10984     }
10985   }
10986 
10987   switch (I->getOpcode()) {
10988   case Instruction::Sub:
10989   case Instruction::Add: {
10990     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
10991       return false;
10992 
10993     // If the exts' operands extract either the lower or upper elements, we
10994     // can sink them too.
10995     auto Ext1 = cast<Instruction>(I->getOperand(0));
10996     auto Ext2 = cast<Instruction>(I->getOperand(1));
10997     if (areExtractShuffleVectors(Ext1, Ext2)) {
10998       Ops.push_back(&Ext1->getOperandUse(0));
10999       Ops.push_back(&Ext2->getOperandUse(0));
11000     }
11001 
11002     Ops.push_back(&I->getOperandUse(0));
11003     Ops.push_back(&I->getOperandUse(1));
11004 
11005     return true;
11006   }
11007   case Instruction::Mul: {
11008     bool IsProfitable = false;
11009     for (auto &Op : I->operands()) {
11010       // Make sure we are not already sinking this operand
11011       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
11012         continue;
11013 
11014       ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
11015       if (!Shuffle || !Shuffle->isZeroEltSplat())
11016         continue;
11017 
11018       Value *ShuffleOperand = Shuffle->getOperand(0);
11019       InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
11020       if (!Insert)
11021         continue;
11022 
11023       Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
11024       if (!OperandInstr)
11025         continue;
11026 
11027       ConstantInt *ElementConstant =
11028           dyn_cast<ConstantInt>(Insert->getOperand(2));
11029       // Check that the insertelement is inserting into element 0
11030       if (!ElementConstant || ElementConstant->getZExtValue() != 0)
11031         continue;
11032 
11033       unsigned Opcode = OperandInstr->getOpcode();
11034       if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
11035         continue;
11036 
11037       Ops.push_back(&Shuffle->getOperandUse(0));
11038       Ops.push_back(&Op);
11039       IsProfitable = true;
11040     }
11041 
11042     return IsProfitable;
11043   }
11044   default:
11045     return false;
11046   }
11047   return false;
11048 }
11049 
11050 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
11051                                           Align &RequiredAligment) const {
11052   if (!LoadedType.isSimple() ||
11053       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
11054     return false;
11055   // Cyclone supports unaligned accesses.
11056   RequiredAligment = Align(1);
11057   unsigned NumBits = LoadedType.getSizeInBits();
11058   return NumBits == 32 || NumBits == 64;
11059 }
11060 
11061 /// A helper function for determining the number of interleaved accesses we
11062 /// will generate when lowering accesses of the given type.
11063 unsigned
11064 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
11065                                                  const DataLayout &DL) const {
11066   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
11067 }
11068 
11069 MachineMemOperand::Flags
11070 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
11071   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
11072       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
11073     return MOStridedAccess;
11074   return MachineMemOperand::MONone;
11075 }
11076 
11077 bool AArch64TargetLowering::isLegalInterleavedAccessType(
11078     VectorType *VecTy, const DataLayout &DL) const {
11079 
11080   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
11081   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
11082 
11083   // Ensure the number of vector elements is greater than 1.
11084   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
11085     return false;
11086 
11087   // Ensure the element type is legal.
11088   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
11089     return false;
11090 
11091   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
11092   // 128 will be split into multiple interleaved accesses.
11093   return VecSize == 64 || VecSize % 128 == 0;
11094 }
11095 
11096 /// Lower an interleaved load into a ldN intrinsic.
11097 ///
11098 /// E.g. Lower an interleaved load (Factor = 2):
11099 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
11100 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11101 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11102 ///
11103 ///      Into:
11104 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
11105 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
11106 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
11107 bool AArch64TargetLowering::lowerInterleavedLoad(
11108     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11109     ArrayRef<unsigned> Indices, unsigned Factor) const {
11110   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11111          "Invalid interleave factor");
11112   assert(!Shuffles.empty() && "Empty shufflevector input");
11113   assert(Shuffles.size() == Indices.size() &&
11114          "Unmatched number of shufflevectors and indices");
11115 
11116   const DataLayout &DL = LI->getModule()->getDataLayout();
11117 
11118   VectorType *VTy = Shuffles[0]->getType();
11119 
11120   // Skip if we do not have NEON and skip illegal vector types. We can
11121   // "legalize" wide vector types into multiple interleaved accesses as long as
11122   // the vector types are divisible by 128.
11123   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
11124     return false;
11125 
11126   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
11127 
11128   auto *FVTy = cast<FixedVectorType>(VTy);
11129 
11130   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11131   // load integer vectors first and then convert to pointer vectors.
11132   Type *EltTy = FVTy->getElementType();
11133   if (EltTy->isPointerTy())
11134     FVTy =
11135         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
11136 
11137   IRBuilder<> Builder(LI);
11138 
11139   // The base address of the load.
11140   Value *BaseAddr = LI->getPointerOperand();
11141 
11142   if (NumLoads > 1) {
11143     // If we're going to generate more than one load, reset the sub-vector type
11144     // to something legal.
11145     FVTy = FixedVectorType::get(FVTy->getElementType(),
11146                                 FVTy->getNumElements() / NumLoads);
11147 
11148     // We will compute the pointer operand of each load from the original base
11149     // address using GEPs. Cast the base address to a pointer to the scalar
11150     // element type.
11151     BaseAddr = Builder.CreateBitCast(
11152         BaseAddr,
11153         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
11154   }
11155 
11156   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
11157   Type *Tys[2] = {FVTy, PtrTy};
11158   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
11159                                             Intrinsic::aarch64_neon_ld3,
11160                                             Intrinsic::aarch64_neon_ld4};
11161   Function *LdNFunc =
11162       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11163 
11164   // Holds sub-vectors extracted from the load intrinsic return values. The
11165   // sub-vectors are associated with the shufflevector instructions they will
11166   // replace.
11167   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
11168 
11169   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
11170 
11171     // If we're generating more than one load, compute the base address of
11172     // subsequent loads as an offset from the previous.
11173     if (LoadCount > 0)
11174       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
11175                                             FVTy->getNumElements() * Factor);
11176 
11177     CallInst *LdN = Builder.CreateCall(
11178         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
11179 
11180     // Extract and store the sub-vectors returned by the load intrinsic.
11181     for (unsigned i = 0; i < Shuffles.size(); i++) {
11182       ShuffleVectorInst *SVI = Shuffles[i];
11183       unsigned Index = Indices[i];
11184 
11185       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
11186 
11187       // Convert the integer vector to pointer vector if the element is pointer.
11188       if (EltTy->isPointerTy())
11189         SubVec = Builder.CreateIntToPtr(
11190             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
11191                                          FVTy->getNumElements()));
11192       SubVecs[SVI].push_back(SubVec);
11193     }
11194   }
11195 
11196   // Replace uses of the shufflevector instructions with the sub-vectors
11197   // returned by the load intrinsic. If a shufflevector instruction is
11198   // associated with more than one sub-vector, those sub-vectors will be
11199   // concatenated into a single wide vector.
11200   for (ShuffleVectorInst *SVI : Shuffles) {
11201     auto &SubVec = SubVecs[SVI];
11202     auto *WideVec =
11203         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
11204     SVI->replaceAllUsesWith(WideVec);
11205   }
11206 
11207   return true;
11208 }
11209 
11210 /// Lower an interleaved store into a stN intrinsic.
11211 ///
11212 /// E.g. Lower an interleaved store (Factor = 3):
11213 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11214 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11215 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
11216 ///
11217 ///      Into:
11218 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11219 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11220 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11221 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
11222 ///
11223 /// Note that the new shufflevectors will be removed and we'll only generate one
11224 /// st3 instruction in CodeGen.
11225 ///
11226 /// Example for a more general valid mask (Factor 3). Lower:
11227 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
11228 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
11229 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
11230 ///
11231 ///      Into:
11232 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
11233 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
11234 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
11235 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
11236 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
11237                                                   ShuffleVectorInst *SVI,
11238                                                   unsigned Factor) const {
11239   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11240          "Invalid interleave factor");
11241 
11242   auto *VecTy = cast<FixedVectorType>(SVI->getType());
11243   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
11244 
11245   unsigned LaneLen = VecTy->getNumElements() / Factor;
11246   Type *EltTy = VecTy->getElementType();
11247   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
11248 
11249   const DataLayout &DL = SI->getModule()->getDataLayout();
11250 
11251   // Skip if we do not have NEON and skip illegal vector types. We can
11252   // "legalize" wide vector types into multiple interleaved accesses as long as
11253   // the vector types are divisible by 128.
11254   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
11255     return false;
11256 
11257   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
11258 
11259   Value *Op0 = SVI->getOperand(0);
11260   Value *Op1 = SVI->getOperand(1);
11261   IRBuilder<> Builder(SI);
11262 
11263   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11264   // vectors to integer vectors.
11265   if (EltTy->isPointerTy()) {
11266     Type *IntTy = DL.getIntPtrType(EltTy);
11267     unsigned NumOpElts =
11268         cast<FixedVectorType>(Op0->getType())->getNumElements();
11269 
11270     // Convert to the corresponding integer vector.
11271     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
11272     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11273     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11274 
11275     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
11276   }
11277 
11278   // The base address of the store.
11279   Value *BaseAddr = SI->getPointerOperand();
11280 
11281   if (NumStores > 1) {
11282     // If we're going to generate more than one store, reset the lane length
11283     // and sub-vector type to something legal.
11284     LaneLen /= NumStores;
11285     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
11286 
11287     // We will compute the pointer operand of each store from the original base
11288     // address using GEPs. Cast the base address to a pointer to the scalar
11289     // element type.
11290     BaseAddr = Builder.CreateBitCast(
11291         BaseAddr,
11292         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
11293   }
11294 
11295   auto Mask = SVI->getShuffleMask();
11296 
11297   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
11298   Type *Tys[2] = {SubVecTy, PtrTy};
11299   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
11300                                              Intrinsic::aarch64_neon_st3,
11301                                              Intrinsic::aarch64_neon_st4};
11302   Function *StNFunc =
11303       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
11304 
11305   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
11306 
11307     SmallVector<Value *, 5> Ops;
11308 
11309     // Split the shufflevector operands into sub vectors for the new stN call.
11310     for (unsigned i = 0; i < Factor; i++) {
11311       unsigned IdxI = StoreCount * LaneLen * Factor + i;
11312       if (Mask[IdxI] >= 0) {
11313         Ops.push_back(Builder.CreateShuffleVector(
11314             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
11315       } else {
11316         unsigned StartMask = 0;
11317         for (unsigned j = 1; j < LaneLen; j++) {
11318           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
11319           if (Mask[IdxJ * Factor + IdxI] >= 0) {
11320             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
11321             break;
11322           }
11323         }
11324         // Note: Filling undef gaps with random elements is ok, since
11325         // those elements were being written anyway (with undefs).
11326         // In the case of all undefs we're defaulting to using elems from 0
11327         // Note: StartMask cannot be negative, it's checked in
11328         // isReInterleaveMask
11329         Ops.push_back(Builder.CreateShuffleVector(
11330             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
11331       }
11332     }
11333 
11334     // If we generating more than one store, we compute the base address of
11335     // subsequent stores as an offset from the previous.
11336     if (StoreCount > 0)
11337       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
11338                                             BaseAddr, LaneLen * Factor);
11339 
11340     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
11341     Builder.CreateCall(StNFunc, Ops);
11342   }
11343   return true;
11344 }
11345 
11346 // Lower an SVE structured load intrinsic returning a tuple type to target
11347 // specific intrinsic taking the same input but returning a multi-result value
11348 // of the split tuple type.
11349 //
11350 // E.g. Lowering an LD3:
11351 //
11352 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
11353 //                                                    <vscale x 4 x i1> %pred,
11354 //                                                    <vscale x 4 x i32>* %addr)
11355 //
11356 //  Output DAG:
11357 //
11358 //    t0: ch = EntryToken
11359 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
11360 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
11361 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
11362 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
11363 //
11364 // This is called pre-legalization to avoid widening/splitting issues with
11365 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
11366 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
11367                                                   ArrayRef<SDValue> LoadOps,
11368                                                   EVT VT, SelectionDAG &DAG,
11369                                                   const SDLoc &DL) const {
11370   assert(VT.isScalableVector() && "Can only lower scalable vectors");
11371 
11372   unsigned N, Opcode;
11373   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
11374       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
11375       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
11376       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
11377 
11378   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
11379   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
11380          "invalid tuple vector type!");
11381 
11382   EVT SplitVT =
11383       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
11384                        VT.getVectorElementCount().divideCoefficientBy(N));
11385   assert(isTypeLegal(SplitVT));
11386 
11387   SmallVector<EVT, 5> VTs(N, SplitVT);
11388   VTs.push_back(MVT::Other); // Chain
11389   SDVTList NodeTys = DAG.getVTList(VTs);
11390 
11391   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
11392   SmallVector<SDValue, 4> PseudoLoadOps;
11393   for (unsigned I = 0; I < N; ++I)
11394     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
11395   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
11396 }
11397 
11398 EVT AArch64TargetLowering::getOptimalMemOpType(
11399     const MemOp &Op, const AttributeList &FuncAttributes) const {
11400   bool CanImplicitFloat =
11401       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
11402   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
11403   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
11404   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
11405   // taken one instruction to materialize the v2i64 zero and one store (with
11406   // restrictive addressing mode). Just do i64 stores.
11407   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
11408   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
11409     if (Op.isAligned(AlignCheck))
11410       return true;
11411     bool Fast;
11412     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
11413                                           MachineMemOperand::MONone, &Fast) &&
11414            Fast;
11415   };
11416 
11417   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
11418       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
11419     return MVT::v2i64;
11420   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
11421     return MVT::f128;
11422   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
11423     return MVT::i64;
11424   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
11425     return MVT::i32;
11426   return MVT::Other;
11427 }
11428 
11429 LLT AArch64TargetLowering::getOptimalMemOpLLT(
11430     const MemOp &Op, const AttributeList &FuncAttributes) const {
11431   bool CanImplicitFloat =
11432       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
11433   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
11434   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
11435   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
11436   // taken one instruction to materialize the v2i64 zero and one store (with
11437   // restrictive addressing mode). Just do i64 stores.
11438   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
11439   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
11440     if (Op.isAligned(AlignCheck))
11441       return true;
11442     bool Fast;
11443     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
11444                                           MachineMemOperand::MONone, &Fast) &&
11445            Fast;
11446   };
11447 
11448   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
11449       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
11450     return LLT::vector(2, 64);
11451   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
11452     return LLT::scalar(128);
11453   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
11454     return LLT::scalar(64);
11455   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
11456     return LLT::scalar(32);
11457   return LLT();
11458 }
11459 
11460 // 12-bit optionally shifted immediates are legal for adds.
11461 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
11462   if (Immed == std::numeric_limits<int64_t>::min()) {
11463     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
11464                       << ": avoid UB for INT64_MIN\n");
11465     return false;
11466   }
11467   // Same encoding for add/sub, just flip the sign.
11468   Immed = std::abs(Immed);
11469   bool IsLegal = ((Immed >> 12) == 0 ||
11470                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
11471   LLVM_DEBUG(dbgs() << "Is " << Immed
11472                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
11473   return IsLegal;
11474 }
11475 
11476 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
11477 // immediates is the same as for an add or a sub.
11478 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
11479   return isLegalAddImmediate(Immed);
11480 }
11481 
11482 /// isLegalAddressingMode - Return true if the addressing mode represented
11483 /// by AM is legal for this target, for a load/store of the specified type.
11484 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
11485                                                   const AddrMode &AM, Type *Ty,
11486                                                   unsigned AS, Instruction *I) const {
11487   // AArch64 has five basic addressing modes:
11488   //  reg
11489   //  reg + 9-bit signed offset
11490   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
11491   //  reg1 + reg2
11492   //  reg + SIZE_IN_BYTES * reg
11493 
11494   // No global is ever allowed as a base.
11495   if (AM.BaseGV)
11496     return false;
11497 
11498   // No reg+reg+imm addressing.
11499   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
11500     return false;
11501 
11502   // FIXME: Update this method to support scalable addressing modes.
11503   if (isa<ScalableVectorType>(Ty))
11504     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
11505 
11506   // check reg + imm case:
11507   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
11508   uint64_t NumBytes = 0;
11509   if (Ty->isSized()) {
11510     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
11511     NumBytes = NumBits / 8;
11512     if (!isPowerOf2_64(NumBits))
11513       NumBytes = 0;
11514   }
11515 
11516   if (!AM.Scale) {
11517     int64_t Offset = AM.BaseOffs;
11518 
11519     // 9-bit signed offset
11520     if (isInt<9>(Offset))
11521       return true;
11522 
11523     // 12-bit unsigned offset
11524     unsigned shift = Log2_64(NumBytes);
11525     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11526         // Must be a multiple of NumBytes (NumBytes is a power of 2)
11527         (Offset >> shift) << shift == Offset)
11528       return true;
11529     return false;
11530   }
11531 
11532   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11533 
11534   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
11535 }
11536 
11537 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
11538   // Consider splitting large offset of struct or array.
11539   return true;
11540 }
11541 
11542 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
11543                                                 const AddrMode &AM, Type *Ty,
11544                                                 unsigned AS) const {
11545   // Scaling factors are not free at all.
11546   // Operands                     | Rt Latency
11547   // -------------------------------------------
11548   // Rt, [Xn, Xm]                 | 4
11549   // -------------------------------------------
11550   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
11551   // Rt, [Xn, Wm, <extend> #imm]  |
11552   if (isLegalAddressingMode(DL, AM, Ty, AS))
11553     // Scale represents reg2 * scale, thus account for 1 if
11554     // it is not equal to 0 or 1.
11555     return AM.Scale != 0 && AM.Scale != 1;
11556   return -1;
11557 }
11558 
11559 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
11560     const MachineFunction &MF, EVT VT) const {
11561   VT = VT.getScalarType();
11562 
11563   if (!VT.isSimple())
11564     return false;
11565 
11566   switch (VT.getSimpleVT().SimpleTy) {
11567   case MVT::f32:
11568   case MVT::f64:
11569     return true;
11570   default:
11571     break;
11572   }
11573 
11574   return false;
11575 }
11576 
11577 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
11578                                                        Type *Ty) const {
11579   switch (Ty->getScalarType()->getTypeID()) {
11580   case Type::FloatTyID:
11581   case Type::DoubleTyID:
11582     return true;
11583   default:
11584     return false;
11585   }
11586 }
11587 
11588 const MCPhysReg *
11589 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
11590   // LR is a callee-save register, but we must treat it as clobbered by any call
11591   // site. Hence we include LR in the scratch registers, which are in turn added
11592   // as implicit-defs for stackmaps and patchpoints.
11593   static const MCPhysReg ScratchRegs[] = {
11594     AArch64::X16, AArch64::X17, AArch64::LR, 0
11595   };
11596   return ScratchRegs;
11597 }
11598 
11599 bool
11600 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11601                                                      CombineLevel Level) const {
11602   N = N->getOperand(0).getNode();
11603   EVT VT = N->getValueType(0);
11604     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
11605     // it with shift to let it be lowered to UBFX.
11606   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
11607       isa<ConstantSDNode>(N->getOperand(1))) {
11608     uint64_t TruncMask = N->getConstantOperandVal(1);
11609     if (isMask_64(TruncMask) &&
11610       N->getOperand(0).getOpcode() == ISD::SRL &&
11611       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
11612       return false;
11613   }
11614   return true;
11615 }
11616 
11617 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11618                                                               Type *Ty) const {
11619   assert(Ty->isIntegerTy());
11620 
11621   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11622   if (BitSize == 0)
11623     return false;
11624 
11625   int64_t Val = Imm.getSExtValue();
11626   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
11627     return true;
11628 
11629   if ((int64_t)Val < 0)
11630     Val = ~Val;
11631   if (BitSize == 32)
11632     Val &= (1LL << 32) - 1;
11633 
11634   unsigned LZ = countLeadingZeros((uint64_t)Val);
11635   unsigned Shift = (63 - LZ) / 16;
11636   // MOVZ is free so return true for one or fewer MOVK.
11637   return Shift < 3;
11638 }
11639 
11640 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
11641                                                     unsigned Index) const {
11642   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
11643     return false;
11644 
11645   return (Index == 0 || Index == ResVT.getVectorNumElements());
11646 }
11647 
11648 /// Turn vector tests of the signbit in the form of:
11649 ///   xor (sra X, elt_size(X)-1), -1
11650 /// into:
11651 ///   cmge X, X, #0
11652 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
11653                                          const AArch64Subtarget *Subtarget) {
11654   EVT VT = N->getValueType(0);
11655   if (!Subtarget->hasNEON() || !VT.isVector())
11656     return SDValue();
11657 
11658   // There must be a shift right algebraic before the xor, and the xor must be a
11659   // 'not' operation.
11660   SDValue Shift = N->getOperand(0);
11661   SDValue Ones = N->getOperand(1);
11662   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
11663       !ISD::isBuildVectorAllOnes(Ones.getNode()))
11664     return SDValue();
11665 
11666   // The shift should be smearing the sign bit across each vector element.
11667   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
11668   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
11669   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
11670     return SDValue();
11671 
11672   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
11673 }
11674 
11675 // VECREDUCE_ADD( EXTEND(v16i8_type) ) to
11676 // VECREDUCE_ADD( DOTv16i8(v16i8_type) )
11677 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
11678                                           const AArch64Subtarget *ST) {
11679   SDValue Op0 = N->getOperand(0);
11680   if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32)
11681     return SDValue();
11682 
11683   if (Op0.getValueType().getVectorElementType() != MVT::i32)
11684     return SDValue();
11685 
11686   unsigned ExtOpcode = Op0.getOpcode();
11687   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
11688     return SDValue();
11689 
11690   EVT Op0VT = Op0.getOperand(0).getValueType();
11691   if (Op0VT != MVT::v16i8)
11692     return SDValue();
11693 
11694   SDLoc DL(Op0);
11695   SDValue Ones = DAG.getConstant(1, DL, Op0VT);
11696   SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
11697   auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND)
11698                          ? Intrinsic::aarch64_neon_udot
11699                          : Intrinsic::aarch64_neon_sdot;
11700   SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(),
11701                             DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros,
11702                             Ones, Op0.getOperand(0));
11703   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
11704 }
11705 
11706 // Given a ABS node, detect the following pattern:
11707 // (ABS (SUB (EXTEND a), (EXTEND b))).
11708 // Generates UABD/SABD instruction.
11709 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG,
11710                                  TargetLowering::DAGCombinerInfo &DCI,
11711                                  const AArch64Subtarget *Subtarget) {
11712   SDValue AbsOp1 = N->getOperand(0);
11713   SDValue Op0, Op1;
11714 
11715   if (AbsOp1.getOpcode() != ISD::SUB)
11716     return SDValue();
11717 
11718   Op0 = AbsOp1.getOperand(0);
11719   Op1 = AbsOp1.getOperand(1);
11720 
11721   unsigned Opc0 = Op0.getOpcode();
11722   // Check if the operands of the sub are (zero|sign)-extended.
11723   if (Opc0 != Op1.getOpcode() ||
11724       (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
11725     return SDValue();
11726 
11727   EVT VectorT1 = Op0.getOperand(0).getValueType();
11728   EVT VectorT2 = Op1.getOperand(0).getValueType();
11729   // Check if vectors are of same type and valid size.
11730   uint64_t Size = VectorT1.getFixedSizeInBits();
11731   if (VectorT1 != VectorT2 || (Size != 64 && Size != 128))
11732     return SDValue();
11733 
11734   // Check if vector element types are valid.
11735   EVT VT1 = VectorT1.getVectorElementType();
11736   if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32)
11737     return SDValue();
11738 
11739   Op0 = Op0.getOperand(0);
11740   Op1 = Op1.getOperand(0);
11741   unsigned ABDOpcode =
11742       (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD;
11743   SDValue ABD =
11744       DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
11745   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
11746 }
11747 
11748 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
11749                                  TargetLowering::DAGCombinerInfo &DCI,
11750                                  const AArch64Subtarget *Subtarget) {
11751   if (DCI.isBeforeLegalizeOps())
11752     return SDValue();
11753 
11754   return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
11755 }
11756 
11757 SDValue
11758 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11759                                      SelectionDAG &DAG,
11760                                      SmallVectorImpl<SDNode *> &Created) const {
11761   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11762   if (isIntDivCheap(N->getValueType(0), Attr))
11763     return SDValue(N,0); // Lower SDIV as SDIV
11764 
11765   // fold (sdiv X, pow2)
11766   EVT VT = N->getValueType(0);
11767   if ((VT != MVT::i32 && VT != MVT::i64) ||
11768       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11769     return SDValue();
11770 
11771   SDLoc DL(N);
11772   SDValue N0 = N->getOperand(0);
11773   unsigned Lg2 = Divisor.countTrailingZeros();
11774   SDValue Zero = DAG.getConstant(0, DL, VT);
11775   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11776 
11777   // Add (N0 < 0) ? Pow2 - 1 : 0;
11778   SDValue CCVal;
11779   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
11780   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11781   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
11782 
11783   Created.push_back(Cmp.getNode());
11784   Created.push_back(Add.getNode());
11785   Created.push_back(CSel.getNode());
11786 
11787   // Divide by pow2.
11788   SDValue SRA =
11789       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
11790 
11791   // If we're dividing by a positive value, we're done.  Otherwise, we must
11792   // negate the result.
11793   if (Divisor.isNonNegative())
11794     return SRA;
11795 
11796   Created.push_back(SRA.getNode());
11797   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11798 }
11799 
11800 static bool IsSVECntIntrinsic(SDValue S) {
11801   switch(getIntrinsicID(S.getNode())) {
11802   default:
11803     break;
11804   case Intrinsic::aarch64_sve_cntb:
11805   case Intrinsic::aarch64_sve_cnth:
11806   case Intrinsic::aarch64_sve_cntw:
11807   case Intrinsic::aarch64_sve_cntd:
11808     return true;
11809   }
11810   return false;
11811 }
11812 
11813 /// Calculates what the pre-extend type is, based on the extension
11814 /// operation node provided by \p Extend.
11815 ///
11816 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
11817 /// pre-extend type is pulled directly from the operand, while other extend
11818 /// operations need a bit more inspection to get this information.
11819 ///
11820 /// \param Extend The SDNode from the DAG that represents the extend operation
11821 /// \param DAG The SelectionDAG hosting the \p Extend node
11822 ///
11823 /// \returns The type representing the \p Extend source type, or \p MVT::Other
11824 /// if no valid type can be determined
11825 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
11826   switch (Extend.getOpcode()) {
11827   case ISD::SIGN_EXTEND:
11828   case ISD::ZERO_EXTEND:
11829     return Extend.getOperand(0).getValueType();
11830   case ISD::AssertSext:
11831   case ISD::AssertZext:
11832   case ISD::SIGN_EXTEND_INREG: {
11833     VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
11834     if (!TypeNode)
11835       return MVT::Other;
11836     return TypeNode->getVT();
11837   }
11838   case ISD::AND: {
11839     ConstantSDNode *Constant =
11840         dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
11841     if (!Constant)
11842       return MVT::Other;
11843 
11844     uint32_t Mask = Constant->getZExtValue();
11845 
11846     if (Mask == UCHAR_MAX)
11847       return MVT::i8;
11848     else if (Mask == USHRT_MAX)
11849       return MVT::i16;
11850     else if (Mask == UINT_MAX)
11851       return MVT::i32;
11852 
11853     return MVT::Other;
11854   }
11855   default:
11856     return MVT::Other;
11857   }
11858 
11859   llvm_unreachable("Code path unhandled in calculatePreExtendType!");
11860 }
11861 
11862 /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
11863 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
11864 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
11865                                                 SelectionDAG &DAG) {
11866 
11867   ShuffleVectorSDNode *ShuffleNode =
11868       dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
11869   if (!ShuffleNode)
11870     return SDValue();
11871 
11872   // Ensuring the mask is zero before continuing
11873   if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
11874     return SDValue();
11875 
11876   SDValue InsertVectorElt = VectorShuffle.getOperand(0);
11877 
11878   if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
11879     return SDValue();
11880 
11881   SDValue InsertLane = InsertVectorElt.getOperand(2);
11882   ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
11883   // Ensures the insert is inserting into lane 0
11884   if (!Constant || Constant->getZExtValue() != 0)
11885     return SDValue();
11886 
11887   SDValue Extend = InsertVectorElt.getOperand(1);
11888   unsigned ExtendOpcode = Extend.getOpcode();
11889 
11890   bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
11891                 ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
11892                 ExtendOpcode == ISD::AssertSext;
11893   if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
11894       ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
11895     return SDValue();
11896 
11897   EVT TargetType = VectorShuffle.getValueType();
11898   EVT PreExtendType = calculatePreExtendType(Extend, DAG);
11899 
11900   if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
11901        TargetType != MVT::v2i64) ||
11902       (PreExtendType == MVT::Other))
11903     return SDValue();
11904 
11905   // Restrict valid pre-extend data type
11906   if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
11907       PreExtendType != MVT::i32)
11908     return SDValue();
11909 
11910   EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
11911 
11912   if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
11913     return SDValue();
11914 
11915   if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
11916     return SDValue();
11917 
11918   SDLoc DL(VectorShuffle);
11919 
11920   SDValue InsertVectorNode = DAG.getNode(
11921       InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
11922       DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
11923       DAG.getConstant(0, DL, MVT::i64));
11924 
11925   std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue());
11926 
11927   SDValue VectorShuffleNode =
11928       DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
11929                            DAG.getUNDEF(PreExtendVT), ShuffleMask);
11930 
11931   SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11932                                    DL, TargetType, VectorShuffleNode);
11933 
11934   return ExtendNode;
11935 }
11936 
11937 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
11938 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
11939 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
11940   // If the value type isn't a vector, none of the operands are going to be dups
11941   if (!Mul->getValueType(0).isVector())
11942     return SDValue();
11943 
11944   SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
11945   SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
11946 
11947   // Neither operands have been changed, don't make any further changes
11948   if (!Op0 && !Op1)
11949     return SDValue();
11950 
11951   SDLoc DL(Mul);
11952   return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
11953                      Op0 ? Op0 : Mul->getOperand(0),
11954                      Op1 ? Op1 : Mul->getOperand(1));
11955 }
11956 
11957 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
11958                                  TargetLowering::DAGCombinerInfo &DCI,
11959                                  const AArch64Subtarget *Subtarget) {
11960 
11961   if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
11962     return Ext;
11963 
11964   if (DCI.isBeforeLegalizeOps())
11965     return SDValue();
11966 
11967   // The below optimizations require a constant RHS.
11968   if (!isa<ConstantSDNode>(N->getOperand(1)))
11969     return SDValue();
11970 
11971   SDValue N0 = N->getOperand(0);
11972   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
11973   const APInt &ConstValue = C->getAPIntValue();
11974 
11975   // Allow the scaling to be folded into the `cnt` instruction by preventing
11976   // the scaling to be obscured here. This makes it easier to pattern match.
11977   if (IsSVECntIntrinsic(N0) ||
11978      (N0->getOpcode() == ISD::TRUNCATE &&
11979       (IsSVECntIntrinsic(N0->getOperand(0)))))
11980        if (ConstValue.sge(1) && ConstValue.sle(16))
11981          return SDValue();
11982 
11983   // Multiplication of a power of two plus/minus one can be done more
11984   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
11985   // future CPUs have a cheaper MADD instruction, this may need to be
11986   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
11987   // 64-bit is 5 cycles, so this is always a win.
11988   // More aggressively, some multiplications N0 * C can be lowered to
11989   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
11990   // e.g. 6=3*2=(2+1)*2.
11991   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
11992   // which equals to (1+2)*16-(1+2).
11993   // TrailingZeroes is used to test if the mul can be lowered to
11994   // shift+add+shift.
11995   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
11996   if (TrailingZeroes) {
11997     // Conservatively do not lower to shift+add+shift if the mul might be
11998     // folded into smul or umul.
11999     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
12000                             isZeroExtended(N0.getNode(), DAG)))
12001       return SDValue();
12002     // Conservatively do not lower to shift+add+shift if the mul might be
12003     // folded into madd or msub.
12004     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
12005                            N->use_begin()->getOpcode() == ISD::SUB))
12006       return SDValue();
12007   }
12008   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
12009   // and shift+add+shift.
12010   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
12011 
12012   unsigned ShiftAmt, AddSubOpc;
12013   // Is the shifted value the LHS operand of the add/sub?
12014   bool ShiftValUseIsN0 = true;
12015   // Do we need to negate the result?
12016   bool NegateResult = false;
12017 
12018   if (ConstValue.isNonNegative()) {
12019     // (mul x, 2^N + 1) => (add (shl x, N), x)
12020     // (mul x, 2^N - 1) => (sub (shl x, N), x)
12021     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
12022     APInt SCVMinus1 = ShiftedConstValue - 1;
12023     APInt CVPlus1 = ConstValue + 1;
12024     if (SCVMinus1.isPowerOf2()) {
12025       ShiftAmt = SCVMinus1.logBase2();
12026       AddSubOpc = ISD::ADD;
12027     } else if (CVPlus1.isPowerOf2()) {
12028       ShiftAmt = CVPlus1.logBase2();
12029       AddSubOpc = ISD::SUB;
12030     } else
12031       return SDValue();
12032   } else {
12033     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12034     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12035     APInt CVNegPlus1 = -ConstValue + 1;
12036     APInt CVNegMinus1 = -ConstValue - 1;
12037     if (CVNegPlus1.isPowerOf2()) {
12038       ShiftAmt = CVNegPlus1.logBase2();
12039       AddSubOpc = ISD::SUB;
12040       ShiftValUseIsN0 = false;
12041     } else if (CVNegMinus1.isPowerOf2()) {
12042       ShiftAmt = CVNegMinus1.logBase2();
12043       AddSubOpc = ISD::ADD;
12044       NegateResult = true;
12045     } else
12046       return SDValue();
12047   }
12048 
12049   SDLoc DL(N);
12050   EVT VT = N->getValueType(0);
12051   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
12052                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
12053 
12054   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
12055   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
12056   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
12057   assert(!(NegateResult && TrailingZeroes) &&
12058          "NegateResult and TrailingZeroes cannot both be true for now.");
12059   // Negate the result.
12060   if (NegateResult)
12061     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
12062   // Shift the result.
12063   if (TrailingZeroes)
12064     return DAG.getNode(ISD::SHL, DL, VT, Res,
12065                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
12066   return Res;
12067 }
12068 
12069 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
12070                                                          SelectionDAG &DAG) {
12071   // Take advantage of vector comparisons producing 0 or -1 in each lane to
12072   // optimize away operation when it's from a constant.
12073   //
12074   // The general transformation is:
12075   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
12076   //       AND(VECTOR_CMP(x,y), constant2)
12077   //    constant2 = UNARYOP(constant)
12078 
12079   // Early exit if this isn't a vector operation, the operand of the
12080   // unary operation isn't a bitwise AND, or if the sizes of the operations
12081   // aren't the same.
12082   EVT VT = N->getValueType(0);
12083   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
12084       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
12085       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
12086     return SDValue();
12087 
12088   // Now check that the other operand of the AND is a constant. We could
12089   // make the transformation for non-constant splats as well, but it's unclear
12090   // that would be a benefit as it would not eliminate any operations, just
12091   // perform one more step in scalar code before moving to the vector unit.
12092   if (BuildVectorSDNode *BV =
12093           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
12094     // Bail out if the vector isn't a constant.
12095     if (!BV->isConstant())
12096       return SDValue();
12097 
12098     // Everything checks out. Build up the new and improved node.
12099     SDLoc DL(N);
12100     EVT IntVT = BV->getValueType(0);
12101     // Create a new constant of the appropriate type for the transformed
12102     // DAG.
12103     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
12104     // The AND node needs bitcasts to/from an integer vector type around it.
12105     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
12106     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
12107                                  N->getOperand(0)->getOperand(0), MaskConst);
12108     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
12109     return Res;
12110   }
12111 
12112   return SDValue();
12113 }
12114 
12115 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
12116                                      const AArch64Subtarget *Subtarget) {
12117   // First try to optimize away the conversion when it's conditionally from
12118   // a constant. Vectors only.
12119   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
12120     return Res;
12121 
12122   EVT VT = N->getValueType(0);
12123   if (VT != MVT::f32 && VT != MVT::f64)
12124     return SDValue();
12125 
12126   // Only optimize when the source and destination types have the same width.
12127   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
12128     return SDValue();
12129 
12130   // If the result of an integer load is only used by an integer-to-float
12131   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
12132   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
12133   SDValue N0 = N->getOperand(0);
12134   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12135       // Do not change the width of a volatile load.
12136       !cast<LoadSDNode>(N0)->isVolatile()) {
12137     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
12138     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
12139                                LN0->getPointerInfo(), LN0->getAlignment(),
12140                                LN0->getMemOperand()->getFlags());
12141 
12142     // Make sure successors of the original load stay after it by updating them
12143     // to use the new Chain.
12144     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
12145 
12146     unsigned Opcode =
12147         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
12148     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
12149   }
12150 
12151   return SDValue();
12152 }
12153 
12154 /// Fold a floating-point multiply by power of two into floating-point to
12155 /// fixed-point conversion.
12156 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
12157                                      TargetLowering::DAGCombinerInfo &DCI,
12158                                      const AArch64Subtarget *Subtarget) {
12159   if (!Subtarget->hasNEON())
12160     return SDValue();
12161 
12162   if (!N->getValueType(0).isSimple())
12163     return SDValue();
12164 
12165   SDValue Op = N->getOperand(0);
12166   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12167       Op.getOpcode() != ISD::FMUL)
12168     return SDValue();
12169 
12170   SDValue ConstVec = Op->getOperand(1);
12171   if (!isa<BuildVectorSDNode>(ConstVec))
12172     return SDValue();
12173 
12174   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12175   uint32_t FloatBits = FloatTy.getSizeInBits();
12176   if (FloatBits != 32 && FloatBits != 64)
12177     return SDValue();
12178 
12179   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12180   uint32_t IntBits = IntTy.getSizeInBits();
12181   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
12182     return SDValue();
12183 
12184   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
12185   if (IntBits > FloatBits)
12186     return SDValue();
12187 
12188   BitVector UndefElements;
12189   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12190   int32_t Bits = IntBits == 64 ? 64 : 32;
12191   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
12192   if (C == -1 || C == 0 || C > Bits)
12193     return SDValue();
12194 
12195   MVT ResTy;
12196   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12197   switch (NumLanes) {
12198   default:
12199     return SDValue();
12200   case 2:
12201     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
12202     break;
12203   case 4:
12204     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
12205     break;
12206   }
12207 
12208   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
12209     return SDValue();
12210 
12211   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
12212          "Illegal vector type after legalization");
12213 
12214   SDLoc DL(N);
12215   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12216   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
12217                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
12218   SDValue FixConv =
12219       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
12220                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
12221                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
12222   // We can handle smaller integers by generating an extra trunc.
12223   if (IntBits < FloatBits)
12224     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
12225 
12226   return FixConv;
12227 }
12228 
12229 /// Fold a floating-point divide by power of two into fixed-point to
12230 /// floating-point conversion.
12231 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
12232                                   TargetLowering::DAGCombinerInfo &DCI,
12233                                   const AArch64Subtarget *Subtarget) {
12234   if (!Subtarget->hasNEON())
12235     return SDValue();
12236 
12237   SDValue Op = N->getOperand(0);
12238   unsigned Opc = Op->getOpcode();
12239   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12240       !Op.getOperand(0).getValueType().isSimple() ||
12241       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
12242     return SDValue();
12243 
12244   SDValue ConstVec = N->getOperand(1);
12245   if (!isa<BuildVectorSDNode>(ConstVec))
12246     return SDValue();
12247 
12248   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12249   int32_t IntBits = IntTy.getSizeInBits();
12250   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
12251     return SDValue();
12252 
12253   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12254   int32_t FloatBits = FloatTy.getSizeInBits();
12255   if (FloatBits != 32 && FloatBits != 64)
12256     return SDValue();
12257 
12258   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
12259   if (IntBits > FloatBits)
12260     return SDValue();
12261 
12262   BitVector UndefElements;
12263   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12264   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
12265   if (C == -1 || C == 0 || C > FloatBits)
12266     return SDValue();
12267 
12268   MVT ResTy;
12269   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12270   switch (NumLanes) {
12271   default:
12272     return SDValue();
12273   case 2:
12274     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
12275     break;
12276   case 4:
12277     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
12278     break;
12279   }
12280 
12281   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
12282     return SDValue();
12283 
12284   SDLoc DL(N);
12285   SDValue ConvInput = Op.getOperand(0);
12286   bool IsSigned = Opc == ISD::SINT_TO_FP;
12287   if (IntBits < FloatBits)
12288     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
12289                             ResTy, ConvInput);
12290 
12291   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
12292                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
12293   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
12294                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
12295                      DAG.getConstant(C, DL, MVT::i32));
12296 }
12297 
12298 /// An EXTR instruction is made up of two shifts, ORed together. This helper
12299 /// searches for and classifies those shifts.
12300 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
12301                          bool &FromHi) {
12302   if (N.getOpcode() == ISD::SHL)
12303     FromHi = false;
12304   else if (N.getOpcode() == ISD::SRL)
12305     FromHi = true;
12306   else
12307     return false;
12308 
12309   if (!isa<ConstantSDNode>(N.getOperand(1)))
12310     return false;
12311 
12312   ShiftAmount = N->getConstantOperandVal(1);
12313   Src = N->getOperand(0);
12314   return true;
12315 }
12316 
12317 /// EXTR instruction extracts a contiguous chunk of bits from two existing
12318 /// registers viewed as a high/low pair. This function looks for the pattern:
12319 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
12320 /// with an EXTR. Can't quite be done in TableGen because the two immediates
12321 /// aren't independent.
12322 static SDValue tryCombineToEXTR(SDNode *N,
12323                                 TargetLowering::DAGCombinerInfo &DCI) {
12324   SelectionDAG &DAG = DCI.DAG;
12325   SDLoc DL(N);
12326   EVT VT = N->getValueType(0);
12327 
12328   assert(N->getOpcode() == ISD::OR && "Unexpected root");
12329 
12330   if (VT != MVT::i32 && VT != MVT::i64)
12331     return SDValue();
12332 
12333   SDValue LHS;
12334   uint32_t ShiftLHS = 0;
12335   bool LHSFromHi = false;
12336   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
12337     return SDValue();
12338 
12339   SDValue RHS;
12340   uint32_t ShiftRHS = 0;
12341   bool RHSFromHi = false;
12342   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
12343     return SDValue();
12344 
12345   // If they're both trying to come from the high part of the register, they're
12346   // not really an EXTR.
12347   if (LHSFromHi == RHSFromHi)
12348     return SDValue();
12349 
12350   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
12351     return SDValue();
12352 
12353   if (LHSFromHi) {
12354     std::swap(LHS, RHS);
12355     std::swap(ShiftLHS, ShiftRHS);
12356   }
12357 
12358   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
12359                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
12360 }
12361 
12362 static SDValue tryCombineToBSL(SDNode *N,
12363                                 TargetLowering::DAGCombinerInfo &DCI) {
12364   EVT VT = N->getValueType(0);
12365   SelectionDAG &DAG = DCI.DAG;
12366   SDLoc DL(N);
12367 
12368   if (!VT.isVector())
12369     return SDValue();
12370 
12371   SDValue N0 = N->getOperand(0);
12372   if (N0.getOpcode() != ISD::AND)
12373     return SDValue();
12374 
12375   SDValue N1 = N->getOperand(1);
12376   if (N1.getOpcode() != ISD::AND)
12377     return SDValue();
12378 
12379   // We only have to look for constant vectors here since the general, variable
12380   // case can be handled in TableGen.
12381   unsigned Bits = VT.getScalarSizeInBits();
12382   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
12383   for (int i = 1; i >= 0; --i)
12384     for (int j = 1; j >= 0; --j) {
12385       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
12386       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
12387       if (!BVN0 || !BVN1)
12388         continue;
12389 
12390       bool FoundMatch = true;
12391       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
12392         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
12393         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
12394         if (!CN0 || !CN1 ||
12395             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
12396           FoundMatch = false;
12397           break;
12398         }
12399       }
12400 
12401       if (FoundMatch)
12402         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
12403                            N0->getOperand(1 - i), N1->getOperand(1 - j));
12404     }
12405 
12406   return SDValue();
12407 }
12408 
12409 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12410                                 const AArch64Subtarget *Subtarget) {
12411   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
12412   SelectionDAG &DAG = DCI.DAG;
12413   EVT VT = N->getValueType(0);
12414 
12415   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12416     return SDValue();
12417 
12418   if (SDValue Res = tryCombineToEXTR(N, DCI))
12419     return Res;
12420 
12421   if (SDValue Res = tryCombineToBSL(N, DCI))
12422     return Res;
12423 
12424   return SDValue();
12425 }
12426 
12427 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
12428   if (!MemVT.getVectorElementType().isSimple())
12429     return false;
12430 
12431   uint64_t MaskForTy = 0ull;
12432   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
12433   case MVT::i8:
12434     MaskForTy = 0xffull;
12435     break;
12436   case MVT::i16:
12437     MaskForTy = 0xffffull;
12438     break;
12439   case MVT::i32:
12440     MaskForTy = 0xffffffffull;
12441     break;
12442   default:
12443     return false;
12444     break;
12445   }
12446 
12447   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
12448     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
12449       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
12450 
12451   return false;
12452 }
12453 
12454 static SDValue performSVEAndCombine(SDNode *N,
12455                                     TargetLowering::DAGCombinerInfo &DCI) {
12456   if (DCI.isBeforeLegalizeOps())
12457     return SDValue();
12458 
12459   SelectionDAG &DAG = DCI.DAG;
12460   SDValue Src = N->getOperand(0);
12461   unsigned Opc = Src->getOpcode();
12462 
12463   // Zero/any extend of an unsigned unpack
12464   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
12465     SDValue UnpkOp = Src->getOperand(0);
12466     SDValue Dup = N->getOperand(1);
12467 
12468     if (Dup.getOpcode() != AArch64ISD::DUP)
12469       return SDValue();
12470 
12471     SDLoc DL(N);
12472     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
12473     uint64_t ExtVal = C->getZExtValue();
12474 
12475     // If the mask is fully covered by the unpack, we don't need to push
12476     // a new AND onto the operand
12477     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
12478     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
12479         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
12480         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
12481       return Src;
12482 
12483     // Truncate to prevent a DUP with an over wide constant
12484     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
12485 
12486     // Otherwise, make sure we propagate the AND to the operand
12487     // of the unpack
12488     Dup = DAG.getNode(AArch64ISD::DUP, DL,
12489                       UnpkOp->getValueType(0),
12490                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
12491 
12492     SDValue And = DAG.getNode(ISD::AND, DL,
12493                               UnpkOp->getValueType(0), UnpkOp, Dup);
12494 
12495     return DAG.getNode(Opc, DL, N->getValueType(0), And);
12496   }
12497 
12498   if (!EnableCombineMGatherIntrinsics)
12499     return SDValue();
12500 
12501   SDValue Mask = N->getOperand(1);
12502 
12503   if (!Src.hasOneUse())
12504     return SDValue();
12505 
12506   EVT MemVT;
12507 
12508   // SVE load instructions perform an implicit zero-extend, which makes them
12509   // perfect candidates for combining.
12510   switch (Opc) {
12511   case AArch64ISD::LD1_MERGE_ZERO:
12512   case AArch64ISD::LDNF1_MERGE_ZERO:
12513   case AArch64ISD::LDFF1_MERGE_ZERO:
12514     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
12515     break;
12516   case AArch64ISD::GLD1_MERGE_ZERO:
12517   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
12518   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
12519   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
12520   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
12521   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
12522   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
12523   case AArch64ISD::GLDFF1_MERGE_ZERO:
12524   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
12525   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
12526   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
12527   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
12528   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
12529   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
12530   case AArch64ISD::GLDNT1_MERGE_ZERO:
12531     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
12532     break;
12533   default:
12534     return SDValue();
12535   }
12536 
12537   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
12538     return Src;
12539 
12540   return SDValue();
12541 }
12542 
12543 static SDValue performANDCombine(SDNode *N,
12544                                  TargetLowering::DAGCombinerInfo &DCI) {
12545   SelectionDAG &DAG = DCI.DAG;
12546   SDValue LHS = N->getOperand(0);
12547   EVT VT = N->getValueType(0);
12548   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
12549     return SDValue();
12550 
12551   if (VT.isScalableVector())
12552     return performSVEAndCombine(N, DCI);
12553 
12554   // The combining code below works only for NEON vectors. In particular, it
12555   // does not work for SVE when dealing with vectors wider than 128 bits.
12556   if (!(VT.is64BitVector() || VT.is128BitVector()))
12557     return SDValue();
12558 
12559   BuildVectorSDNode *BVN =
12560       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
12561   if (!BVN)
12562     return SDValue();
12563 
12564   // AND does not accept an immediate, so check if we can use a BIC immediate
12565   // instruction instead. We do this here instead of using a (and x, (mvni imm))
12566   // pattern in isel, because some immediates may be lowered to the preferred
12567   // (and x, (movi imm)) form, even though an mvni representation also exists.
12568   APInt DefBits(VT.getSizeInBits(), 0);
12569   APInt UndefBits(VT.getSizeInBits(), 0);
12570   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
12571     SDValue NewOp;
12572 
12573     DefBits = ~DefBits;
12574     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
12575                                     DefBits, &LHS)) ||
12576         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
12577                                     DefBits, &LHS)))
12578       return NewOp;
12579 
12580     UndefBits = ~UndefBits;
12581     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
12582                                     UndefBits, &LHS)) ||
12583         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
12584                                     UndefBits, &LHS)))
12585       return NewOp;
12586   }
12587 
12588   return SDValue();
12589 }
12590 
12591 static SDValue performSRLCombine(SDNode *N,
12592                                  TargetLowering::DAGCombinerInfo &DCI) {
12593   SelectionDAG &DAG = DCI.DAG;
12594   EVT VT = N->getValueType(0);
12595   if (VT != MVT::i32 && VT != MVT::i64)
12596     return SDValue();
12597 
12598   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
12599   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
12600   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
12601   SDValue N0 = N->getOperand(0);
12602   if (N0.getOpcode() == ISD::BSWAP) {
12603     SDLoc DL(N);
12604     SDValue N1 = N->getOperand(1);
12605     SDValue N00 = N0.getOperand(0);
12606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12607       uint64_t ShiftAmt = C->getZExtValue();
12608       if (VT == MVT::i32 && ShiftAmt == 16 &&
12609           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
12610         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
12611       if (VT == MVT::i64 && ShiftAmt == 32 &&
12612           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
12613         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
12614     }
12615   }
12616   return SDValue();
12617 }
12618 
12619 // Attempt to form urhadd(OpA, OpB) from
12620 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
12621 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
12622 // The original form of the first expression is
12623 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
12624 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
12625 // Before this function is called the srl will have been lowered to
12626 // AArch64ISD::VLSHR.
12627 // This pass can also recognize signed variants of the patterns that use sign
12628 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
12629 // shadd(OpA, OpB) from them.
12630 static SDValue
12631 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12632                              SelectionDAG &DAG) {
12633   EVT VT = N->getValueType(0);
12634 
12635   // Since we are looking for a right shift by a constant value of 1 and we are
12636   // operating on types at least 16 bits in length (sign/zero extended OpA and
12637   // OpB, which are at least 8 bits), it follows that the truncate will always
12638   // discard the shifted-in bit and therefore the right shift will be logical
12639   // regardless of the signedness of OpA and OpB.
12640   SDValue Shift = N->getOperand(0);
12641   if (Shift.getOpcode() != AArch64ISD::VLSHR)
12642     return SDValue();
12643 
12644   // Is the right shift using an immediate value of 1?
12645   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
12646   if (ShiftAmount != 1)
12647     return SDValue();
12648 
12649   SDValue ExtendOpA, ExtendOpB;
12650   SDValue ShiftOp0 = Shift.getOperand(0);
12651   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
12652   if (ShiftOp0Opc == ISD::SUB) {
12653 
12654     SDValue Xor = ShiftOp0.getOperand(1);
12655     if (Xor.getOpcode() != ISD::XOR)
12656       return SDValue();
12657 
12658     // Is the XOR using a constant amount of all ones in the right hand side?
12659     uint64_t C;
12660     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
12661       return SDValue();
12662 
12663     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
12664     APInt CAsAPInt(ElemSizeInBits, C);
12665     if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
12666       return SDValue();
12667 
12668     ExtendOpA = Xor.getOperand(0);
12669     ExtendOpB = ShiftOp0.getOperand(0);
12670   } else if (ShiftOp0Opc == ISD::ADD) {
12671     ExtendOpA = ShiftOp0.getOperand(0);
12672     ExtendOpB = ShiftOp0.getOperand(1);
12673   } else
12674     return SDValue();
12675 
12676   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
12677   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
12678   if (!(ExtendOpAOpc == ExtendOpBOpc &&
12679         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
12680     return SDValue();
12681 
12682   // Is the result of the right shift being truncated to the same value type as
12683   // the original operands, OpA and OpB?
12684   SDValue OpA = ExtendOpA.getOperand(0);
12685   SDValue OpB = ExtendOpB.getOperand(0);
12686   EVT OpAVT = OpA.getValueType();
12687   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
12688   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
12689     return SDValue();
12690 
12691   SDLoc DL(N);
12692   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
12693   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
12694   unsigned HADDOpc = IsSignExtend
12695                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
12696                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
12697   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
12698 
12699   return ResultHADD;
12700 }
12701 
12702 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
12703   switch (Opcode) {
12704   case ISD::FADD:
12705     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
12706   case ISD::ADD:
12707     return VT == MVT::i64;
12708   default:
12709     return false;
12710   }
12711 }
12712 
12713 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
12714   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
12715   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
12716 
12717   EVT VT = N->getValueType(0);
12718   const bool FullFP16 =
12719       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
12720 
12721   // Rewrite for pairwise fadd pattern
12722   //   (f32 (extract_vector_elt
12723   //           (fadd (vXf32 Other)
12724   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
12725   // ->
12726   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
12727   //              (extract_vector_elt (vXf32 Other) 1))
12728   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
12729       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
12730     SDLoc DL(N0);
12731     SDValue N00 = N0->getOperand(0);
12732     SDValue N01 = N0->getOperand(1);
12733 
12734     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
12735     SDValue Other = N00;
12736 
12737     // And handle the commutative case.
12738     if (!Shuffle) {
12739       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
12740       Other = N01;
12741     }
12742 
12743     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
12744         Other == Shuffle->getOperand(0)) {
12745       return DAG.getNode(N0->getOpcode(), DL, VT,
12746                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
12747                                      DAG.getConstant(0, DL, MVT::i64)),
12748                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
12749                                      DAG.getConstant(1, DL, MVT::i64)));
12750     }
12751   }
12752 
12753   return SDValue();
12754 }
12755 
12756 static SDValue performConcatVectorsCombine(SDNode *N,
12757                                            TargetLowering::DAGCombinerInfo &DCI,
12758                                            SelectionDAG &DAG) {
12759   SDLoc dl(N);
12760   EVT VT = N->getValueType(0);
12761   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
12762   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
12763 
12764   // Optimize concat_vectors of truncated vectors, where the intermediate
12765   // type is illegal, to avoid said illegality,  e.g.,
12766   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
12767   //                          (v2i16 (truncate (v2i64)))))
12768   // ->
12769   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
12770   //                                    (v4i32 (bitcast (v2i64))),
12771   //                                    <0, 2, 4, 6>)))
12772   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
12773   // on both input and result type, so we might generate worse code.
12774   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
12775   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
12776       N1Opc == ISD::TRUNCATE) {
12777     SDValue N00 = N0->getOperand(0);
12778     SDValue N10 = N1->getOperand(0);
12779     EVT N00VT = N00.getValueType();
12780 
12781     if (N00VT == N10.getValueType() &&
12782         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
12783         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
12784       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
12785       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
12786       for (size_t i = 0; i < Mask.size(); ++i)
12787         Mask[i] = i * 2;
12788       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12789                          DAG.getVectorShuffle(
12790                              MidVT, dl,
12791                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
12792                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
12793     }
12794   }
12795 
12796   // Wait 'til after everything is legalized to try this. That way we have
12797   // legal vector types and such.
12798   if (DCI.isBeforeLegalizeOps())
12799     return SDValue();
12800 
12801   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
12802   // subvectors from the same original vectors. Combine these into a single
12803   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
12804   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
12805   //                                        extract_subvector (v16i8 OpB,
12806   //                                        <0>))),
12807   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
12808   //                                        extract_subvector (v16i8 OpB,
12809   //                                        <8>)))))
12810   // ->
12811   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
12812   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
12813       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
12814        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
12815     SDValue N00 = N0->getOperand(0);
12816     SDValue N01 = N0->getOperand(1);
12817     SDValue N10 = N1->getOperand(0);
12818     SDValue N11 = N1->getOperand(1);
12819 
12820     EVT N00VT = N00.getValueType();
12821     EVT N10VT = N10.getValueType();
12822 
12823     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12824         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12825         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12826         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
12827       SDValue N00Source = N00->getOperand(0);
12828       SDValue N01Source = N01->getOperand(0);
12829       SDValue N10Source = N10->getOperand(0);
12830       SDValue N11Source = N11->getOperand(0);
12831 
12832       if (N00Source == N10Source && N01Source == N11Source &&
12833           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
12834         assert(N0.getValueType() == N1.getValueType());
12835 
12836         uint64_t N00Index = N00.getConstantOperandVal(1);
12837         uint64_t N01Index = N01.getConstantOperandVal(1);
12838         uint64_t N10Index = N10.getConstantOperandVal(1);
12839         uint64_t N11Index = N11.getConstantOperandVal(1);
12840 
12841         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
12842             N10Index == N00VT.getVectorNumElements())
12843           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
12844       }
12845     }
12846   }
12847 
12848   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
12849   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
12850   // canonicalise to that.
12851   if (N0 == N1 && VT.getVectorNumElements() == 2) {
12852     assert(VT.getScalarSizeInBits() == 64);
12853     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
12854                        DAG.getConstant(0, dl, MVT::i64));
12855   }
12856 
12857   // Canonicalise concat_vectors so that the right-hand vector has as few
12858   // bit-casts as possible before its real operation. The primary matching
12859   // destination for these operations will be the narrowing "2" instructions,
12860   // which depend on the operation being performed on this right-hand vector.
12861   // For example,
12862   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
12863   // becomes
12864   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
12865 
12866   if (N1Opc != ISD::BITCAST)
12867     return SDValue();
12868   SDValue RHS = N1->getOperand(0);
12869   MVT RHSTy = RHS.getValueType().getSimpleVT();
12870   // If the RHS is not a vector, this is not the pattern we're looking for.
12871   if (!RHSTy.isVector())
12872     return SDValue();
12873 
12874   LLVM_DEBUG(
12875       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
12876 
12877   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
12878                                   RHSTy.getVectorNumElements() * 2);
12879   return DAG.getNode(ISD::BITCAST, dl, VT,
12880                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
12881                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
12882                                  RHS));
12883 }
12884 
12885 static SDValue tryCombineFixedPointConvert(SDNode *N,
12886                                            TargetLowering::DAGCombinerInfo &DCI,
12887                                            SelectionDAG &DAG) {
12888   // Wait until after everything is legalized to try this. That way we have
12889   // legal vector types and such.
12890   if (DCI.isBeforeLegalizeOps())
12891     return SDValue();
12892   // Transform a scalar conversion of a value from a lane extract into a
12893   // lane extract of a vector conversion. E.g., from foo1 to foo2:
12894   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
12895   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
12896   //
12897   // The second form interacts better with instruction selection and the
12898   // register allocator to avoid cross-class register copies that aren't
12899   // coalescable due to a lane reference.
12900 
12901   // Check the operand and see if it originates from a lane extract.
12902   SDValue Op1 = N->getOperand(1);
12903   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12904     // Yep, no additional predication needed. Perform the transform.
12905     SDValue IID = N->getOperand(0);
12906     SDValue Shift = N->getOperand(2);
12907     SDValue Vec = Op1.getOperand(0);
12908     SDValue Lane = Op1.getOperand(1);
12909     EVT ResTy = N->getValueType(0);
12910     EVT VecResTy;
12911     SDLoc DL(N);
12912 
12913     // The vector width should be 128 bits by the time we get here, even
12914     // if it started as 64 bits (the extract_vector handling will have
12915     // done so).
12916     assert(Vec.getValueSizeInBits() == 128 &&
12917            "unexpected vector size on extract_vector_elt!");
12918     if (Vec.getValueType() == MVT::v4i32)
12919       VecResTy = MVT::v4f32;
12920     else if (Vec.getValueType() == MVT::v2i64)
12921       VecResTy = MVT::v2f64;
12922     else
12923       llvm_unreachable("unexpected vector type!");
12924 
12925     SDValue Convert =
12926         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
12927     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
12928   }
12929   return SDValue();
12930 }
12931 
12932 // AArch64 high-vector "long" operations are formed by performing the non-high
12933 // version on an extract_subvector of each operand which gets the high half:
12934 //
12935 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
12936 //
12937 // However, there are cases which don't have an extract_high explicitly, but
12938 // have another operation that can be made compatible with one for free. For
12939 // example:
12940 //
12941 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
12942 //
12943 // This routine does the actual conversion of such DUPs, once outer routines
12944 // have determined that everything else is in order.
12945 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
12946 // similarly here.
12947 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
12948   switch (N.getOpcode()) {
12949   case AArch64ISD::DUP:
12950   case AArch64ISD::DUPLANE8:
12951   case AArch64ISD::DUPLANE16:
12952   case AArch64ISD::DUPLANE32:
12953   case AArch64ISD::DUPLANE64:
12954   case AArch64ISD::MOVI:
12955   case AArch64ISD::MOVIshift:
12956   case AArch64ISD::MOVIedit:
12957   case AArch64ISD::MOVImsl:
12958   case AArch64ISD::MVNIshift:
12959   case AArch64ISD::MVNImsl:
12960     break;
12961   default:
12962     // FMOV could be supported, but isn't very useful, as it would only occur
12963     // if you passed a bitcast' floating point immediate to an eligible long
12964     // integer op (addl, smull, ...).
12965     return SDValue();
12966   }
12967 
12968   MVT NarrowTy = N.getSimpleValueType();
12969   if (!NarrowTy.is64BitVector())
12970     return SDValue();
12971 
12972   MVT ElementTy = NarrowTy.getVectorElementType();
12973   unsigned NumElems = NarrowTy.getVectorNumElements();
12974   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
12975 
12976   SDLoc dl(N);
12977   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
12978                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
12979                      DAG.getConstant(NumElems, dl, MVT::i64));
12980 }
12981 
12982 static bool isEssentiallyExtractHighSubvector(SDValue N) {
12983   if (N.getOpcode() == ISD::BITCAST)
12984     N = N.getOperand(0);
12985   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12986     return false;
12987   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
12988          N.getOperand(0).getValueType().getVectorNumElements() / 2;
12989 }
12990 
12991 /// Helper structure to keep track of ISD::SET_CC operands.
12992 struct GenericSetCCInfo {
12993   const SDValue *Opnd0;
12994   const SDValue *Opnd1;
12995   ISD::CondCode CC;
12996 };
12997 
12998 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
12999 struct AArch64SetCCInfo {
13000   const SDValue *Cmp;
13001   AArch64CC::CondCode CC;
13002 };
13003 
13004 /// Helper structure to keep track of SetCC information.
13005 union SetCCInfo {
13006   GenericSetCCInfo Generic;
13007   AArch64SetCCInfo AArch64;
13008 };
13009 
13010 /// Helper structure to be able to read SetCC information.  If set to
13011 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
13012 /// GenericSetCCInfo.
13013 struct SetCCInfoAndKind {
13014   SetCCInfo Info;
13015   bool IsAArch64;
13016 };
13017 
13018 /// Check whether or not \p Op is a SET_CC operation, either a generic or
13019 /// an
13020 /// AArch64 lowered one.
13021 /// \p SetCCInfo is filled accordingly.
13022 /// \post SetCCInfo is meanginfull only when this function returns true.
13023 /// \return True when Op is a kind of SET_CC operation.
13024 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
13025   // If this is a setcc, this is straight forward.
13026   if (Op.getOpcode() == ISD::SETCC) {
13027     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
13028     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
13029     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13030     SetCCInfo.IsAArch64 = false;
13031     return true;
13032   }
13033   // Otherwise, check if this is a matching csel instruction.
13034   // In other words:
13035   // - csel 1, 0, cc
13036   // - csel 0, 1, !cc
13037   if (Op.getOpcode() != AArch64ISD::CSEL)
13038     return false;
13039   // Set the information about the operands.
13040   // TODO: we want the operands of the Cmp not the csel
13041   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
13042   SetCCInfo.IsAArch64 = true;
13043   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
13044       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13045 
13046   // Check that the operands matches the constraints:
13047   // (1) Both operands must be constants.
13048   // (2) One must be 1 and the other must be 0.
13049   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
13050   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13051 
13052   // Check (1).
13053   if (!TValue || !FValue)
13054     return false;
13055 
13056   // Check (2).
13057   if (!TValue->isOne()) {
13058     // Update the comparison when we are interested in !cc.
13059     std::swap(TValue, FValue);
13060     SetCCInfo.Info.AArch64.CC =
13061         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
13062   }
13063   return TValue->isOne() && FValue->isNullValue();
13064 }
13065 
13066 // Returns true if Op is setcc or zext of setcc.
13067 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
13068   if (isSetCC(Op, Info))
13069     return true;
13070   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
13071     isSetCC(Op->getOperand(0), Info));
13072 }
13073 
13074 // The folding we want to perform is:
13075 // (add x, [zext] (setcc cc ...) )
13076 //   -->
13077 // (csel x, (add x, 1), !cc ...)
13078 //
13079 // The latter will get matched to a CSINC instruction.
13080 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
13081   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
13082   SDValue LHS = Op->getOperand(0);
13083   SDValue RHS = Op->getOperand(1);
13084   SetCCInfoAndKind InfoAndKind;
13085 
13086   // If neither operand is a SET_CC, give up.
13087   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
13088     std::swap(LHS, RHS);
13089     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
13090       return SDValue();
13091   }
13092 
13093   // FIXME: This could be generatized to work for FP comparisons.
13094   EVT CmpVT = InfoAndKind.IsAArch64
13095                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
13096                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
13097   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
13098     return SDValue();
13099 
13100   SDValue CCVal;
13101   SDValue Cmp;
13102   SDLoc dl(Op);
13103   if (InfoAndKind.IsAArch64) {
13104     CCVal = DAG.getConstant(
13105         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
13106         MVT::i32);
13107     Cmp = *InfoAndKind.Info.AArch64.Cmp;
13108   } else
13109     Cmp = getAArch64Cmp(
13110         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
13111         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
13112         dl);
13113 
13114   EVT VT = Op->getValueType(0);
13115   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
13116   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
13117 }
13118 
13119 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
13120 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
13121   EVT VT = N->getValueType(0);
13122   // Only scalar integer and vector types.
13123   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
13124     return SDValue();
13125 
13126   SDValue LHS = N->getOperand(0);
13127   SDValue RHS = N->getOperand(1);
13128   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13129       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
13130     return SDValue();
13131 
13132   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13133   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
13134   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue())
13135     return SDValue();
13136 
13137   SDValue Op1 = LHS->getOperand(0);
13138   SDValue Op2 = RHS->getOperand(0);
13139   EVT OpVT1 = Op1.getValueType();
13140   EVT OpVT2 = Op2.getValueType();
13141   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
13142       Op2.getOpcode() != AArch64ISD::UADDV ||
13143       OpVT1.getVectorElementType() != VT)
13144     return SDValue();
13145 
13146   SDValue Val1 = Op1.getOperand(0);
13147   SDValue Val2 = Op2.getOperand(0);
13148   EVT ValVT = Val1->getValueType(0);
13149   SDLoc DL(N);
13150   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
13151   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13152                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
13153                      DAG.getConstant(0, DL, MVT::i64));
13154 }
13155 
13156 // The basic add/sub long vector instructions have variants with "2" on the end
13157 // which act on the high-half of their inputs. They are normally matched by
13158 // patterns like:
13159 //
13160 // (add (zeroext (extract_high LHS)),
13161 //      (zeroext (extract_high RHS)))
13162 // -> uaddl2 vD, vN, vM
13163 //
13164 // However, if one of the extracts is something like a duplicate, this
13165 // instruction can still be used profitably. This function puts the DAG into a
13166 // more appropriate form for those patterns to trigger.
13167 static SDValue performAddSubLongCombine(SDNode *N,
13168                                         TargetLowering::DAGCombinerInfo &DCI,
13169                                         SelectionDAG &DAG) {
13170   if (DCI.isBeforeLegalizeOps())
13171     return SDValue();
13172 
13173   MVT VT = N->getSimpleValueType(0);
13174   if (!VT.is128BitVector()) {
13175     if (N->getOpcode() == ISD::ADD)
13176       return performSetccAddFolding(N, DAG);
13177     return SDValue();
13178   }
13179 
13180   // Make sure both branches are extended in the same way.
13181   SDValue LHS = N->getOperand(0);
13182   SDValue RHS = N->getOperand(1);
13183   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
13184        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
13185       LHS.getOpcode() != RHS.getOpcode())
13186     return SDValue();
13187 
13188   unsigned ExtType = LHS.getOpcode();
13189 
13190   // It's not worth doing if at least one of the inputs isn't already an
13191   // extract, but we don't know which it'll be so we have to try both.
13192   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
13193     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
13194     if (!RHS.getNode())
13195       return SDValue();
13196 
13197     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
13198   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
13199     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
13200     if (!LHS.getNode())
13201       return SDValue();
13202 
13203     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
13204   }
13205 
13206   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
13207 }
13208 
13209 static SDValue performAddSubCombine(SDNode *N,
13210                                     TargetLowering::DAGCombinerInfo &DCI,
13211                                     SelectionDAG &DAG) {
13212   // Try to change sum of two reductions.
13213   if (SDValue Val = performUADDVCombine(N, DAG))
13214     return Val;
13215 
13216   return performAddSubLongCombine(N, DCI, DAG);
13217 }
13218 
13219 // Massage DAGs which we can use the high-half "long" operations on into
13220 // something isel will recognize better. E.g.
13221 //
13222 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
13223 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
13224 //                     (extract_high (v2i64 (dup128 scalar)))))
13225 //
13226 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
13227                                        TargetLowering::DAGCombinerInfo &DCI,
13228                                        SelectionDAG &DAG) {
13229   if (DCI.isBeforeLegalizeOps())
13230     return SDValue();
13231 
13232   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
13233   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
13234   assert(LHS.getValueType().is64BitVector() &&
13235          RHS.getValueType().is64BitVector() &&
13236          "unexpected shape for long operation");
13237 
13238   // Either node could be a DUP, but it's not worth doing both of them (you'd
13239   // just as well use the non-high version) so look for a corresponding extract
13240   // operation on the other "wing".
13241   if (isEssentiallyExtractHighSubvector(LHS)) {
13242     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
13243     if (!RHS.getNode())
13244       return SDValue();
13245   } else if (isEssentiallyExtractHighSubvector(RHS)) {
13246     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
13247     if (!LHS.getNode())
13248       return SDValue();
13249   }
13250 
13251   if (IID == Intrinsic::not_intrinsic)
13252     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
13253 
13254   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
13255                      N->getOperand(0), LHS, RHS);
13256 }
13257 
13258 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
13259   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
13260   unsigned ElemBits = ElemTy.getSizeInBits();
13261 
13262   int64_t ShiftAmount;
13263   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
13264     APInt SplatValue, SplatUndef;
13265     unsigned SplatBitSize;
13266     bool HasAnyUndefs;
13267     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13268                               HasAnyUndefs, ElemBits) ||
13269         SplatBitSize != ElemBits)
13270       return SDValue();
13271 
13272     ShiftAmount = SplatValue.getSExtValue();
13273   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
13274     ShiftAmount = CVN->getSExtValue();
13275   } else
13276     return SDValue();
13277 
13278   unsigned Opcode;
13279   bool IsRightShift;
13280   switch (IID) {
13281   default:
13282     llvm_unreachable("Unknown shift intrinsic");
13283   case Intrinsic::aarch64_neon_sqshl:
13284     Opcode = AArch64ISD::SQSHL_I;
13285     IsRightShift = false;
13286     break;
13287   case Intrinsic::aarch64_neon_uqshl:
13288     Opcode = AArch64ISD::UQSHL_I;
13289     IsRightShift = false;
13290     break;
13291   case Intrinsic::aarch64_neon_srshl:
13292     Opcode = AArch64ISD::SRSHR_I;
13293     IsRightShift = true;
13294     break;
13295   case Intrinsic::aarch64_neon_urshl:
13296     Opcode = AArch64ISD::URSHR_I;
13297     IsRightShift = true;
13298     break;
13299   case Intrinsic::aarch64_neon_sqshlu:
13300     Opcode = AArch64ISD::SQSHLU_I;
13301     IsRightShift = false;
13302     break;
13303   case Intrinsic::aarch64_neon_sshl:
13304   case Intrinsic::aarch64_neon_ushl:
13305     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
13306     // left shift for positive shift amounts. Below, we only replace the current
13307     // node with VSHL, if this condition is met.
13308     Opcode = AArch64ISD::VSHL;
13309     IsRightShift = false;
13310     break;
13311   }
13312 
13313   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
13314     SDLoc dl(N);
13315     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
13316                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
13317   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
13318     SDLoc dl(N);
13319     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
13320                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
13321   }
13322 
13323   return SDValue();
13324 }
13325 
13326 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
13327 // the intrinsics must be legal and take an i32, this means there's almost
13328 // certainly going to be a zext in the DAG which we can eliminate.
13329 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
13330   SDValue AndN = N->getOperand(2);
13331   if (AndN.getOpcode() != ISD::AND)
13332     return SDValue();
13333 
13334   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
13335   if (!CMask || CMask->getZExtValue() != Mask)
13336     return SDValue();
13337 
13338   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
13339                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
13340 }
13341 
13342 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
13343                                            SelectionDAG &DAG) {
13344   SDLoc dl(N);
13345   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
13346                      DAG.getNode(Opc, dl,
13347                                  N->getOperand(1).getSimpleValueType(),
13348                                  N->getOperand(1)),
13349                      DAG.getConstant(0, dl, MVT::i64));
13350 }
13351 
13352 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
13353   SDLoc DL(N);
13354   SDValue Op1 = N->getOperand(1);
13355   SDValue Op2 = N->getOperand(2);
13356   EVT ScalarTy = Op1.getValueType();
13357 
13358   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
13359     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
13360     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
13361   }
13362 
13363   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
13364                      Op1, Op2);
13365 }
13366 
13367 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
13368   SDLoc dl(N);
13369   SDValue Scalar = N->getOperand(3);
13370   EVT ScalarTy = Scalar.getValueType();
13371 
13372   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
13373     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
13374 
13375   SDValue Passthru = N->getOperand(1);
13376   SDValue Pred = N->getOperand(2);
13377   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
13378                      Pred, Scalar, Passthru);
13379 }
13380 
13381 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
13382   SDLoc dl(N);
13383   LLVMContext &Ctx = *DAG.getContext();
13384   EVT VT = N->getValueType(0);
13385 
13386   assert(VT.isScalableVector() && "Expected a scalable vector.");
13387 
13388   // Current lowering only supports the SVE-ACLE types.
13389   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
13390     return SDValue();
13391 
13392   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
13393   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
13394   EVT ByteVT =
13395       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
13396 
13397   // Convert everything to the domain of EXT (i.e bytes).
13398   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
13399   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
13400   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
13401                             DAG.getConstant(ElemSize, dl, MVT::i32));
13402 
13403   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
13404   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
13405 }
13406 
13407 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
13408                                         TargetLowering::DAGCombinerInfo &DCI,
13409                                         SelectionDAG &DAG) {
13410   if (DCI.isBeforeLegalize())
13411     return SDValue();
13412 
13413   SDValue Comparator = N->getOperand(3);
13414   if (Comparator.getOpcode() == AArch64ISD::DUP ||
13415       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
13416     unsigned IID = getIntrinsicID(N);
13417     EVT VT = N->getValueType(0);
13418     EVT CmpVT = N->getOperand(2).getValueType();
13419     SDValue Pred = N->getOperand(1);
13420     SDValue Imm;
13421     SDLoc DL(N);
13422 
13423     switch (IID) {
13424     default:
13425       llvm_unreachable("Called with wrong intrinsic!");
13426       break;
13427 
13428     // Signed comparisons
13429     case Intrinsic::aarch64_sve_cmpeq_wide:
13430     case Intrinsic::aarch64_sve_cmpne_wide:
13431     case Intrinsic::aarch64_sve_cmpge_wide:
13432     case Intrinsic::aarch64_sve_cmpgt_wide:
13433     case Intrinsic::aarch64_sve_cmplt_wide:
13434     case Intrinsic::aarch64_sve_cmple_wide: {
13435       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
13436         int64_t ImmVal = CN->getSExtValue();
13437         if (ImmVal >= -16 && ImmVal <= 15)
13438           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
13439         else
13440           return SDValue();
13441       }
13442       break;
13443     }
13444     // Unsigned comparisons
13445     case Intrinsic::aarch64_sve_cmphs_wide:
13446     case Intrinsic::aarch64_sve_cmphi_wide:
13447     case Intrinsic::aarch64_sve_cmplo_wide:
13448     case Intrinsic::aarch64_sve_cmpls_wide:  {
13449       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
13450         uint64_t ImmVal = CN->getZExtValue();
13451         if (ImmVal <= 127)
13452           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
13453         else
13454           return SDValue();
13455       }
13456       break;
13457     }
13458     }
13459 
13460     if (!Imm)
13461       return SDValue();
13462 
13463     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
13464     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
13465                        N->getOperand(2), Splat, DAG.getCondCode(CC));
13466   }
13467 
13468   return SDValue();
13469 }
13470 
13471 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
13472                         AArch64CC::CondCode Cond) {
13473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13474 
13475   SDLoc DL(Op);
13476   assert(Op.getValueType().isScalableVector() &&
13477          TLI.isTypeLegal(Op.getValueType()) &&
13478          "Expected legal scalable vector type!");
13479 
13480   // Ensure target specific opcodes are using legal type.
13481   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
13482   SDValue TVal = DAG.getConstant(1, DL, OutVT);
13483   SDValue FVal = DAG.getConstant(0, DL, OutVT);
13484 
13485   // Set condition code (CC) flags.
13486   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
13487 
13488   // Convert CC to integer based on requested condition.
13489   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
13490   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
13491   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
13492   return DAG.getZExtOrTrunc(Res, DL, VT);
13493 }
13494 
13495 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
13496                                       SelectionDAG &DAG) {
13497   SDLoc DL(N);
13498 
13499   SDValue Pred = N->getOperand(1);
13500   SDValue VecToReduce = N->getOperand(2);
13501 
13502   // NOTE: The integer reduction's result type is not always linked to the
13503   // operand's element type so we construct it from the intrinsic's result type.
13504   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
13505   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
13506 
13507   // SVE reductions set the whole vector register with the first element
13508   // containing the reduction result, which we'll now extract.
13509   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
13510   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
13511                      Zero);
13512 }
13513 
13514 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
13515                                      SelectionDAG &DAG) {
13516   SDLoc DL(N);
13517 
13518   SDValue Pred = N->getOperand(1);
13519   SDValue VecToReduce = N->getOperand(2);
13520 
13521   EVT ReduceVT = VecToReduce.getValueType();
13522   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
13523 
13524   // SVE reductions set the whole vector register with the first element
13525   // containing the reduction result, which we'll now extract.
13526   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
13527   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
13528                      Zero);
13529 }
13530 
13531 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
13532                                             SelectionDAG &DAG) {
13533   SDLoc DL(N);
13534 
13535   SDValue Pred = N->getOperand(1);
13536   SDValue InitVal = N->getOperand(2);
13537   SDValue VecToReduce = N->getOperand(3);
13538   EVT ReduceVT = VecToReduce.getValueType();
13539 
13540   // Ordered reductions use the first lane of the result vector as the
13541   // reduction's initial value.
13542   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
13543   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
13544                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
13545 
13546   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
13547 
13548   // SVE reductions set the whole vector register with the first element
13549   // containing the reduction result, which we'll now extract.
13550   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
13551                      Zero);
13552 }
13553 
13554 // If a merged operation has no inactive lanes we can relax it to a predicated
13555 // or unpredicated operation, which potentially allows better isel (perhaps
13556 // using immediate forms) or relaxing register reuse requirements.
13557 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
13558                                        SelectionDAG &DAG) {
13559   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
13560   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
13561   SDValue Pg = N->getOperand(1);
13562 
13563   // ISD way to specify an all active predicate.
13564   if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
13565       (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
13566     return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
13567                        N->getOperand(2), N->getOperand(3));
13568 
13569   // FUTURE: SplatVector(true)
13570   return SDValue();
13571 }
13572 
13573 static SDValue performIntrinsicCombine(SDNode *N,
13574                                        TargetLowering::DAGCombinerInfo &DCI,
13575                                        const AArch64Subtarget *Subtarget) {
13576   SelectionDAG &DAG = DCI.DAG;
13577   unsigned IID = getIntrinsicID(N);
13578   switch (IID) {
13579   default:
13580     break;
13581   case Intrinsic::aarch64_neon_vcvtfxs2fp:
13582   case Intrinsic::aarch64_neon_vcvtfxu2fp:
13583     return tryCombineFixedPointConvert(N, DCI, DAG);
13584   case Intrinsic::aarch64_neon_saddv:
13585     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
13586   case Intrinsic::aarch64_neon_uaddv:
13587     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
13588   case Intrinsic::aarch64_neon_sminv:
13589     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
13590   case Intrinsic::aarch64_neon_uminv:
13591     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
13592   case Intrinsic::aarch64_neon_smaxv:
13593     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
13594   case Intrinsic::aarch64_neon_umaxv:
13595     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
13596   case Intrinsic::aarch64_neon_fmax:
13597     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
13598                        N->getOperand(1), N->getOperand(2));
13599   case Intrinsic::aarch64_neon_fmin:
13600     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
13601                        N->getOperand(1), N->getOperand(2));
13602   case Intrinsic::aarch64_neon_fmaxnm:
13603     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
13604                        N->getOperand(1), N->getOperand(2));
13605   case Intrinsic::aarch64_neon_fminnm:
13606     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
13607                        N->getOperand(1), N->getOperand(2));
13608   case Intrinsic::aarch64_neon_smull:
13609   case Intrinsic::aarch64_neon_umull:
13610   case Intrinsic::aarch64_neon_pmull:
13611   case Intrinsic::aarch64_neon_sqdmull:
13612     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
13613   case Intrinsic::aarch64_neon_sqshl:
13614   case Intrinsic::aarch64_neon_uqshl:
13615   case Intrinsic::aarch64_neon_sqshlu:
13616   case Intrinsic::aarch64_neon_srshl:
13617   case Intrinsic::aarch64_neon_urshl:
13618   case Intrinsic::aarch64_neon_sshl:
13619   case Intrinsic::aarch64_neon_ushl:
13620     return tryCombineShiftImm(IID, N, DAG);
13621   case Intrinsic::aarch64_crc32b:
13622   case Intrinsic::aarch64_crc32cb:
13623     return tryCombineCRC32(0xff, N, DAG);
13624   case Intrinsic::aarch64_crc32h:
13625   case Intrinsic::aarch64_crc32ch:
13626     return tryCombineCRC32(0xffff, N, DAG);
13627   case Intrinsic::aarch64_sve_saddv:
13628     // There is no i64 version of SADDV because the sign is irrelevant.
13629     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
13630       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
13631     else
13632       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
13633   case Intrinsic::aarch64_sve_uaddv:
13634     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
13635   case Intrinsic::aarch64_sve_smaxv:
13636     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
13637   case Intrinsic::aarch64_sve_umaxv:
13638     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
13639   case Intrinsic::aarch64_sve_sminv:
13640     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
13641   case Intrinsic::aarch64_sve_uminv:
13642     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
13643   case Intrinsic::aarch64_sve_orv:
13644     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
13645   case Intrinsic::aarch64_sve_eorv:
13646     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
13647   case Intrinsic::aarch64_sve_andv:
13648     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
13649   case Intrinsic::aarch64_sve_index:
13650     return LowerSVEIntrinsicIndex(N, DAG);
13651   case Intrinsic::aarch64_sve_dup:
13652     return LowerSVEIntrinsicDUP(N, DAG);
13653   case Intrinsic::aarch64_sve_dup_x:
13654     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
13655                        N->getOperand(1));
13656   case Intrinsic::aarch64_sve_ext:
13657     return LowerSVEIntrinsicEXT(N, DAG);
13658   case Intrinsic::aarch64_sve_smin:
13659     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
13660   case Intrinsic::aarch64_sve_umin:
13661     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
13662   case Intrinsic::aarch64_sve_smax:
13663     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
13664   case Intrinsic::aarch64_sve_umax:
13665     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
13666   case Intrinsic::aarch64_sve_lsl:
13667     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
13668   case Intrinsic::aarch64_sve_lsr:
13669     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
13670   case Intrinsic::aarch64_sve_asr:
13671     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
13672   case Intrinsic::aarch64_sve_cmphs:
13673     if (!N->getOperand(2).getValueType().isFloatingPoint())
13674       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13675                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13676                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
13677     break;
13678   case Intrinsic::aarch64_sve_cmphi:
13679     if (!N->getOperand(2).getValueType().isFloatingPoint())
13680       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13681                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13682                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
13683     break;
13684   case Intrinsic::aarch64_sve_cmpge:
13685     if (!N->getOperand(2).getValueType().isFloatingPoint())
13686       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13687                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13688                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
13689     break;
13690   case Intrinsic::aarch64_sve_cmpgt:
13691     if (!N->getOperand(2).getValueType().isFloatingPoint())
13692       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13693                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13694                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
13695     break;
13696   case Intrinsic::aarch64_sve_cmpeq:
13697     if (!N->getOperand(2).getValueType().isFloatingPoint())
13698       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13699                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13700                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
13701     break;
13702   case Intrinsic::aarch64_sve_cmpne:
13703     if (!N->getOperand(2).getValueType().isFloatingPoint())
13704       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13705                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13706                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
13707     break;
13708   case Intrinsic::aarch64_sve_fadda:
13709     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
13710   case Intrinsic::aarch64_sve_faddv:
13711     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
13712   case Intrinsic::aarch64_sve_fmaxnmv:
13713     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
13714   case Intrinsic::aarch64_sve_fmaxv:
13715     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
13716   case Intrinsic::aarch64_sve_fminnmv:
13717     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
13718   case Intrinsic::aarch64_sve_fminv:
13719     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
13720   case Intrinsic::aarch64_sve_sel:
13721     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
13722                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
13723   case Intrinsic::aarch64_sve_cmpeq_wide:
13724     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
13725   case Intrinsic::aarch64_sve_cmpne_wide:
13726     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
13727   case Intrinsic::aarch64_sve_cmpge_wide:
13728     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
13729   case Intrinsic::aarch64_sve_cmpgt_wide:
13730     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
13731   case Intrinsic::aarch64_sve_cmplt_wide:
13732     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
13733   case Intrinsic::aarch64_sve_cmple_wide:
13734     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
13735   case Intrinsic::aarch64_sve_cmphs_wide:
13736     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
13737   case Intrinsic::aarch64_sve_cmphi_wide:
13738     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
13739   case Intrinsic::aarch64_sve_cmplo_wide:
13740     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
13741   case Intrinsic::aarch64_sve_cmpls_wide:
13742     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
13743   case Intrinsic::aarch64_sve_ptest_any:
13744     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13745                     AArch64CC::ANY_ACTIVE);
13746   case Intrinsic::aarch64_sve_ptest_first:
13747     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13748                     AArch64CC::FIRST_ACTIVE);
13749   case Intrinsic::aarch64_sve_ptest_last:
13750     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13751                     AArch64CC::LAST_ACTIVE);
13752   }
13753   return SDValue();
13754 }
13755 
13756 static SDValue performExtendCombine(SDNode *N,
13757                                     TargetLowering::DAGCombinerInfo &DCI,
13758                                     SelectionDAG &DAG) {
13759   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
13760   // we can convert that DUP into another extract_high (of a bigger DUP), which
13761   // helps the backend to decide that an sabdl2 would be useful, saving a real
13762   // extract_high operation.
13763   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
13764       (N->getOperand(0).getOpcode() == AArch64ISD::UABD ||
13765        N->getOperand(0).getOpcode() == AArch64ISD::SABD)) {
13766     SDNode *ABDNode = N->getOperand(0).getNode();
13767     SDValue NewABD =
13768         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
13769     if (!NewABD.getNode())
13770       return SDValue();
13771 
13772     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
13773   }
13774 
13775   // This is effectively a custom type legalization for AArch64.
13776   //
13777   // Type legalization will split an extend of a small, legal, type to a larger
13778   // illegal type by first splitting the destination type, often creating
13779   // illegal source types, which then get legalized in isel-confusing ways,
13780   // leading to really terrible codegen. E.g.,
13781   //   %result = v8i32 sext v8i8 %value
13782   // becomes
13783   //   %losrc = extract_subreg %value, ...
13784   //   %hisrc = extract_subreg %value, ...
13785   //   %lo = v4i32 sext v4i8 %losrc
13786   //   %hi = v4i32 sext v4i8 %hisrc
13787   // Things go rapidly downhill from there.
13788   //
13789   // For AArch64, the [sz]ext vector instructions can only go up one element
13790   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
13791   // take two instructions.
13792   //
13793   // This implies that the most efficient way to do the extend from v8i8
13794   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
13795   // the normal splitting to happen for the v8i16->v8i32.
13796 
13797   // This is pre-legalization to catch some cases where the default
13798   // type legalization will create ill-tempered code.
13799   if (!DCI.isBeforeLegalizeOps())
13800     return SDValue();
13801 
13802   // We're only interested in cleaning things up for non-legal vector types
13803   // here. If both the source and destination are legal, things will just
13804   // work naturally without any fiddling.
13805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13806   EVT ResVT = N->getValueType(0);
13807   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
13808     return SDValue();
13809   // If the vector type isn't a simple VT, it's beyond the scope of what
13810   // we're  worried about here. Let legalization do its thing and hope for
13811   // the best.
13812   SDValue Src = N->getOperand(0);
13813   EVT SrcVT = Src->getValueType(0);
13814   if (!ResVT.isSimple() || !SrcVT.isSimple())
13815     return SDValue();
13816 
13817   // If the source VT is a 64-bit fixed or scalable vector, we can play games
13818   // and get the better results we want.
13819   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
13820     return SDValue();
13821 
13822   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
13823   ElementCount SrcEC = SrcVT.getVectorElementCount();
13824   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
13825   SDLoc DL(N);
13826   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
13827 
13828   // Now split the rest of the operation into two halves, each with a 64
13829   // bit source.
13830   EVT LoVT, HiVT;
13831   SDValue Lo, Hi;
13832   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
13833 
13834   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
13835                                LoVT.getVectorElementCount());
13836   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13837                    DAG.getConstant(0, DL, MVT::i64));
13838   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13839                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
13840   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
13841   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
13842 
13843   // Now combine the parts back together so we still have a single result
13844   // like the combiner expects.
13845   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
13846 }
13847 
13848 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
13849                                SDValue SplatVal, unsigned NumVecElts) {
13850   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
13851   unsigned OrigAlignment = St.getAlignment();
13852   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
13853 
13854   // Create scalar stores. This is at least as good as the code sequence for a
13855   // split unaligned store which is a dup.s, ext.b, and two stores.
13856   // Most of the time the three stores should be replaced by store pair
13857   // instructions (stp).
13858   SDLoc DL(&St);
13859   SDValue BasePtr = St.getBasePtr();
13860   uint64_t BaseOffset = 0;
13861 
13862   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
13863   SDValue NewST1 =
13864       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
13865                    OrigAlignment, St.getMemOperand()->getFlags());
13866 
13867   // As this in ISel, we will not merge this add which may degrade results.
13868   if (BasePtr->getOpcode() == ISD::ADD &&
13869       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
13870     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
13871     BasePtr = BasePtr->getOperand(0);
13872   }
13873 
13874   unsigned Offset = EltOffset;
13875   while (--NumVecElts) {
13876     unsigned Alignment = MinAlign(OrigAlignment, Offset);
13877     SDValue OffsetPtr =
13878         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13879                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
13880     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
13881                           PtrInfo.getWithOffset(Offset), Alignment,
13882                           St.getMemOperand()->getFlags());
13883     Offset += EltOffset;
13884   }
13885   return NewST1;
13886 }
13887 
13888 // Returns an SVE type that ContentTy can be trivially sign or zero extended
13889 // into.
13890 static MVT getSVEContainerType(EVT ContentTy) {
13891   assert(ContentTy.isSimple() && "No SVE containers for extended types");
13892 
13893   switch (ContentTy.getSimpleVT().SimpleTy) {
13894   default:
13895     llvm_unreachable("No known SVE container for this MVT type");
13896   case MVT::nxv2i8:
13897   case MVT::nxv2i16:
13898   case MVT::nxv2i32:
13899   case MVT::nxv2i64:
13900   case MVT::nxv2f32:
13901   case MVT::nxv2f64:
13902     return MVT::nxv2i64;
13903   case MVT::nxv4i8:
13904   case MVT::nxv4i16:
13905   case MVT::nxv4i32:
13906   case MVT::nxv4f32:
13907     return MVT::nxv4i32;
13908   case MVT::nxv8i8:
13909   case MVT::nxv8i16:
13910   case MVT::nxv8f16:
13911   case MVT::nxv8bf16:
13912     return MVT::nxv8i16;
13913   case MVT::nxv16i8:
13914     return MVT::nxv16i8;
13915   }
13916 }
13917 
13918 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
13919   SDLoc DL(N);
13920   EVT VT = N->getValueType(0);
13921 
13922   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13923     return SDValue();
13924 
13925   EVT ContainerVT = VT;
13926   if (ContainerVT.isInteger())
13927     ContainerVT = getSVEContainerType(ContainerVT);
13928 
13929   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
13930   SDValue Ops[] = { N->getOperand(0), // Chain
13931                     N->getOperand(2), // Pg
13932                     N->getOperand(3), // Base
13933                     DAG.getValueType(VT) };
13934 
13935   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
13936   SDValue LoadChain = SDValue(Load.getNode(), 1);
13937 
13938   if (ContainerVT.isInteger() && (VT != ContainerVT))
13939     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
13940 
13941   return DAG.getMergeValues({ Load, LoadChain }, DL);
13942 }
13943 
13944 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
13945   SDLoc DL(N);
13946   EVT VT = N->getValueType(0);
13947   EVT PtrTy = N->getOperand(3).getValueType();
13948 
13949   if (VT == MVT::nxv8bf16 &&
13950       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13951     return SDValue();
13952 
13953   EVT LoadVT = VT;
13954   if (VT.isFloatingPoint())
13955     LoadVT = VT.changeTypeToInteger();
13956 
13957   auto *MINode = cast<MemIntrinsicSDNode>(N);
13958   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
13959   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
13960                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
13961                                 MINode->getOperand(2), PassThru,
13962                                 MINode->getMemoryVT(), MINode->getMemOperand(),
13963                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
13964 
13965    if (VT.isFloatingPoint()) {
13966      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
13967      return DAG.getMergeValues(Ops, DL);
13968    }
13969 
13970   return L;
13971 }
13972 
13973 template <unsigned Opcode>
13974 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
13975   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
13976                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
13977                 "Unsupported opcode.");
13978   SDLoc DL(N);
13979   EVT VT = N->getValueType(0);
13980   if (VT == MVT::nxv8bf16 &&
13981       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13982     return SDValue();
13983 
13984   EVT LoadVT = VT;
13985   if (VT.isFloatingPoint())
13986     LoadVT = VT.changeTypeToInteger();
13987 
13988   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
13989   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
13990   SDValue LoadChain = SDValue(Load.getNode(), 1);
13991 
13992   if (VT.isFloatingPoint())
13993     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
13994 
13995   return DAG.getMergeValues({Load, LoadChain}, DL);
13996 }
13997 
13998 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
13999   SDLoc DL(N);
14000   SDValue Data = N->getOperand(2);
14001   EVT DataVT = Data.getValueType();
14002   EVT HwSrcVt = getSVEContainerType(DataVT);
14003   SDValue InputVT = DAG.getValueType(DataVT);
14004 
14005   if (DataVT == MVT::nxv8bf16 &&
14006       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
14007     return SDValue();
14008 
14009   if (DataVT.isFloatingPoint())
14010     InputVT = DAG.getValueType(HwSrcVt);
14011 
14012   SDValue SrcNew;
14013   if (Data.getValueType().isFloatingPoint())
14014     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
14015   else
14016     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
14017 
14018   SDValue Ops[] = { N->getOperand(0), // Chain
14019                     SrcNew,
14020                     N->getOperand(4), // Base
14021                     N->getOperand(3), // Pg
14022                     InputVT
14023                   };
14024 
14025   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
14026 }
14027 
14028 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
14029   SDLoc DL(N);
14030 
14031   SDValue Data = N->getOperand(2);
14032   EVT DataVT = Data.getValueType();
14033   EVT PtrTy = N->getOperand(4).getValueType();
14034 
14035   if (DataVT == MVT::nxv8bf16 &&
14036       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
14037     return SDValue();
14038 
14039   if (DataVT.isFloatingPoint())
14040     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
14041 
14042   auto *MINode = cast<MemIntrinsicSDNode>(N);
14043   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
14044                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
14045                             MINode->getMemoryVT(), MINode->getMemOperand(),
14046                             ISD::UNINDEXED, false, false);
14047 }
14048 
14049 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
14050 /// load store optimizer pass will merge them to store pair stores.  This should
14051 /// be better than a movi to create the vector zero followed by a vector store
14052 /// if the zero constant is not re-used, since one instructions and one register
14053 /// live range will be removed.
14054 ///
14055 /// For example, the final generated code should be:
14056 ///
14057 ///   stp xzr, xzr, [x0]
14058 ///
14059 /// instead of:
14060 ///
14061 ///   movi v0.2d, #0
14062 ///   str q0, [x0]
14063 ///
14064 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
14065   SDValue StVal = St.getValue();
14066   EVT VT = StVal.getValueType();
14067 
14068   // Avoid scalarizing zero splat stores for scalable vectors.
14069   if (VT.isScalableVector())
14070     return SDValue();
14071 
14072   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
14073   // 2, 3 or 4 i32 elements.
14074   int NumVecElts = VT.getVectorNumElements();
14075   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
14076          VT.getVectorElementType().getSizeInBits() == 64) ||
14077         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
14078          VT.getVectorElementType().getSizeInBits() == 32)))
14079     return SDValue();
14080 
14081   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
14082     return SDValue();
14083 
14084   // If the zero constant has more than one use then the vector store could be
14085   // better since the constant mov will be amortized and stp q instructions
14086   // should be able to be formed.
14087   if (!StVal.hasOneUse())
14088     return SDValue();
14089 
14090   // If the store is truncating then it's going down to i16 or smaller, which
14091   // means it can be implemented in a single store anyway.
14092   if (St.isTruncatingStore())
14093     return SDValue();
14094 
14095   // If the immediate offset of the address operand is too large for the stp
14096   // instruction, then bail out.
14097   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
14098     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
14099     if (Offset < -512 || Offset > 504)
14100       return SDValue();
14101   }
14102 
14103   for (int I = 0; I < NumVecElts; ++I) {
14104     SDValue EltVal = StVal.getOperand(I);
14105     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
14106       return SDValue();
14107   }
14108 
14109   // Use a CopyFromReg WZR/XZR here to prevent
14110   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
14111   SDLoc DL(&St);
14112   unsigned ZeroReg;
14113   EVT ZeroVT;
14114   if (VT.getVectorElementType().getSizeInBits() == 32) {
14115     ZeroReg = AArch64::WZR;
14116     ZeroVT = MVT::i32;
14117   } else {
14118     ZeroReg = AArch64::XZR;
14119     ZeroVT = MVT::i64;
14120   }
14121   SDValue SplatVal =
14122       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
14123   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
14124 }
14125 
14126 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
14127 /// value. The load store optimizer pass will merge them to store pair stores.
14128 /// This has better performance than a splat of the scalar followed by a split
14129 /// vector store. Even if the stores are not merged it is four stores vs a dup,
14130 /// followed by an ext.b and two stores.
14131 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
14132   SDValue StVal = St.getValue();
14133   EVT VT = StVal.getValueType();
14134 
14135   // Don't replace floating point stores, they possibly won't be transformed to
14136   // stp because of the store pair suppress pass.
14137   if (VT.isFloatingPoint())
14138     return SDValue();
14139 
14140   // We can express a splat as store pair(s) for 2 or 4 elements.
14141   unsigned NumVecElts = VT.getVectorNumElements();
14142   if (NumVecElts != 4 && NumVecElts != 2)
14143     return SDValue();
14144 
14145   // If the store is truncating then it's going down to i16 or smaller, which
14146   // means it can be implemented in a single store anyway.
14147   if (St.isTruncatingStore())
14148     return SDValue();
14149 
14150   // Check that this is a splat.
14151   // Make sure that each of the relevant vector element locations are inserted
14152   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
14153   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
14154   SDValue SplatVal;
14155   for (unsigned I = 0; I < NumVecElts; ++I) {
14156     // Check for insert vector elements.
14157     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
14158       return SDValue();
14159 
14160     // Check that same value is inserted at each vector element.
14161     if (I == 0)
14162       SplatVal = StVal.getOperand(1);
14163     else if (StVal.getOperand(1) != SplatVal)
14164       return SDValue();
14165 
14166     // Check insert element index.
14167     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
14168     if (!CIndex)
14169       return SDValue();
14170     uint64_t IndexVal = CIndex->getZExtValue();
14171     if (IndexVal >= NumVecElts)
14172       return SDValue();
14173     IndexNotInserted.reset(IndexVal);
14174 
14175     StVal = StVal.getOperand(0);
14176   }
14177   // Check that all vector element locations were inserted to.
14178   if (IndexNotInserted.any())
14179       return SDValue();
14180 
14181   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
14182 }
14183 
14184 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14185                            SelectionDAG &DAG,
14186                            const AArch64Subtarget *Subtarget) {
14187 
14188   StoreSDNode *S = cast<StoreSDNode>(N);
14189   if (S->isVolatile() || S->isIndexed())
14190     return SDValue();
14191 
14192   SDValue StVal = S->getValue();
14193   EVT VT = StVal.getValueType();
14194 
14195   if (!VT.isFixedLengthVector())
14196     return SDValue();
14197 
14198   // If we get a splat of zeros, convert this vector store to a store of
14199   // scalars. They will be merged into store pairs of xzr thereby removing one
14200   // instruction and one register.
14201   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
14202     return ReplacedZeroSplat;
14203 
14204   // FIXME: The logic for deciding if an unaligned store should be split should
14205   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
14206   // a call to that function here.
14207 
14208   if (!Subtarget->isMisaligned128StoreSlow())
14209     return SDValue();
14210 
14211   // Don't split at -Oz.
14212   if (DAG.getMachineFunction().getFunction().hasMinSize())
14213     return SDValue();
14214 
14215   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
14216   // those up regresses performance on micro-benchmarks and olden/bh.
14217   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
14218     return SDValue();
14219 
14220   // Split unaligned 16B stores. They are terrible for performance.
14221   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
14222   // extensions can use this to mark that it does not want splitting to happen
14223   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
14224   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
14225   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
14226       S->getAlignment() <= 2)
14227     return SDValue();
14228 
14229   // If we get a splat of a scalar convert this vector store to a store of
14230   // scalars. They will be merged into store pairs thereby removing two
14231   // instructions.
14232   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
14233     return ReplacedSplat;
14234 
14235   SDLoc DL(S);
14236 
14237   // Split VT into two.
14238   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
14239   unsigned NumElts = HalfVT.getVectorNumElements();
14240   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
14241                                    DAG.getConstant(0, DL, MVT::i64));
14242   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
14243                                    DAG.getConstant(NumElts, DL, MVT::i64));
14244   SDValue BasePtr = S->getBasePtr();
14245   SDValue NewST1 =
14246       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
14247                    S->getAlignment(), S->getMemOperand()->getFlags());
14248   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
14249                                   DAG.getConstant(8, DL, MVT::i64));
14250   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
14251                       S->getPointerInfo(), S->getAlignment(),
14252                       S->getMemOperand()->getFlags());
14253 }
14254 
14255 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
14256   SDLoc DL(N);
14257   SDValue Op0 = N->getOperand(0);
14258   SDValue Op1 = N->getOperand(1);
14259   EVT ResVT = N->getValueType(0);
14260 
14261   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
14262   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
14263     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
14264       SDValue X = Op0.getOperand(0).getOperand(0);
14265       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
14266     }
14267   }
14268 
14269   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
14270   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
14271     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
14272       SDValue Z = Op1.getOperand(0).getOperand(1);
14273       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
14274     }
14275   }
14276 
14277   return SDValue();
14278 }
14279 
14280 /// Target-specific DAG combine function for post-increment LD1 (lane) and
14281 /// post-increment LD1R.
14282 static SDValue performPostLD1Combine(SDNode *N,
14283                                      TargetLowering::DAGCombinerInfo &DCI,
14284                                      bool IsLaneOp) {
14285   if (DCI.isBeforeLegalizeOps())
14286     return SDValue();
14287 
14288   SelectionDAG &DAG = DCI.DAG;
14289   EVT VT = N->getValueType(0);
14290 
14291   if (VT.isScalableVector())
14292     return SDValue();
14293 
14294   unsigned LoadIdx = IsLaneOp ? 1 : 0;
14295   SDNode *LD = N->getOperand(LoadIdx).getNode();
14296   // If it is not LOAD, can not do such combine.
14297   if (LD->getOpcode() != ISD::LOAD)
14298     return SDValue();
14299 
14300   // The vector lane must be a constant in the LD1LANE opcode.
14301   SDValue Lane;
14302   if (IsLaneOp) {
14303     Lane = N->getOperand(2);
14304     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
14305     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
14306       return SDValue();
14307   }
14308 
14309   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
14310   EVT MemVT = LoadSDN->getMemoryVT();
14311   // Check if memory operand is the same type as the vector element.
14312   if (MemVT != VT.getVectorElementType())
14313     return SDValue();
14314 
14315   // Check if there are other uses. If so, do not combine as it will introduce
14316   // an extra load.
14317   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
14318        ++UI) {
14319     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
14320       continue;
14321     if (*UI != N)
14322       return SDValue();
14323   }
14324 
14325   SDValue Addr = LD->getOperand(1);
14326   SDValue Vector = N->getOperand(0);
14327   // Search for a use of the address operand that is an increment.
14328   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
14329        Addr.getNode()->use_end(); UI != UE; ++UI) {
14330     SDNode *User = *UI;
14331     if (User->getOpcode() != ISD::ADD
14332         || UI.getUse().getResNo() != Addr.getResNo())
14333       continue;
14334 
14335     // If the increment is a constant, it must match the memory ref size.
14336     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14337     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
14338       uint32_t IncVal = CInc->getZExtValue();
14339       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
14340       if (IncVal != NumBytes)
14341         continue;
14342       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
14343     }
14344 
14345     // To avoid cycle construction make sure that neither the load nor the add
14346     // are predecessors to each other or the Vector.
14347     SmallPtrSet<const SDNode *, 32> Visited;
14348     SmallVector<const SDNode *, 16> Worklist;
14349     Visited.insert(Addr.getNode());
14350     Worklist.push_back(User);
14351     Worklist.push_back(LD);
14352     Worklist.push_back(Vector.getNode());
14353     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
14354         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14355       continue;
14356 
14357     SmallVector<SDValue, 8> Ops;
14358     Ops.push_back(LD->getOperand(0));  // Chain
14359     if (IsLaneOp) {
14360       Ops.push_back(Vector);           // The vector to be inserted
14361       Ops.push_back(Lane);             // The lane to be inserted in the vector
14362     }
14363     Ops.push_back(Addr);
14364     Ops.push_back(Inc);
14365 
14366     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
14367     SDVTList SDTys = DAG.getVTList(Tys);
14368     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
14369     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
14370                                            MemVT,
14371                                            LoadSDN->getMemOperand());
14372 
14373     // Update the uses.
14374     SDValue NewResults[] = {
14375         SDValue(LD, 0),            // The result of load
14376         SDValue(UpdN.getNode(), 2) // Chain
14377     };
14378     DCI.CombineTo(LD, NewResults);
14379     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
14380     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
14381 
14382     break;
14383   }
14384   return SDValue();
14385 }
14386 
14387 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
14388 /// address translation.
14389 static bool performTBISimplification(SDValue Addr,
14390                                      TargetLowering::DAGCombinerInfo &DCI,
14391                                      SelectionDAG &DAG) {
14392   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
14393   KnownBits Known;
14394   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14395                                         !DCI.isBeforeLegalizeOps());
14396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14397   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
14398     DCI.CommitTargetLoweringOpt(TLO);
14399     return true;
14400   }
14401   return false;
14402 }
14403 
14404 static SDValue performSTORECombine(SDNode *N,
14405                                    TargetLowering::DAGCombinerInfo &DCI,
14406                                    SelectionDAG &DAG,
14407                                    const AArch64Subtarget *Subtarget) {
14408   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
14409     return Split;
14410 
14411   if (Subtarget->supportsAddressTopByteIgnored() &&
14412       performTBISimplification(N->getOperand(2), DCI, DAG))
14413     return SDValue(N, 0);
14414 
14415   return SDValue();
14416 }
14417 
14418 /// Target-specific DAG combine function for NEON load/store intrinsics
14419 /// to merge base address updates.
14420 static SDValue performNEONPostLDSTCombine(SDNode *N,
14421                                           TargetLowering::DAGCombinerInfo &DCI,
14422                                           SelectionDAG &DAG) {
14423   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14424     return SDValue();
14425 
14426   unsigned AddrOpIdx = N->getNumOperands() - 1;
14427   SDValue Addr = N->getOperand(AddrOpIdx);
14428 
14429   // Search for a use of the address operand that is an increment.
14430   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14431        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
14432     SDNode *User = *UI;
14433     if (User->getOpcode() != ISD::ADD ||
14434         UI.getUse().getResNo() != Addr.getResNo())
14435       continue;
14436 
14437     // Check that the add is independent of the load/store.  Otherwise, folding
14438     // it would create a cycle.
14439     SmallPtrSet<const SDNode *, 32> Visited;
14440     SmallVector<const SDNode *, 16> Worklist;
14441     Visited.insert(Addr.getNode());
14442     Worklist.push_back(N);
14443     Worklist.push_back(User);
14444     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14445         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14446       continue;
14447 
14448     // Find the new opcode for the updating load/store.
14449     bool IsStore = false;
14450     bool IsLaneOp = false;
14451     bool IsDupOp = false;
14452     unsigned NewOpc = 0;
14453     unsigned NumVecs = 0;
14454     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14455     switch (IntNo) {
14456     default: llvm_unreachable("unexpected intrinsic for Neon base update");
14457     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
14458       NumVecs = 2; break;
14459     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
14460       NumVecs = 3; break;
14461     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
14462       NumVecs = 4; break;
14463     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
14464       NumVecs = 2; IsStore = true; break;
14465     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
14466       NumVecs = 3; IsStore = true; break;
14467     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
14468       NumVecs = 4; IsStore = true; break;
14469     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
14470       NumVecs = 2; break;
14471     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
14472       NumVecs = 3; break;
14473     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
14474       NumVecs = 4; break;
14475     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
14476       NumVecs = 2; IsStore = true; break;
14477     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
14478       NumVecs = 3; IsStore = true; break;
14479     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
14480       NumVecs = 4; IsStore = true; break;
14481     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
14482       NumVecs = 2; IsDupOp = true; break;
14483     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
14484       NumVecs = 3; IsDupOp = true; break;
14485     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
14486       NumVecs = 4; IsDupOp = true; break;
14487     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
14488       NumVecs = 2; IsLaneOp = true; break;
14489     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
14490       NumVecs = 3; IsLaneOp = true; break;
14491     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
14492       NumVecs = 4; IsLaneOp = true; break;
14493     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
14494       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
14495     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
14496       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
14497     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
14498       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
14499     }
14500 
14501     EVT VecTy;
14502     if (IsStore)
14503       VecTy = N->getOperand(2).getValueType();
14504     else
14505       VecTy = N->getValueType(0);
14506 
14507     // If the increment is a constant, it must match the memory ref size.
14508     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14509     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
14510       uint32_t IncVal = CInc->getZExtValue();
14511       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14512       if (IsLaneOp || IsDupOp)
14513         NumBytes /= VecTy.getVectorNumElements();
14514       if (IncVal != NumBytes)
14515         continue;
14516       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
14517     }
14518     SmallVector<SDValue, 8> Ops;
14519     Ops.push_back(N->getOperand(0)); // Incoming chain
14520     // Load lane and store have vector list as input.
14521     if (IsLaneOp || IsStore)
14522       for (unsigned i = 2; i < AddrOpIdx; ++i)
14523         Ops.push_back(N->getOperand(i));
14524     Ops.push_back(Addr); // Base register
14525     Ops.push_back(Inc);
14526 
14527     // Return Types.
14528     EVT Tys[6];
14529     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
14530     unsigned n;
14531     for (n = 0; n < NumResultVecs; ++n)
14532       Tys[n] = VecTy;
14533     Tys[n++] = MVT::i64;  // Type of write back register
14534     Tys[n] = MVT::Other;  // Type of the chain
14535     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
14536 
14537     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
14538     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
14539                                            MemInt->getMemoryVT(),
14540                                            MemInt->getMemOperand());
14541 
14542     // Update the uses.
14543     std::vector<SDValue> NewResults;
14544     for (unsigned i = 0; i < NumResultVecs; ++i) {
14545       NewResults.push_back(SDValue(UpdN.getNode(), i));
14546     }
14547     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
14548     DCI.CombineTo(N, NewResults);
14549     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14550 
14551     break;
14552   }
14553   return SDValue();
14554 }
14555 
14556 // Checks to see if the value is the prescribed width and returns information
14557 // about its extension mode.
14558 static
14559 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
14560   ExtType = ISD::NON_EXTLOAD;
14561   switch(V.getNode()->getOpcode()) {
14562   default:
14563     return false;
14564   case ISD::LOAD: {
14565     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
14566     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
14567        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
14568       ExtType = LoadNode->getExtensionType();
14569       return true;
14570     }
14571     return false;
14572   }
14573   case ISD::AssertSext: {
14574     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
14575     if ((TypeNode->getVT() == MVT::i8 && width == 8)
14576        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
14577       ExtType = ISD::SEXTLOAD;
14578       return true;
14579     }
14580     return false;
14581   }
14582   case ISD::AssertZext: {
14583     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
14584     if ((TypeNode->getVT() == MVT::i8 && width == 8)
14585        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
14586       ExtType = ISD::ZEXTLOAD;
14587       return true;
14588     }
14589     return false;
14590   }
14591   case ISD::Constant:
14592   case ISD::TargetConstant: {
14593     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
14594            1LL << (width - 1);
14595   }
14596   }
14597 
14598   return true;
14599 }
14600 
14601 // This function does a whole lot of voodoo to determine if the tests are
14602 // equivalent without and with a mask. Essentially what happens is that given a
14603 // DAG resembling:
14604 //
14605 //  +-------------+ +-------------+ +-------------+ +-------------+
14606 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
14607 //  +-------------+ +-------------+ +-------------+ +-------------+
14608 //           |           |           |               |
14609 //           V           V           |    +----------+
14610 //          +-------------+  +----+  |    |
14611 //          |     ADD     |  |0xff|  |    |
14612 //          +-------------+  +----+  |    |
14613 //                  |           |    |    |
14614 //                  V           V    |    |
14615 //                 +-------------+   |    |
14616 //                 |     AND     |   |    |
14617 //                 +-------------+   |    |
14618 //                      |            |    |
14619 //                      +-----+      |    |
14620 //                            |      |    |
14621 //                            V      V    V
14622 //                           +-------------+
14623 //                           |     CMP     |
14624 //                           +-------------+
14625 //
14626 // The AND node may be safely removed for some combinations of inputs. In
14627 // particular we need to take into account the extension type of the Input,
14628 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
14629 // width of the input (this can work for any width inputs, the above graph is
14630 // specific to 8 bits.
14631 //
14632 // The specific equations were worked out by generating output tables for each
14633 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
14634 // problem was simplified by working with 4 bit inputs, which means we only
14635 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
14636 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
14637 // patterns present in both extensions (0,7). For every distinct set of
14638 // AddConstant and CompConstants bit patterns we can consider the masked and
14639 // unmasked versions to be equivalent if the result of this function is true for
14640 // all 16 distinct bit patterns of for the current extension type of Input (w0).
14641 //
14642 //   sub      w8, w0, w1
14643 //   and      w10, w8, #0x0f
14644 //   cmp      w8, w2
14645 //   cset     w9, AArch64CC
14646 //   cmp      w10, w2
14647 //   cset     w11, AArch64CC
14648 //   cmp      w9, w11
14649 //   cset     w0, eq
14650 //   ret
14651 //
14652 // Since the above function shows when the outputs are equivalent it defines
14653 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
14654 // would be expensive to run during compiles. The equations below were written
14655 // in a test harness that confirmed they gave equivalent outputs to the above
14656 // for all inputs function, so they can be used determine if the removal is
14657 // legal instead.
14658 //
14659 // isEquivalentMaskless() is the code for testing if the AND can be removed
14660 // factored out of the DAG recognition as the DAG can take several forms.
14661 
14662 static bool isEquivalentMaskless(unsigned CC, unsigned width,
14663                                  ISD::LoadExtType ExtType, int AddConstant,
14664                                  int CompConstant) {
14665   // By being careful about our equations and only writing the in term
14666   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
14667   // make them generally applicable to all bit widths.
14668   int MaxUInt = (1 << width);
14669 
14670   // For the purposes of these comparisons sign extending the type is
14671   // equivalent to zero extending the add and displacing it by half the integer
14672   // width. Provided we are careful and make sure our equations are valid over
14673   // the whole range we can just adjust the input and avoid writing equations
14674   // for sign extended inputs.
14675   if (ExtType == ISD::SEXTLOAD)
14676     AddConstant -= (1 << (width-1));
14677 
14678   switch(CC) {
14679   case AArch64CC::LE:
14680   case AArch64CC::GT:
14681     if ((AddConstant == 0) ||
14682         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
14683         (AddConstant >= 0 && CompConstant < 0) ||
14684         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
14685       return true;
14686     break;
14687   case AArch64CC::LT:
14688   case AArch64CC::GE:
14689     if ((AddConstant == 0) ||
14690         (AddConstant >= 0 && CompConstant <= 0) ||
14691         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
14692       return true;
14693     break;
14694   case AArch64CC::HI:
14695   case AArch64CC::LS:
14696     if ((AddConstant >= 0 && CompConstant < 0) ||
14697        (AddConstant <= 0 && CompConstant >= -1 &&
14698         CompConstant < AddConstant + MaxUInt))
14699       return true;
14700    break;
14701   case AArch64CC::PL:
14702   case AArch64CC::MI:
14703     if ((AddConstant == 0) ||
14704         (AddConstant > 0 && CompConstant <= 0) ||
14705         (AddConstant < 0 && CompConstant <= AddConstant))
14706       return true;
14707     break;
14708   case AArch64CC::LO:
14709   case AArch64CC::HS:
14710     if ((AddConstant >= 0 && CompConstant <= 0) ||
14711         (AddConstant <= 0 && CompConstant >= 0 &&
14712          CompConstant <= AddConstant + MaxUInt))
14713       return true;
14714     break;
14715   case AArch64CC::EQ:
14716   case AArch64CC::NE:
14717     if ((AddConstant > 0 && CompConstant < 0) ||
14718         (AddConstant < 0 && CompConstant >= 0 &&
14719          CompConstant < AddConstant + MaxUInt) ||
14720         (AddConstant >= 0 && CompConstant >= 0 &&
14721          CompConstant >= AddConstant) ||
14722         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
14723       return true;
14724     break;
14725   case AArch64CC::VS:
14726   case AArch64CC::VC:
14727   case AArch64CC::AL:
14728   case AArch64CC::NV:
14729     return true;
14730   case AArch64CC::Invalid:
14731     break;
14732   }
14733 
14734   return false;
14735 }
14736 
14737 static
14738 SDValue performCONDCombine(SDNode *N,
14739                            TargetLowering::DAGCombinerInfo &DCI,
14740                            SelectionDAG &DAG, unsigned CCIndex,
14741                            unsigned CmpIndex) {
14742   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
14743   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
14744   unsigned CondOpcode = SubsNode->getOpcode();
14745 
14746   if (CondOpcode != AArch64ISD::SUBS)
14747     return SDValue();
14748 
14749   // There is a SUBS feeding this condition. Is it fed by a mask we can
14750   // use?
14751 
14752   SDNode *AndNode = SubsNode->getOperand(0).getNode();
14753   unsigned MaskBits = 0;
14754 
14755   if (AndNode->getOpcode() != ISD::AND)
14756     return SDValue();
14757 
14758   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
14759     uint32_t CNV = CN->getZExtValue();
14760     if (CNV == 255)
14761       MaskBits = 8;
14762     else if (CNV == 65535)
14763       MaskBits = 16;
14764   }
14765 
14766   if (!MaskBits)
14767     return SDValue();
14768 
14769   SDValue AddValue = AndNode->getOperand(0);
14770 
14771   if (AddValue.getOpcode() != ISD::ADD)
14772     return SDValue();
14773 
14774   // The basic dag structure is correct, grab the inputs and validate them.
14775 
14776   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
14777   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
14778   SDValue SubsInputValue = SubsNode->getOperand(1);
14779 
14780   // The mask is present and the provenance of all the values is a smaller type,
14781   // lets see if the mask is superfluous.
14782 
14783   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
14784       !isa<ConstantSDNode>(SubsInputValue.getNode()))
14785     return SDValue();
14786 
14787   ISD::LoadExtType ExtType;
14788 
14789   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
14790       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
14791       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
14792     return SDValue();
14793 
14794   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
14795                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
14796                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
14797     return SDValue();
14798 
14799   // The AND is not necessary, remove it.
14800 
14801   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
14802                                SubsNode->getValueType(1));
14803   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
14804 
14805   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
14806   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
14807 
14808   return SDValue(N, 0);
14809 }
14810 
14811 // Optimize compare with zero and branch.
14812 static SDValue performBRCONDCombine(SDNode *N,
14813                                     TargetLowering::DAGCombinerInfo &DCI,
14814                                     SelectionDAG &DAG) {
14815   MachineFunction &MF = DAG.getMachineFunction();
14816   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
14817   // will not be produced, as they are conditional branch instructions that do
14818   // not set flags.
14819   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
14820     return SDValue();
14821 
14822   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
14823     N = NV.getNode();
14824   SDValue Chain = N->getOperand(0);
14825   SDValue Dest = N->getOperand(1);
14826   SDValue CCVal = N->getOperand(2);
14827   SDValue Cmp = N->getOperand(3);
14828 
14829   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
14830   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
14831   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
14832     return SDValue();
14833 
14834   unsigned CmpOpc = Cmp.getOpcode();
14835   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
14836     return SDValue();
14837 
14838   // Only attempt folding if there is only one use of the flag and no use of the
14839   // value.
14840   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
14841     return SDValue();
14842 
14843   SDValue LHS = Cmp.getOperand(0);
14844   SDValue RHS = Cmp.getOperand(1);
14845 
14846   assert(LHS.getValueType() == RHS.getValueType() &&
14847          "Expected the value type to be the same for both operands!");
14848   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
14849     return SDValue();
14850 
14851   if (isNullConstant(LHS))
14852     std::swap(LHS, RHS);
14853 
14854   if (!isNullConstant(RHS))
14855     return SDValue();
14856 
14857   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
14858       LHS.getOpcode() == ISD::SRL)
14859     return SDValue();
14860 
14861   // Fold the compare into the branch instruction.
14862   SDValue BR;
14863   if (CC == AArch64CC::EQ)
14864     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14865   else
14866     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14867 
14868   // Do not add new nodes to DAG combiner worklist.
14869   DCI.CombineTo(N, BR, false);
14870 
14871   return SDValue();
14872 }
14873 
14874 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
14875 // as well as whether the test should be inverted.  This code is required to
14876 // catch these cases (as opposed to standard dag combines) because
14877 // AArch64ISD::TBZ is matched during legalization.
14878 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
14879                                  SelectionDAG &DAG) {
14880 
14881   if (!Op->hasOneUse())
14882     return Op;
14883 
14884   // We don't handle undef/constant-fold cases below, as they should have
14885   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
14886   // etc.)
14887 
14888   // (tbz (trunc x), b) -> (tbz x, b)
14889   // This case is just here to enable more of the below cases to be caught.
14890   if (Op->getOpcode() == ISD::TRUNCATE &&
14891       Bit < Op->getValueType(0).getSizeInBits()) {
14892     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14893   }
14894 
14895   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
14896   if (Op->getOpcode() == ISD::ANY_EXTEND &&
14897       Bit < Op->getOperand(0).getValueSizeInBits()) {
14898     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14899   }
14900 
14901   if (Op->getNumOperands() != 2)
14902     return Op;
14903 
14904   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14905   if (!C)
14906     return Op;
14907 
14908   switch (Op->getOpcode()) {
14909   default:
14910     return Op;
14911 
14912   // (tbz (and x, m), b) -> (tbz x, b)
14913   case ISD::AND:
14914     if ((C->getZExtValue() >> Bit) & 1)
14915       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14916     return Op;
14917 
14918   // (tbz (shl x, c), b) -> (tbz x, b-c)
14919   case ISD::SHL:
14920     if (C->getZExtValue() <= Bit &&
14921         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14922       Bit = Bit - C->getZExtValue();
14923       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14924     }
14925     return Op;
14926 
14927   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
14928   case ISD::SRA:
14929     Bit = Bit + C->getZExtValue();
14930     if (Bit >= Op->getValueType(0).getSizeInBits())
14931       Bit = Op->getValueType(0).getSizeInBits() - 1;
14932     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14933 
14934   // (tbz (srl x, c), b) -> (tbz x, b+c)
14935   case ISD::SRL:
14936     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14937       Bit = Bit + C->getZExtValue();
14938       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14939     }
14940     return Op;
14941 
14942   // (tbz (xor x, -1), b) -> (tbnz x, b)
14943   case ISD::XOR:
14944     if ((C->getZExtValue() >> Bit) & 1)
14945       Invert = !Invert;
14946     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14947   }
14948 }
14949 
14950 // Optimize test single bit zero/non-zero and branch.
14951 static SDValue performTBZCombine(SDNode *N,
14952                                  TargetLowering::DAGCombinerInfo &DCI,
14953                                  SelectionDAG &DAG) {
14954   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14955   bool Invert = false;
14956   SDValue TestSrc = N->getOperand(1);
14957   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
14958 
14959   if (TestSrc == NewTestSrc)
14960     return SDValue();
14961 
14962   unsigned NewOpc = N->getOpcode();
14963   if (Invert) {
14964     if (NewOpc == AArch64ISD::TBZ)
14965       NewOpc = AArch64ISD::TBNZ;
14966     else {
14967       assert(NewOpc == AArch64ISD::TBNZ);
14968       NewOpc = AArch64ISD::TBZ;
14969     }
14970   }
14971 
14972   SDLoc DL(N);
14973   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
14974                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
14975 }
14976 
14977 // vselect (v1i1 setcc) ->
14978 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
14979 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
14980 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
14981 // such VSELECT.
14982 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
14983   SDValue N0 = N->getOperand(0);
14984   EVT CCVT = N0.getValueType();
14985 
14986   // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
14987   // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
14988   // supported types.
14989   SDValue SetCC = N->getOperand(0);
14990   if (SetCC.getOpcode() == ISD::SETCC &&
14991       SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
14992     SDValue CmpLHS = SetCC.getOperand(0);
14993     EVT VT = CmpLHS.getValueType();
14994     SDNode *CmpRHS = SetCC.getOperand(1).getNode();
14995     SDNode *SplatLHS = N->getOperand(1).getNode();
14996     SDNode *SplatRHS = N->getOperand(2).getNode();
14997     APInt SplatLHSVal;
14998     if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
14999         VT.isSimple() &&
15000         is_contained(
15001             makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
15002                           MVT::v2i32, MVT::v4i32, MVT::v2i64}),
15003             VT.getSimpleVT().SimpleTy) &&
15004         ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
15005         SplatLHSVal.isOneValue() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
15006         ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
15007       unsigned NumElts = VT.getVectorNumElements();
15008       SmallVector<SDValue, 8> Ops(
15009           NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
15010                                    VT.getScalarType()));
15011       SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
15012 
15013       auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
15014       auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
15015       return Or;
15016     }
15017   }
15018 
15019   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
15020       CCVT.getVectorElementType() != MVT::i1)
15021     return SDValue();
15022 
15023   EVT ResVT = N->getValueType(0);
15024   EVT CmpVT = N0.getOperand(0).getValueType();
15025   // Only combine when the result type is of the same size as the compared
15026   // operands.
15027   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
15028     return SDValue();
15029 
15030   SDValue IfTrue = N->getOperand(1);
15031   SDValue IfFalse = N->getOperand(2);
15032   SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
15033                        N0.getOperand(0), N0.getOperand(1),
15034                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
15035   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
15036                      IfTrue, IfFalse);
15037 }
15038 
15039 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
15040 /// the compare-mask instructions rather than going via NZCV, even if LHS and
15041 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
15042 /// with a vector one followed by a DUP shuffle on the result.
15043 static SDValue performSelectCombine(SDNode *N,
15044                                     TargetLowering::DAGCombinerInfo &DCI) {
15045   SelectionDAG &DAG = DCI.DAG;
15046   SDValue N0 = N->getOperand(0);
15047   EVT ResVT = N->getValueType(0);
15048 
15049   if (N0.getOpcode() != ISD::SETCC)
15050     return SDValue();
15051 
15052   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
15053   // scalar SetCCResultType. We also don't expect vectors, because we assume
15054   // that selects fed by vector SETCCs are canonicalized to VSELECT.
15055   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
15056          "Scalar-SETCC feeding SELECT has unexpected result type!");
15057 
15058   // If NumMaskElts == 0, the comparison is larger than select result. The
15059   // largest real NEON comparison is 64-bits per lane, which means the result is
15060   // at most 32-bits and an illegal vector. Just bail out for now.
15061   EVT SrcVT = N0.getOperand(0).getValueType();
15062 
15063   // Don't try to do this optimization when the setcc itself has i1 operands.
15064   // There are no legal vectors of i1, so this would be pointless.
15065   if (SrcVT == MVT::i1)
15066     return SDValue();
15067 
15068   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
15069   if (!ResVT.isVector() || NumMaskElts == 0)
15070     return SDValue();
15071 
15072   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
15073   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
15074 
15075   // Also bail out if the vector CCVT isn't the same size as ResVT.
15076   // This can happen if the SETCC operand size doesn't divide the ResVT size
15077   // (e.g., f64 vs v3f32).
15078   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
15079     return SDValue();
15080 
15081   // Make sure we didn't create illegal types, if we're not supposed to.
15082   assert(DCI.isBeforeLegalize() ||
15083          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
15084 
15085   // First perform a vector comparison, where lane 0 is the one we're interested
15086   // in.
15087   SDLoc DL(N0);
15088   SDValue LHS =
15089       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
15090   SDValue RHS =
15091       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
15092   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
15093 
15094   // Now duplicate the comparison mask we want across all other lanes.
15095   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
15096   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
15097   Mask = DAG.getNode(ISD::BITCAST, DL,
15098                      ResVT.changeVectorElementTypeToInteger(), Mask);
15099 
15100   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
15101 }
15102 
15103 /// Get rid of unnecessary NVCASTs (that don't change the type).
15104 static SDValue performNVCASTCombine(SDNode *N) {
15105   if (N->getValueType(0) == N->getOperand(0).getValueType())
15106     return N->getOperand(0);
15107 
15108   return SDValue();
15109 }
15110 
15111 // If all users of the globaladdr are of the form (globaladdr + constant), find
15112 // the smallest constant, fold it into the globaladdr's offset and rewrite the
15113 // globaladdr as (globaladdr + constant) - constant.
15114 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
15115                                            const AArch64Subtarget *Subtarget,
15116                                            const TargetMachine &TM) {
15117   auto *GN = cast<GlobalAddressSDNode>(N);
15118   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
15119       AArch64II::MO_NO_FLAG)
15120     return SDValue();
15121 
15122   uint64_t MinOffset = -1ull;
15123   for (SDNode *N : GN->uses()) {
15124     if (N->getOpcode() != ISD::ADD)
15125       return SDValue();
15126     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
15127     if (!C)
15128       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15129     if (!C)
15130       return SDValue();
15131     MinOffset = std::min(MinOffset, C->getZExtValue());
15132   }
15133   uint64_t Offset = MinOffset + GN->getOffset();
15134 
15135   // Require that the new offset is larger than the existing one. Otherwise, we
15136   // can end up oscillating between two possible DAGs, for example,
15137   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
15138   if (Offset <= uint64_t(GN->getOffset()))
15139     return SDValue();
15140 
15141   // Check whether folding this offset is legal. It must not go out of bounds of
15142   // the referenced object to avoid violating the code model, and must be
15143   // smaller than 2^21 because this is the largest offset expressible in all
15144   // object formats.
15145   //
15146   // This check also prevents us from folding negative offsets, which will end
15147   // up being treated in the same way as large positive ones. They could also
15148   // cause code model violations, and aren't really common enough to matter.
15149   if (Offset >= (1 << 21))
15150     return SDValue();
15151 
15152   const GlobalValue *GV = GN->getGlobal();
15153   Type *T = GV->getValueType();
15154   if (!T->isSized() ||
15155       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
15156     return SDValue();
15157 
15158   SDLoc DL(GN);
15159   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
15160   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
15161                      DAG.getConstant(MinOffset, DL, MVT::i64));
15162 }
15163 
15164 // Turns the vector of indices into a vector of byte offstes by scaling Offset
15165 // by (BitWidth / 8).
15166 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
15167                                           SDLoc DL, unsigned BitWidth) {
15168   assert(Offset.getValueType().isScalableVector() &&
15169          "This method is only for scalable vectors of offsets");
15170 
15171   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
15172   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
15173 
15174   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
15175 }
15176 
15177 /// Check if the value of \p OffsetInBytes can be used as an immediate for
15178 /// the gather load/prefetch and scatter store instructions with vector base and
15179 /// immediate offset addressing mode:
15180 ///
15181 ///      [<Zn>.[S|D]{, #<imm>}]
15182 ///
15183 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
15184 
15185 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
15186                                                   unsigned ScalarSizeInBytes) {
15187   // The immediate is not a multiple of the scalar size.
15188   if (OffsetInBytes % ScalarSizeInBytes)
15189     return false;
15190 
15191   // The immediate is out of range.
15192   if (OffsetInBytes / ScalarSizeInBytes > 31)
15193     return false;
15194 
15195   return true;
15196 }
15197 
15198 /// Check if the value of \p Offset represents a valid immediate for the SVE
15199 /// gather load/prefetch and scatter store instructiona with vector base and
15200 /// immediate offset addressing mode:
15201 ///
15202 ///      [<Zn>.[S|D]{, #<imm>}]
15203 ///
15204 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
15205 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
15206                                            unsigned ScalarSizeInBytes) {
15207   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
15208   return OffsetConst && isValidImmForSVEVecImmAddrMode(
15209                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
15210 }
15211 
15212 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
15213                                           unsigned Opcode,
15214                                           bool OnlyPackedOffsets = true) {
15215   const SDValue Src = N->getOperand(2);
15216   const EVT SrcVT = Src->getValueType(0);
15217   assert(SrcVT.isScalableVector() &&
15218          "Scatter stores are only possible for SVE vectors");
15219 
15220   SDLoc DL(N);
15221   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
15222 
15223   // Make sure that source data will fit into an SVE register
15224   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
15225     return SDValue();
15226 
15227   // For FPs, ACLE only supports _packed_ single and double precision types.
15228   if (SrcElVT.isFloatingPoint())
15229     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
15230       return SDValue();
15231 
15232   // Depending on the addressing mode, this is either a pointer or a vector of
15233   // pointers (that fits into one register)
15234   SDValue Base = N->getOperand(4);
15235   // Depending on the addressing mode, this is either a single offset or a
15236   // vector of offsets  (that fits into one register)
15237   SDValue Offset = N->getOperand(5);
15238 
15239   // For "scalar + vector of indices", just scale the indices. This only
15240   // applies to non-temporal scatters because there's no instruction that takes
15241   // indicies.
15242   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
15243     Offset =
15244         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
15245     Opcode = AArch64ISD::SSTNT1_PRED;
15246   }
15247 
15248   // In the case of non-temporal gather loads there's only one SVE instruction
15249   // per data-size: "scalar + vector", i.e.
15250   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
15251   // Since we do have intrinsics that allow the arguments to be in a different
15252   // order, we may need to swap them to match the spec.
15253   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
15254     std::swap(Base, Offset);
15255 
15256   // SST1_IMM requires that the offset is an immediate that is:
15257   //    * a multiple of #SizeInBytes,
15258   //    * in the range [0, 31 x #SizeInBytes],
15259   // where #SizeInBytes is the size in bytes of the stored items. For
15260   // immediates outside that range and non-immediate scalar offsets use SST1 or
15261   // SST1_UXTW instead.
15262   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
15263     if (!isValidImmForSVEVecImmAddrMode(Offset,
15264                                         SrcVT.getScalarSizeInBits() / 8)) {
15265       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
15266         Opcode = AArch64ISD::SST1_UXTW_PRED;
15267       else
15268         Opcode = AArch64ISD::SST1_PRED;
15269 
15270       std::swap(Base, Offset);
15271     }
15272   }
15273 
15274   auto &TLI = DAG.getTargetLoweringInfo();
15275   if (!TLI.isTypeLegal(Base.getValueType()))
15276     return SDValue();
15277 
15278   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
15279   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
15280   // nxv2i64. Legalize accordingly.
15281   if (!OnlyPackedOffsets &&
15282       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
15283     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
15284 
15285   if (!TLI.isTypeLegal(Offset.getValueType()))
15286     return SDValue();
15287 
15288   // Source value type that is representable in hardware
15289   EVT HwSrcVt = getSVEContainerType(SrcVT);
15290 
15291   // Keep the original type of the input data to store - this is needed to be
15292   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
15293   // FP values we want the integer equivalent, so just use HwSrcVt.
15294   SDValue InputVT = DAG.getValueType(SrcVT);
15295   if (SrcVT.isFloatingPoint())
15296     InputVT = DAG.getValueType(HwSrcVt);
15297 
15298   SDVTList VTs = DAG.getVTList(MVT::Other);
15299   SDValue SrcNew;
15300 
15301   if (Src.getValueType().isFloatingPoint())
15302     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
15303   else
15304     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
15305 
15306   SDValue Ops[] = {N->getOperand(0), // Chain
15307                    SrcNew,
15308                    N->getOperand(3), // Pg
15309                    Base,
15310                    Offset,
15311                    InputVT};
15312 
15313   return DAG.getNode(Opcode, DL, VTs, Ops);
15314 }
15315 
15316 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
15317                                         unsigned Opcode,
15318                                         bool OnlyPackedOffsets = true) {
15319   const EVT RetVT = N->getValueType(0);
15320   assert(RetVT.isScalableVector() &&
15321          "Gather loads are only possible for SVE vectors");
15322 
15323   SDLoc DL(N);
15324 
15325   // Make sure that the loaded data will fit into an SVE register
15326   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
15327     return SDValue();
15328 
15329   // Depending on the addressing mode, this is either a pointer or a vector of
15330   // pointers (that fits into one register)
15331   SDValue Base = N->getOperand(3);
15332   // Depending on the addressing mode, this is either a single offset or a
15333   // vector of offsets  (that fits into one register)
15334   SDValue Offset = N->getOperand(4);
15335 
15336   // For "scalar + vector of indices", just scale the indices. This only
15337   // applies to non-temporal gathers because there's no instruction that takes
15338   // indicies.
15339   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
15340     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
15341                                         RetVT.getScalarSizeInBits());
15342     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
15343   }
15344 
15345   // In the case of non-temporal gather loads there's only one SVE instruction
15346   // per data-size: "scalar + vector", i.e.
15347   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
15348   // Since we do have intrinsics that allow the arguments to be in a different
15349   // order, we may need to swap them to match the spec.
15350   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
15351       Offset.getValueType().isVector())
15352     std::swap(Base, Offset);
15353 
15354   // GLD{FF}1_IMM requires that the offset is an immediate that is:
15355   //    * a multiple of #SizeInBytes,
15356   //    * in the range [0, 31 x #SizeInBytes],
15357   // where #SizeInBytes is the size in bytes of the loaded items. For
15358   // immediates outside that range and non-immediate scalar offsets use
15359   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
15360   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
15361       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
15362     if (!isValidImmForSVEVecImmAddrMode(Offset,
15363                                         RetVT.getScalarSizeInBits() / 8)) {
15364       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
15365         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
15366                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
15367                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
15368       else
15369         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
15370                      ? AArch64ISD::GLD1_MERGE_ZERO
15371                      : AArch64ISD::GLDFF1_MERGE_ZERO;
15372 
15373       std::swap(Base, Offset);
15374     }
15375   }
15376 
15377   auto &TLI = DAG.getTargetLoweringInfo();
15378   if (!TLI.isTypeLegal(Base.getValueType()))
15379     return SDValue();
15380 
15381   // Some gather load variants allow unpacked offsets, but only as nxv2i32
15382   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
15383   // nxv2i64. Legalize accordingly.
15384   if (!OnlyPackedOffsets &&
15385       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
15386     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
15387 
15388   // Return value type that is representable in hardware
15389   EVT HwRetVt = getSVEContainerType(RetVT);
15390 
15391   // Keep the original output value type around - this is needed to be able to
15392   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
15393   // values we want the integer equivalent, so just use HwRetVT.
15394   SDValue OutVT = DAG.getValueType(RetVT);
15395   if (RetVT.isFloatingPoint())
15396     OutVT = DAG.getValueType(HwRetVt);
15397 
15398   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
15399   SDValue Ops[] = {N->getOperand(0), // Chain
15400                    N->getOperand(2), // Pg
15401                    Base, Offset, OutVT};
15402 
15403   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
15404   SDValue LoadChain = SDValue(Load.getNode(), 1);
15405 
15406   if (RetVT.isInteger() && (RetVT != HwRetVt))
15407     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
15408 
15409   // If the original return value was FP, bitcast accordingly. Doing it here
15410   // means that we can avoid adding TableGen patterns for FPs.
15411   if (RetVT.isFloatingPoint())
15412     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
15413 
15414   return DAG.getMergeValues({Load, LoadChain}, DL);
15415 }
15416 
15417 static SDValue
15418 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
15419                               SelectionDAG &DAG) {
15420   SDLoc DL(N);
15421   SDValue Src = N->getOperand(0);
15422   unsigned Opc = Src->getOpcode();
15423 
15424   // Sign extend of an unsigned unpack -> signed unpack
15425   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
15426 
15427     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
15428                                                : AArch64ISD::SUNPKLO;
15429 
15430     // Push the sign extend to the operand of the unpack
15431     // This is necessary where, for example, the operand of the unpack
15432     // is another unpack:
15433     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
15434     // ->
15435     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
15436     // ->
15437     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
15438     SDValue ExtOp = Src->getOperand(0);
15439     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
15440     EVT EltTy = VT.getVectorElementType();
15441     (void)EltTy;
15442 
15443     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
15444            "Sign extending from an invalid type");
15445 
15446     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
15447 
15448     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
15449                               ExtOp, DAG.getValueType(ExtVT));
15450 
15451     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
15452   }
15453 
15454   if (DCI.isBeforeLegalizeOps())
15455     return SDValue();
15456 
15457   if (!EnableCombineMGatherIntrinsics)
15458     return SDValue();
15459 
15460   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
15461   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
15462   unsigned NewOpc;
15463   unsigned MemVTOpNum = 4;
15464   switch (Opc) {
15465   case AArch64ISD::LD1_MERGE_ZERO:
15466     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
15467     MemVTOpNum = 3;
15468     break;
15469   case AArch64ISD::LDNF1_MERGE_ZERO:
15470     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
15471     MemVTOpNum = 3;
15472     break;
15473   case AArch64ISD::LDFF1_MERGE_ZERO:
15474     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
15475     MemVTOpNum = 3;
15476     break;
15477   case AArch64ISD::GLD1_MERGE_ZERO:
15478     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
15479     break;
15480   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
15481     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
15482     break;
15483   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
15484     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
15485     break;
15486   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
15487     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
15488     break;
15489   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
15490     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
15491     break;
15492   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
15493     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
15494     break;
15495   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
15496     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
15497     break;
15498   case AArch64ISD::GLDFF1_MERGE_ZERO:
15499     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
15500     break;
15501   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
15502     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
15503     break;
15504   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
15505     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
15506     break;
15507   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
15508     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
15509     break;
15510   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
15511     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
15512     break;
15513   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
15514     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
15515     break;
15516   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
15517     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
15518     break;
15519   case AArch64ISD::GLDNT1_MERGE_ZERO:
15520     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
15521     break;
15522   default:
15523     return SDValue();
15524   }
15525 
15526   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
15527   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
15528 
15529   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
15530     return SDValue();
15531 
15532   EVT DstVT = N->getValueType(0);
15533   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
15534 
15535   SmallVector<SDValue, 5> Ops;
15536   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
15537     Ops.push_back(Src->getOperand(I));
15538 
15539   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
15540   DCI.CombineTo(N, ExtLoad);
15541   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
15542 
15543   // Return N so it doesn't get rechecked
15544   return SDValue(N, 0);
15545 }
15546 
15547 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
15548 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
15549 /// != nxv2i32) do not need legalization.
15550 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
15551   const unsigned OffsetPos = 4;
15552   SDValue Offset = N->getOperand(OffsetPos);
15553 
15554   // Not an unpacked vector, bail out.
15555   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
15556     return SDValue();
15557 
15558   // Extend the unpacked offset vector to 64-bit lanes.
15559   SDLoc DL(N);
15560   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
15561   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
15562   // Replace the offset operand with the 64-bit one.
15563   Ops[OffsetPos] = Offset;
15564 
15565   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
15566 }
15567 
15568 /// Combines a node carrying the intrinsic
15569 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
15570 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
15571 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
15572 /// sve gather prefetch instruction with vector plus immediate addressing mode.
15573 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
15574                                                unsigned ScalarSizeInBytes) {
15575   const unsigned ImmPos = 4, OffsetPos = 3;
15576   // No need to combine the node if the immediate is valid...
15577   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
15578     return SDValue();
15579 
15580   // ...otherwise swap the offset base with the offset...
15581   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
15582   std::swap(Ops[ImmPos], Ops[OffsetPos]);
15583   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
15584   // `aarch64_sve_prfb_gather_uxtw_index`.
15585   SDLoc DL(N);
15586   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
15587                            MVT::i64);
15588 
15589   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
15590 }
15591 
15592 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
15593                                                  DAGCombinerInfo &DCI) const {
15594   SelectionDAG &DAG = DCI.DAG;
15595   switch (N->getOpcode()) {
15596   default:
15597     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
15598     break;
15599   case ISD::ABS:
15600     return performABSCombine(N, DAG, DCI, Subtarget);
15601   case ISD::ADD:
15602   case ISD::SUB:
15603     return performAddSubCombine(N, DCI, DAG);
15604   case ISD::XOR:
15605     return performXorCombine(N, DAG, DCI, Subtarget);
15606   case ISD::MUL:
15607     return performMulCombine(N, DAG, DCI, Subtarget);
15608   case ISD::SINT_TO_FP:
15609   case ISD::UINT_TO_FP:
15610     return performIntToFpCombine(N, DAG, Subtarget);
15611   case ISD::FP_TO_SINT:
15612   case ISD::FP_TO_UINT:
15613     return performFpToIntCombine(N, DAG, DCI, Subtarget);
15614   case ISD::FDIV:
15615     return performFDivCombine(N, DAG, DCI, Subtarget);
15616   case ISD::OR:
15617     return performORCombine(N, DCI, Subtarget);
15618   case ISD::AND:
15619     return performANDCombine(N, DCI);
15620   case ISD::SRL:
15621     return performSRLCombine(N, DCI);
15622   case ISD::INTRINSIC_WO_CHAIN:
15623     return performIntrinsicCombine(N, DCI, Subtarget);
15624   case ISD::ANY_EXTEND:
15625   case ISD::ZERO_EXTEND:
15626   case ISD::SIGN_EXTEND:
15627     return performExtendCombine(N, DCI, DAG);
15628   case ISD::SIGN_EXTEND_INREG:
15629     return performSignExtendInRegCombine(N, DCI, DAG);
15630   case ISD::TRUNCATE:
15631     return performVectorTruncateCombine(N, DCI, DAG);
15632   case ISD::CONCAT_VECTORS:
15633     return performConcatVectorsCombine(N, DCI, DAG);
15634   case ISD::SELECT:
15635     return performSelectCombine(N, DCI);
15636   case ISD::VSELECT:
15637     return performVSelectCombine(N, DCI.DAG);
15638   case ISD::LOAD:
15639     if (performTBISimplification(N->getOperand(1), DCI, DAG))
15640       return SDValue(N, 0);
15641     break;
15642   case ISD::STORE:
15643     return performSTORECombine(N, DCI, DAG, Subtarget);
15644   case AArch64ISD::BRCOND:
15645     return performBRCONDCombine(N, DCI, DAG);
15646   case AArch64ISD::TBNZ:
15647   case AArch64ISD::TBZ:
15648     return performTBZCombine(N, DCI, DAG);
15649   case AArch64ISD::CSEL:
15650     return performCONDCombine(N, DCI, DAG, 2, 3);
15651   case AArch64ISD::DUP:
15652     return performPostLD1Combine(N, DCI, false);
15653   case AArch64ISD::NVCAST:
15654     return performNVCASTCombine(N);
15655   case AArch64ISD::UZP1:
15656     return performUzpCombine(N, DAG);
15657   case ISD::INSERT_VECTOR_ELT:
15658     return performPostLD1Combine(N, DCI, true);
15659   case ISD::EXTRACT_VECTOR_ELT:
15660     return performExtractVectorEltCombine(N, DAG);
15661   case ISD::VECREDUCE_ADD:
15662     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
15663   case ISD::INTRINSIC_VOID:
15664   case ISD::INTRINSIC_W_CHAIN:
15665     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15666     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
15667       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
15668     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
15669       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
15670     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
15671       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
15672     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
15673       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
15674     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
15675     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
15676     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
15677     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
15678     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
15679     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
15680     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
15681     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
15682       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
15683     case Intrinsic::aarch64_neon_ld2:
15684     case Intrinsic::aarch64_neon_ld3:
15685     case Intrinsic::aarch64_neon_ld4:
15686     case Intrinsic::aarch64_neon_ld1x2:
15687     case Intrinsic::aarch64_neon_ld1x3:
15688     case Intrinsic::aarch64_neon_ld1x4:
15689     case Intrinsic::aarch64_neon_ld2lane:
15690     case Intrinsic::aarch64_neon_ld3lane:
15691     case Intrinsic::aarch64_neon_ld4lane:
15692     case Intrinsic::aarch64_neon_ld2r:
15693     case Intrinsic::aarch64_neon_ld3r:
15694     case Intrinsic::aarch64_neon_ld4r:
15695     case Intrinsic::aarch64_neon_st2:
15696     case Intrinsic::aarch64_neon_st3:
15697     case Intrinsic::aarch64_neon_st4:
15698     case Intrinsic::aarch64_neon_st1x2:
15699     case Intrinsic::aarch64_neon_st1x3:
15700     case Intrinsic::aarch64_neon_st1x4:
15701     case Intrinsic::aarch64_neon_st2lane:
15702     case Intrinsic::aarch64_neon_st3lane:
15703     case Intrinsic::aarch64_neon_st4lane:
15704       return performNEONPostLDSTCombine(N, DCI, DAG);
15705     case Intrinsic::aarch64_sve_ldnt1:
15706       return performLDNT1Combine(N, DAG);
15707     case Intrinsic::aarch64_sve_ld1rq:
15708       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
15709     case Intrinsic::aarch64_sve_ld1ro:
15710       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
15711     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
15712       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15713     case Intrinsic::aarch64_sve_ldnt1_gather:
15714       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15715     case Intrinsic::aarch64_sve_ldnt1_gather_index:
15716       return performGatherLoadCombine(N, DAG,
15717                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
15718     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
15719       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15720     case Intrinsic::aarch64_sve_ld1:
15721       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
15722     case Intrinsic::aarch64_sve_ldnf1:
15723       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
15724     case Intrinsic::aarch64_sve_ldff1:
15725       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
15726     case Intrinsic::aarch64_sve_st1:
15727       return performST1Combine(N, DAG);
15728     case Intrinsic::aarch64_sve_stnt1:
15729       return performSTNT1Combine(N, DAG);
15730     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
15731       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15732     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
15733       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15734     case Intrinsic::aarch64_sve_stnt1_scatter:
15735       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15736     case Intrinsic::aarch64_sve_stnt1_scatter_index:
15737       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
15738     case Intrinsic::aarch64_sve_ld1_gather:
15739       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
15740     case Intrinsic::aarch64_sve_ld1_gather_index:
15741       return performGatherLoadCombine(N, DAG,
15742                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
15743     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
15744       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
15745                                       /*OnlyPackedOffsets=*/false);
15746     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
15747       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
15748                                       /*OnlyPackedOffsets=*/false);
15749     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
15750       return performGatherLoadCombine(N, DAG,
15751                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
15752                                       /*OnlyPackedOffsets=*/false);
15753     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
15754       return performGatherLoadCombine(N, DAG,
15755                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
15756                                       /*OnlyPackedOffsets=*/false);
15757     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
15758       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
15759     case Intrinsic::aarch64_sve_ldff1_gather:
15760       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
15761     case Intrinsic::aarch64_sve_ldff1_gather_index:
15762       return performGatherLoadCombine(N, DAG,
15763                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
15764     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
15765       return performGatherLoadCombine(N, DAG,
15766                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
15767                                       /*OnlyPackedOffsets=*/false);
15768     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
15769       return performGatherLoadCombine(N, DAG,
15770                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
15771                                       /*OnlyPackedOffsets=*/false);
15772     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
15773       return performGatherLoadCombine(N, DAG,
15774                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
15775                                       /*OnlyPackedOffsets=*/false);
15776     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
15777       return performGatherLoadCombine(N, DAG,
15778                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
15779                                       /*OnlyPackedOffsets=*/false);
15780     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
15781       return performGatherLoadCombine(N, DAG,
15782                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
15783     case Intrinsic::aarch64_sve_st1_scatter:
15784       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
15785     case Intrinsic::aarch64_sve_st1_scatter_index:
15786       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
15787     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
15788       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
15789                                         /*OnlyPackedOffsets=*/false);
15790     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
15791       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
15792                                         /*OnlyPackedOffsets=*/false);
15793     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
15794       return performScatterStoreCombine(N, DAG,
15795                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
15796                                         /*OnlyPackedOffsets=*/false);
15797     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
15798       return performScatterStoreCombine(N, DAG,
15799                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
15800                                         /*OnlyPackedOffsets=*/false);
15801     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
15802       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
15803     case Intrinsic::aarch64_sve_tuple_get: {
15804       SDLoc DL(N);
15805       SDValue Chain = N->getOperand(0);
15806       SDValue Src1 = N->getOperand(2);
15807       SDValue Idx = N->getOperand(3);
15808 
15809       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15810       EVT ResVT = N->getValueType(0);
15811       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
15812       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
15813       SDValue Val =
15814           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
15815       return DAG.getMergeValues({Val, Chain}, DL);
15816     }
15817     case Intrinsic::aarch64_sve_tuple_set: {
15818       SDLoc DL(N);
15819       SDValue Chain = N->getOperand(0);
15820       SDValue Tuple = N->getOperand(2);
15821       SDValue Idx = N->getOperand(3);
15822       SDValue Vec = N->getOperand(4);
15823 
15824       EVT TupleVT = Tuple.getValueType();
15825       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
15826 
15827       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15828       uint64_t NumLanes =
15829           Vec.getValueType().getVectorElementCount().getKnownMinValue();
15830 
15831       if ((TupleLanes % NumLanes) != 0)
15832         report_fatal_error("invalid tuple vector!");
15833 
15834       uint64_t NumVecs = TupleLanes / NumLanes;
15835 
15836       SmallVector<SDValue, 4> Opnds;
15837       for (unsigned I = 0; I < NumVecs; ++I) {
15838         if (I == IdxConst)
15839           Opnds.push_back(Vec);
15840         else {
15841           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
15842           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
15843                                       Vec.getValueType(), Tuple, ExtIdx));
15844         }
15845       }
15846       SDValue Concat =
15847           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
15848       return DAG.getMergeValues({Concat, Chain}, DL);
15849     }
15850     case Intrinsic::aarch64_sve_tuple_create2:
15851     case Intrinsic::aarch64_sve_tuple_create3:
15852     case Intrinsic::aarch64_sve_tuple_create4: {
15853       SDLoc DL(N);
15854       SDValue Chain = N->getOperand(0);
15855 
15856       SmallVector<SDValue, 4> Opnds;
15857       for (unsigned I = 2; I < N->getNumOperands(); ++I)
15858         Opnds.push_back(N->getOperand(I));
15859 
15860       EVT VT = Opnds[0].getValueType();
15861       EVT EltVT = VT.getVectorElementType();
15862       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
15863                                     VT.getVectorElementCount() *
15864                                         (N->getNumOperands() - 2));
15865       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
15866       return DAG.getMergeValues({Concat, Chain}, DL);
15867     }
15868     case Intrinsic::aarch64_sve_ld2:
15869     case Intrinsic::aarch64_sve_ld3:
15870     case Intrinsic::aarch64_sve_ld4: {
15871       SDLoc DL(N);
15872       SDValue Chain = N->getOperand(0);
15873       SDValue Mask = N->getOperand(2);
15874       SDValue BasePtr = N->getOperand(3);
15875       SDValue LoadOps[] = {Chain, Mask, BasePtr};
15876       unsigned IntrinsicID =
15877           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15878       SDValue Result =
15879           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
15880       return DAG.getMergeValues({Result, Chain}, DL);
15881     }
15882     default:
15883       break;
15884     }
15885     break;
15886   case ISD::GlobalAddress:
15887     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
15888   }
15889   return SDValue();
15890 }
15891 
15892 // Check if the return value is used as only a return value, as otherwise
15893 // we can't perform a tail-call. In particular, we need to check for
15894 // target ISD nodes that are returns and any other "odd" constructs
15895 // that the generic analysis code won't necessarily catch.
15896 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
15897                                                SDValue &Chain) const {
15898   if (N->getNumValues() != 1)
15899     return false;
15900   if (!N->hasNUsesOfValue(1, 0))
15901     return false;
15902 
15903   SDValue TCChain = Chain;
15904   SDNode *Copy = *N->use_begin();
15905   if (Copy->getOpcode() == ISD::CopyToReg) {
15906     // If the copy has a glue operand, we conservatively assume it isn't safe to
15907     // perform a tail call.
15908     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
15909         MVT::Glue)
15910       return false;
15911     TCChain = Copy->getOperand(0);
15912   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
15913     return false;
15914 
15915   bool HasRet = false;
15916   for (SDNode *Node : Copy->uses()) {
15917     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
15918       return false;
15919     HasRet = true;
15920   }
15921 
15922   if (!HasRet)
15923     return false;
15924 
15925   Chain = TCChain;
15926   return true;
15927 }
15928 
15929 // Return whether the an instruction can potentially be optimized to a tail
15930 // call. This will cause the optimizers to attempt to move, or duplicate,
15931 // return instructions to help enable tail call optimizations for this
15932 // instruction.
15933 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15934   return CI->isTailCall();
15935 }
15936 
15937 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
15938                                                    SDValue &Offset,
15939                                                    ISD::MemIndexedMode &AM,
15940                                                    bool &IsInc,
15941                                                    SelectionDAG &DAG) const {
15942   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
15943     return false;
15944 
15945   Base = Op->getOperand(0);
15946   // All of the indexed addressing mode instructions take a signed
15947   // 9 bit immediate offset.
15948   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
15949     int64_t RHSC = RHS->getSExtValue();
15950     if (Op->getOpcode() == ISD::SUB)
15951       RHSC = -(uint64_t)RHSC;
15952     if (!isInt<9>(RHSC))
15953       return false;
15954     IsInc = (Op->getOpcode() == ISD::ADD);
15955     Offset = Op->getOperand(1);
15956     return true;
15957   }
15958   return false;
15959 }
15960 
15961 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15962                                                       SDValue &Offset,
15963                                                       ISD::MemIndexedMode &AM,
15964                                                       SelectionDAG &DAG) const {
15965   EVT VT;
15966   SDValue Ptr;
15967   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15968     VT = LD->getMemoryVT();
15969     Ptr = LD->getBasePtr();
15970   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15971     VT = ST->getMemoryVT();
15972     Ptr = ST->getBasePtr();
15973   } else
15974     return false;
15975 
15976   bool IsInc;
15977   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
15978     return false;
15979   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
15980   return true;
15981 }
15982 
15983 bool AArch64TargetLowering::getPostIndexedAddressParts(
15984     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
15985     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
15986   EVT VT;
15987   SDValue Ptr;
15988   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15989     VT = LD->getMemoryVT();
15990     Ptr = LD->getBasePtr();
15991   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15992     VT = ST->getMemoryVT();
15993     Ptr = ST->getBasePtr();
15994   } else
15995     return false;
15996 
15997   bool IsInc;
15998   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
15999     return false;
16000   // Post-indexing updates the base, so it's not a valid transform
16001   // if that's not the same as the load's pointer.
16002   if (Ptr != Base)
16003     return false;
16004   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
16005   return true;
16006 }
16007 
16008 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
16009                                   SelectionDAG &DAG) {
16010   SDLoc DL(N);
16011   SDValue Op = N->getOperand(0);
16012 
16013   if (N->getValueType(0) != MVT::i16 ||
16014       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
16015     return;
16016 
16017   Op = SDValue(
16018       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
16019                          DAG.getUNDEF(MVT::i32), Op,
16020                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
16021       0);
16022   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
16023   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
16024 }
16025 
16026 static void ReplaceReductionResults(SDNode *N,
16027                                     SmallVectorImpl<SDValue> &Results,
16028                                     SelectionDAG &DAG, unsigned InterOp,
16029                                     unsigned AcrossOp) {
16030   EVT LoVT, HiVT;
16031   SDValue Lo, Hi;
16032   SDLoc dl(N);
16033   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
16034   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
16035   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
16036   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
16037   Results.push_back(SplitVal);
16038 }
16039 
16040 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
16041   SDLoc DL(N);
16042   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
16043   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
16044                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
16045                                        DAG.getConstant(64, DL, MVT::i64)));
16046   return std::make_pair(Lo, Hi);
16047 }
16048 
16049 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
16050     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
16051   SDValue In = N->getOperand(0);
16052   EVT InVT = In.getValueType();
16053 
16054   // Common code will handle these just fine.
16055   if (!InVT.isScalableVector() || !InVT.isInteger())
16056     return;
16057 
16058   SDLoc DL(N);
16059   EVT VT = N->getValueType(0);
16060 
16061   // The following checks bail if this is not a halving operation.
16062 
16063   ElementCount ResEC = VT.getVectorElementCount();
16064 
16065   if (InVT.getVectorElementCount() != (ResEC * 2))
16066     return;
16067 
16068   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
16069   if (!CIndex)
16070     return;
16071 
16072   unsigned Index = CIndex->getZExtValue();
16073   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
16074     return;
16075 
16076   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
16077   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
16078 
16079   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
16080   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
16081 }
16082 
16083 // Create an even/odd pair of X registers holding integer value V.
16084 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
16085   SDLoc dl(V.getNode());
16086   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
16087   SDValue VHi = DAG.getAnyExtOrTrunc(
16088       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
16089       dl, MVT::i64);
16090   if (DAG.getDataLayout().isBigEndian())
16091     std::swap (VLo, VHi);
16092   SDValue RegClass =
16093       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
16094   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
16095   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
16096   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
16097   return SDValue(
16098       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
16099 }
16100 
16101 static void ReplaceCMP_SWAP_128Results(SDNode *N,
16102                                        SmallVectorImpl<SDValue> &Results,
16103                                        SelectionDAG &DAG,
16104                                        const AArch64Subtarget *Subtarget) {
16105   assert(N->getValueType(0) == MVT::i128 &&
16106          "AtomicCmpSwap on types less than 128 should be legal");
16107 
16108   if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
16109     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
16110     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
16111     SDValue Ops[] = {
16112         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
16113         createGPRPairNode(DAG, N->getOperand(3)), // Store value
16114         N->getOperand(1), // Ptr
16115         N->getOperand(0), // Chain in
16116     };
16117 
16118     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
16119 
16120     unsigned Opcode;
16121     switch (MemOp->getOrdering()) {
16122     case AtomicOrdering::Monotonic:
16123       Opcode = AArch64::CASPX;
16124       break;
16125     case AtomicOrdering::Acquire:
16126       Opcode = AArch64::CASPAX;
16127       break;
16128     case AtomicOrdering::Release:
16129       Opcode = AArch64::CASPLX;
16130       break;
16131     case AtomicOrdering::AcquireRelease:
16132     case AtomicOrdering::SequentiallyConsistent:
16133       Opcode = AArch64::CASPALX;
16134       break;
16135     default:
16136       llvm_unreachable("Unexpected ordering!");
16137     }
16138 
16139     MachineSDNode *CmpSwap = DAG.getMachineNode(
16140         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
16141     DAG.setNodeMemRefs(CmpSwap, {MemOp});
16142 
16143     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
16144     if (DAG.getDataLayout().isBigEndian())
16145       std::swap(SubReg1, SubReg2);
16146     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
16147                                             SDValue(CmpSwap, 0));
16148     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
16149                                             SDValue(CmpSwap, 0));
16150     Results.push_back(
16151         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
16152     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
16153     return;
16154   }
16155 
16156   auto Desired = splitInt128(N->getOperand(2), DAG);
16157   auto New = splitInt128(N->getOperand(3), DAG);
16158   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
16159                    New.first,        New.second,    N->getOperand(0)};
16160   SDNode *CmpSwap = DAG.getMachineNode(
16161       AArch64::CMP_SWAP_128, SDLoc(N),
16162       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
16163 
16164   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
16165   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
16166 
16167   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
16168                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
16169   Results.push_back(SDValue(CmpSwap, 3));
16170 }
16171 
16172 void AArch64TargetLowering::ReplaceNodeResults(
16173     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
16174   switch (N->getOpcode()) {
16175   default:
16176     llvm_unreachable("Don't know how to custom expand this");
16177   case ISD::BITCAST:
16178     ReplaceBITCASTResults(N, Results, DAG);
16179     return;
16180   case ISD::VECREDUCE_ADD:
16181   case ISD::VECREDUCE_SMAX:
16182   case ISD::VECREDUCE_SMIN:
16183   case ISD::VECREDUCE_UMAX:
16184   case ISD::VECREDUCE_UMIN:
16185     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
16186     return;
16187 
16188   case ISD::CTPOP:
16189     if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
16190       Results.push_back(Result);
16191     return;
16192   case AArch64ISD::SADDV:
16193     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
16194     return;
16195   case AArch64ISD::UADDV:
16196     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
16197     return;
16198   case AArch64ISD::SMINV:
16199     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
16200     return;
16201   case AArch64ISD::UMINV:
16202     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
16203     return;
16204   case AArch64ISD::SMAXV:
16205     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
16206     return;
16207   case AArch64ISD::UMAXV:
16208     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
16209     return;
16210   case ISD::FP_TO_UINT:
16211   case ISD::FP_TO_SINT:
16212     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
16213     // Let normal code take care of it by not adding anything to Results.
16214     return;
16215   case ISD::ATOMIC_CMP_SWAP:
16216     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
16217     return;
16218   case ISD::LOAD: {
16219     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
16220            "unexpected load's value type");
16221     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
16222     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
16223       // Non-volatile loads are optimized later in AArch64's load/store
16224       // optimizer.
16225       return;
16226     }
16227 
16228     SDValue Result = DAG.getMemIntrinsicNode(
16229         AArch64ISD::LDP, SDLoc(N),
16230         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
16231         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
16232         LoadNode->getMemOperand());
16233 
16234     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
16235                                Result.getValue(0), Result.getValue(1));
16236     Results.append({Pair, Result.getValue(2) /* Chain */});
16237     return;
16238   }
16239   case ISD::EXTRACT_SUBVECTOR:
16240     ReplaceExtractSubVectorResults(N, Results, DAG);
16241     return;
16242   case ISD::INTRINSIC_WO_CHAIN: {
16243     EVT VT = N->getValueType(0);
16244     assert((VT == MVT::i8 || VT == MVT::i16) &&
16245            "custom lowering for unexpected type");
16246 
16247     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
16248     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
16249     switch (IntID) {
16250     default:
16251       return;
16252     case Intrinsic::aarch64_sve_clasta_n: {
16253       SDLoc DL(N);
16254       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
16255       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
16256                            N->getOperand(1), Op2, N->getOperand(3));
16257       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
16258       return;
16259     }
16260     case Intrinsic::aarch64_sve_clastb_n: {
16261       SDLoc DL(N);
16262       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
16263       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
16264                            N->getOperand(1), Op2, N->getOperand(3));
16265       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
16266       return;
16267     }
16268     case Intrinsic::aarch64_sve_lasta: {
16269       SDLoc DL(N);
16270       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
16271                            N->getOperand(1), N->getOperand(2));
16272       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
16273       return;
16274     }
16275     case Intrinsic::aarch64_sve_lastb: {
16276       SDLoc DL(N);
16277       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
16278                            N->getOperand(1), N->getOperand(2));
16279       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
16280       return;
16281     }
16282     }
16283   }
16284   }
16285 }
16286 
16287 bool AArch64TargetLowering::useLoadStackGuardNode() const {
16288   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
16289     return TargetLowering::useLoadStackGuardNode();
16290   return true;
16291 }
16292 
16293 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
16294   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
16295   // reciprocal if there are three or more FDIVs.
16296   return 3;
16297 }
16298 
16299 TargetLoweringBase::LegalizeTypeAction
16300 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
16301   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
16302   // v4i16, v2i32 instead of to promote.
16303   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
16304       VT == MVT::v1f32)
16305     return TypeWidenVector;
16306 
16307   return TargetLoweringBase::getPreferredVectorAction(VT);
16308 }
16309 
16310 // Loads and stores less than 128-bits are already atomic; ones above that
16311 // are doomed anyway, so defer to the default libcall and blame the OS when
16312 // things go wrong.
16313 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16314   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16315   return Size == 128;
16316 }
16317 
16318 // Loads and stores less than 128-bits are already atomic; ones above that
16319 // are doomed anyway, so defer to the default libcall and blame the OS when
16320 // things go wrong.
16321 TargetLowering::AtomicExpansionKind
16322 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16323   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16324   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
16325 }
16326 
16327 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
16328 TargetLowering::AtomicExpansionKind
16329 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16330   if (AI->isFloatingPointOperation())
16331     return AtomicExpansionKind::CmpXChg;
16332 
16333   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16334   if (Size > 128) return AtomicExpansionKind::None;
16335   // Nand not supported in LSE.
16336   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
16337   // Leave 128 bits to LLSC.
16338   if (Subtarget->hasLSE() && Size < 128)
16339     return AtomicExpansionKind::None;
16340   if (Subtarget->outlineAtomics() && Size < 128) {
16341     // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
16342     // Don't outline them unless
16343     // (1) high level <atomic> support approved:
16344     //   http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
16345     // (2) low level libgcc and compiler-rt support implemented by:
16346     //   min/max outline atomics helpers
16347     if (AI->getOperation() != AtomicRMWInst::Min &&
16348         AI->getOperation() != AtomicRMWInst::Max &&
16349         AI->getOperation() != AtomicRMWInst::UMin &&
16350         AI->getOperation() != AtomicRMWInst::UMax) {
16351       return AtomicExpansionKind::None;
16352     }
16353   }
16354   return AtomicExpansionKind::LLSC;
16355 }
16356 
16357 TargetLowering::AtomicExpansionKind
16358 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
16359     AtomicCmpXchgInst *AI) const {
16360   // If subtarget has LSE, leave cmpxchg intact for codegen.
16361   if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
16362     return AtomicExpansionKind::None;
16363   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16364   // implement cmpxchg without spilling. If the address being exchanged is also
16365   // on the stack and close enough to the spill slot, this can lead to a
16366   // situation where the monitor always gets cleared and the atomic operation
16367   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16368   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
16369     return AtomicExpansionKind::None;
16370   return AtomicExpansionKind::LLSC;
16371 }
16372 
16373 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16374                                              AtomicOrdering Ord) const {
16375   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16376   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16377   bool IsAcquire = isAcquireOrStronger(Ord);
16378 
16379   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
16380   // intrinsic must return {i64, i64} and we have to recombine them into a
16381   // single i128 here.
16382   if (ValTy->getPrimitiveSizeInBits() == 128) {
16383     Intrinsic::ID Int =
16384         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
16385     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
16386 
16387     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16388     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
16389 
16390     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16391     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16392     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16393     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16394     return Builder.CreateOr(
16395         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
16396   }
16397 
16398   Type *Tys[] = { Addr->getType() };
16399   Intrinsic::ID Int =
16400       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
16401   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
16402 
16403   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
16404 
16405   const DataLayout &DL = M->getDataLayout();
16406   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
16407   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
16408 
16409   return Builder.CreateBitCast(Trunc, EltTy);
16410 }
16411 
16412 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16413     IRBuilder<> &Builder) const {
16414   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16415   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
16416 }
16417 
16418 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
16419                                                    Value *Val, Value *Addr,
16420                                                    AtomicOrdering Ord) const {
16421   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16422   bool IsRelease = isReleaseOrStronger(Ord);
16423 
16424   // Since the intrinsics must have legal type, the i128 intrinsics take two
16425   // parameters: "i64, i64". We must marshal Val into the appropriate form
16426   // before the call.
16427   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
16428     Intrinsic::ID Int =
16429         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
16430     Function *Stxr = Intrinsic::getDeclaration(M, Int);
16431     Type *Int64Ty = Type::getInt64Ty(M->getContext());
16432 
16433     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
16434     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
16435     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16436     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
16437   }
16438 
16439   Intrinsic::ID Int =
16440       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
16441   Type *Tys[] = { Addr->getType() };
16442   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
16443 
16444   const DataLayout &DL = M->getDataLayout();
16445   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
16446   Val = Builder.CreateBitCast(Val, IntValTy);
16447 
16448   return Builder.CreateCall(Stxr,
16449                             {Builder.CreateZExtOrBitCast(
16450                                  Val, Stxr->getFunctionType()->getParamType(0)),
16451                              Addr});
16452 }
16453 
16454 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
16455     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16456   if (Ty->isArrayTy())
16457     return true;
16458 
16459   const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
16460   if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
16461     return true;
16462 
16463   return false;
16464 }
16465 
16466 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
16467                                                             EVT) const {
16468   return false;
16469 }
16470 
16471 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
16472   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
16473   Function *ThreadPointerFunc =
16474       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
16475   return IRB.CreatePointerCast(
16476       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
16477                              Offset),
16478       IRB.getInt8PtrTy()->getPointerTo(0));
16479 }
16480 
16481 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
16482   // Android provides a fixed TLS slot for the stack cookie. See the definition
16483   // of TLS_SLOT_STACK_GUARD in
16484   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
16485   if (Subtarget->isTargetAndroid())
16486     return UseTlsOffset(IRB, 0x28);
16487 
16488   // Fuchsia is similar.
16489   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
16490   if (Subtarget->isTargetFuchsia())
16491     return UseTlsOffset(IRB, -0x10);
16492 
16493   return TargetLowering::getIRStackGuard(IRB);
16494 }
16495 
16496 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
16497   // MSVC CRT provides functionalities for stack protection.
16498   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
16499     // MSVC CRT has a global variable holding security cookie.
16500     M.getOrInsertGlobal("__security_cookie",
16501                         Type::getInt8PtrTy(M.getContext()));
16502 
16503     // MSVC CRT has a function to validate security cookie.
16504     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16505         "__security_check_cookie", Type::getVoidTy(M.getContext()),
16506         Type::getInt8PtrTy(M.getContext()));
16507     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
16508       F->setCallingConv(CallingConv::Win64);
16509       F->addAttribute(1, Attribute::AttrKind::InReg);
16510     }
16511     return;
16512   }
16513   TargetLowering::insertSSPDeclarations(M);
16514 }
16515 
16516 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
16517   // MSVC CRT has a global variable holding security cookie.
16518   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16519     return M.getGlobalVariable("__security_cookie");
16520   return TargetLowering::getSDagStackGuard(M);
16521 }
16522 
16523 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
16524   // MSVC CRT has a function to validate security cookie.
16525   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16526     return M.getFunction("__security_check_cookie");
16527   return TargetLowering::getSSPStackGuardCheck(M);
16528 }
16529 
16530 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
16531   // Android provides a fixed TLS slot for the SafeStack pointer. See the
16532   // definition of TLS_SLOT_SAFESTACK in
16533   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
16534   if (Subtarget->isTargetAndroid())
16535     return UseTlsOffset(IRB, 0x48);
16536 
16537   // Fuchsia is similar.
16538   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
16539   if (Subtarget->isTargetFuchsia())
16540     return UseTlsOffset(IRB, -0x8);
16541 
16542   return TargetLowering::getSafeStackPointerLocation(IRB);
16543 }
16544 
16545 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
16546     const Instruction &AndI) const {
16547   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
16548   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
16549   // may be beneficial to sink in other cases, but we would have to check that
16550   // the cmp would not get folded into the br to form a cbz for these to be
16551   // beneficial.
16552   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
16553   if (!Mask)
16554     return false;
16555   return Mask->getValue().isPowerOf2();
16556 }
16557 
16558 bool AArch64TargetLowering::
16559     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
16560         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
16561         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
16562         SelectionDAG &DAG) const {
16563   // Does baseline recommend not to perform the fold by default?
16564   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
16565           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
16566     return false;
16567   // Else, if this is a vector shift, prefer 'shl'.
16568   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
16569 }
16570 
16571 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
16572                                               SDNode *N) const {
16573   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16574       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
16575     return false;
16576   return true;
16577 }
16578 
16579 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16580   // Update IsSplitCSR in AArch64unctionInfo.
16581   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
16582   AFI->setIsSplitCSR(true);
16583 }
16584 
16585 void AArch64TargetLowering::insertCopiesSplitCSR(
16586     MachineBasicBlock *Entry,
16587     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16588   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
16589   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16590   if (!IStart)
16591     return;
16592 
16593   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16594   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16595   MachineBasicBlock::iterator MBBI = Entry->begin();
16596   for (const MCPhysReg *I = IStart; *I; ++I) {
16597     const TargetRegisterClass *RC = nullptr;
16598     if (AArch64::GPR64RegClass.contains(*I))
16599       RC = &AArch64::GPR64RegClass;
16600     else if (AArch64::FPR64RegClass.contains(*I))
16601       RC = &AArch64::FPR64RegClass;
16602     else
16603       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16604 
16605     Register NewVR = MRI->createVirtualRegister(RC);
16606     // Create copy from CSR to a virtual register.
16607     // FIXME: this currently does not emit CFI pseudo-instructions, it works
16608     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16609     // nounwind. If we want to generalize this later, we may need to emit
16610     // CFI pseudo-instructions.
16611     assert(Entry->getParent()->getFunction().hasFnAttribute(
16612                Attribute::NoUnwind) &&
16613            "Function should be nounwind in insertCopiesSplitCSR!");
16614     Entry->addLiveIn(*I);
16615     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16616         .addReg(*I);
16617 
16618     // Insert the copy-back instructions right before the terminator.
16619     for (auto *Exit : Exits)
16620       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16621               TII->get(TargetOpcode::COPY), *I)
16622           .addReg(NewVR);
16623   }
16624 }
16625 
16626 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
16627   // Integer division on AArch64 is expensive. However, when aggressively
16628   // optimizing for code size, we prefer to use a div instruction, as it is
16629   // usually smaller than the alternative sequence.
16630   // The exception to this is vector division. Since AArch64 doesn't have vector
16631   // integer division, leaving the division as-is is a loss even in terms of
16632   // size, because it will have to be scalarized, while the alternative code
16633   // sequence can be performed in vector form.
16634   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
16635   return OptSize && !VT.isVector();
16636 }
16637 
16638 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
16639   // We want inc-of-add for scalars and sub-of-not for vectors.
16640   return VT.isScalarInteger();
16641 }
16642 
16643 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
16644   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
16645 }
16646 
16647 unsigned
16648 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
16649   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
16650     return getPointerTy(DL).getSizeInBits();
16651 
16652   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
16653 }
16654 
16655 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
16656   MF.getFrameInfo().computeMaxCallFrameSize(MF);
16657   TargetLoweringBase::finalizeLowering(MF);
16658 }
16659 
16660 // Unlike X86, we let frame lowering assign offsets to all catch objects.
16661 bool AArch64TargetLowering::needsFixedCatchObjects() const {
16662   return false;
16663 }
16664 
16665 bool AArch64TargetLowering::shouldLocalize(
16666     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
16667   switch (MI.getOpcode()) {
16668   case TargetOpcode::G_GLOBAL_VALUE: {
16669     // On Darwin, TLS global vars get selected into function calls, which
16670     // we don't want localized, as they can get moved into the middle of a
16671     // another call sequence.
16672     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
16673     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
16674       return false;
16675     break;
16676   }
16677   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
16678   // localizable.
16679   case AArch64::ADRP:
16680   case AArch64::G_ADD_LOW:
16681     return true;
16682   default:
16683     break;
16684   }
16685   return TargetLoweringBase::shouldLocalize(MI, TTI);
16686 }
16687 
16688 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
16689   if (isa<ScalableVectorType>(Inst.getType()))
16690     return true;
16691 
16692   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
16693     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
16694       return true;
16695 
16696   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
16697     if (isa<ScalableVectorType>(AI->getAllocatedType()))
16698       return true;
16699   }
16700 
16701   return false;
16702 }
16703 
16704 // Return the largest legal scalable vector type that matches VT's element type.
16705 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
16706   assert(VT.isFixedLengthVector() &&
16707          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16708          "Expected legal fixed length vector!");
16709   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
16710   default:
16711     llvm_unreachable("unexpected element type for SVE container");
16712   case MVT::i8:
16713     return EVT(MVT::nxv16i8);
16714   case MVT::i16:
16715     return EVT(MVT::nxv8i16);
16716   case MVT::i32:
16717     return EVT(MVT::nxv4i32);
16718   case MVT::i64:
16719     return EVT(MVT::nxv2i64);
16720   case MVT::f16:
16721     return EVT(MVT::nxv8f16);
16722   case MVT::f32:
16723     return EVT(MVT::nxv4f32);
16724   case MVT::f64:
16725     return EVT(MVT::nxv2f64);
16726   }
16727 }
16728 
16729 // Return a PTRUE with active lanes corresponding to the extent of VT.
16730 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
16731                                                 EVT VT) {
16732   assert(VT.isFixedLengthVector() &&
16733          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16734          "Expected legal fixed length vector!");
16735 
16736   int PgPattern;
16737   switch (VT.getVectorNumElements()) {
16738   default:
16739     llvm_unreachable("unexpected element count for SVE predicate");
16740   case 1:
16741     PgPattern = AArch64SVEPredPattern::vl1;
16742     break;
16743   case 2:
16744     PgPattern = AArch64SVEPredPattern::vl2;
16745     break;
16746   case 4:
16747     PgPattern = AArch64SVEPredPattern::vl4;
16748     break;
16749   case 8:
16750     PgPattern = AArch64SVEPredPattern::vl8;
16751     break;
16752   case 16:
16753     PgPattern = AArch64SVEPredPattern::vl16;
16754     break;
16755   case 32:
16756     PgPattern = AArch64SVEPredPattern::vl32;
16757     break;
16758   case 64:
16759     PgPattern = AArch64SVEPredPattern::vl64;
16760     break;
16761   case 128:
16762     PgPattern = AArch64SVEPredPattern::vl128;
16763     break;
16764   case 256:
16765     PgPattern = AArch64SVEPredPattern::vl256;
16766     break;
16767   }
16768 
16769   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
16770   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
16771   // variants of instructions when available.
16772 
16773   MVT MaskVT;
16774   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
16775   default:
16776     llvm_unreachable("unexpected element type for SVE predicate");
16777   case MVT::i8:
16778     MaskVT = MVT::nxv16i1;
16779     break;
16780   case MVT::i16:
16781   case MVT::f16:
16782     MaskVT = MVT::nxv8i1;
16783     break;
16784   case MVT::i32:
16785   case MVT::f32:
16786     MaskVT = MVT::nxv4i1;
16787     break;
16788   case MVT::i64:
16789   case MVT::f64:
16790     MaskVT = MVT::nxv2i1;
16791     break;
16792   }
16793 
16794   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
16795                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
16796 }
16797 
16798 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
16799                                              EVT VT) {
16800   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16801          "Expected legal scalable vector!");
16802   auto PredTy = VT.changeVectorElementType(MVT::i1);
16803   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
16804 }
16805 
16806 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
16807   if (VT.isFixedLengthVector())
16808     return getPredicateForFixedLengthVector(DAG, DL, VT);
16809 
16810   return getPredicateForScalableVector(DAG, DL, VT);
16811 }
16812 
16813 // Grow V to consume an entire SVE register.
16814 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
16815   assert(VT.isScalableVector() &&
16816          "Expected to convert into a scalable vector!");
16817   assert(V.getValueType().isFixedLengthVector() &&
16818          "Expected a fixed length vector operand!");
16819   SDLoc DL(V);
16820   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16821   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
16822 }
16823 
16824 // Shrink V so it's just big enough to maintain a VT's worth of data.
16825 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
16826   assert(VT.isFixedLengthVector() &&
16827          "Expected to convert into a fixed length vector!");
16828   assert(V.getValueType().isScalableVector() &&
16829          "Expected a scalable vector operand!");
16830   SDLoc DL(V);
16831   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16832   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
16833 }
16834 
16835 // Convert all fixed length vector loads larger than NEON to masked_loads.
16836 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
16837     SDValue Op, SelectionDAG &DAG) const {
16838   auto Load = cast<LoadSDNode>(Op);
16839 
16840   SDLoc DL(Op);
16841   EVT VT = Op.getValueType();
16842   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16843 
16844   auto NewLoad = DAG.getMaskedLoad(
16845       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
16846       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
16847       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
16848       Load->getExtensionType());
16849 
16850   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
16851   SDValue MergedValues[2] = {Result, Load->getChain()};
16852   return DAG.getMergeValues(MergedValues, DL);
16853 }
16854 
16855 // Convert all fixed length vector stores larger than NEON to masked_stores.
16856 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
16857     SDValue Op, SelectionDAG &DAG) const {
16858   auto Store = cast<StoreSDNode>(Op);
16859 
16860   SDLoc DL(Op);
16861   EVT VT = Store->getValue().getValueType();
16862   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16863 
16864   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
16865   return DAG.getMaskedStore(
16866       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
16867       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
16868       Store->getMemOperand(), Store->getAddressingMode(),
16869       Store->isTruncatingStore());
16870 }
16871 
16872 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
16873     SDValue Op, SelectionDAG &DAG) const {
16874   SDLoc dl(Op);
16875   EVT VT = Op.getValueType();
16876   EVT EltVT = VT.getVectorElementType();
16877 
16878   bool Signed = Op.getOpcode() == ISD::SDIV;
16879   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
16880 
16881   // Scalable vector i32/i64 DIV is supported.
16882   if (EltVT == MVT::i32 || EltVT == MVT::i64)
16883     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
16884 
16885   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
16886   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16887   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
16888   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
16889   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
16890 
16891   // Convert the operands to scalable vectors.
16892   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16893   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16894 
16895   // Extend the scalable operands.
16896   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16897   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
16898   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
16899   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
16900   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
16901   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
16902 
16903   // Convert back to fixed vectors so the DIV can be further lowered.
16904   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
16905   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
16906   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
16907   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
16908   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16909                                  Op0Lo, Op1Lo);
16910   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16911                                  Op0Hi, Op1Hi);
16912 
16913   // Convert again to scalable vectors to truncate.
16914   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
16915   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
16916   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
16917                                        ResultLo, ResultHi);
16918 
16919   return convertFromScalableVector(DAG, VT, ScalableResult);
16920 }
16921 
16922 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
16923     SDValue Op, SelectionDAG &DAG) const {
16924   EVT VT = Op.getValueType();
16925   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16926 
16927   SDLoc DL(Op);
16928   SDValue Val = Op.getOperand(0);
16929   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16930   Val = convertToScalableVector(DAG, ContainerVT, Val);
16931 
16932   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
16933   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16934 
16935   // Repeatedly unpack Val until the result is of the desired element type.
16936   switch (ContainerVT.getSimpleVT().SimpleTy) {
16937   default:
16938     llvm_unreachable("unimplemented container type");
16939   case MVT::nxv16i8:
16940     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
16941     if (VT.getVectorElementType() == MVT::i16)
16942       break;
16943     LLVM_FALLTHROUGH;
16944   case MVT::nxv8i16:
16945     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
16946     if (VT.getVectorElementType() == MVT::i32)
16947       break;
16948     LLVM_FALLTHROUGH;
16949   case MVT::nxv4i32:
16950     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
16951     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
16952     break;
16953   }
16954 
16955   return convertFromScalableVector(DAG, VT, Val);
16956 }
16957 
16958 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
16959     SDValue Op, SelectionDAG &DAG) const {
16960   EVT VT = Op.getValueType();
16961   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16962 
16963   SDLoc DL(Op);
16964   SDValue Val = Op.getOperand(0);
16965   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16966   Val = convertToScalableVector(DAG, ContainerVT, Val);
16967 
16968   // Repeatedly truncate Val until the result is of the desired element type.
16969   switch (ContainerVT.getSimpleVT().SimpleTy) {
16970   default:
16971     llvm_unreachable("unimplemented container type");
16972   case MVT::nxv2i64:
16973     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
16974     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
16975     if (VT.getVectorElementType() == MVT::i32)
16976       break;
16977     LLVM_FALLTHROUGH;
16978   case MVT::nxv4i32:
16979     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
16980     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
16981     if (VT.getVectorElementType() == MVT::i16)
16982       break;
16983     LLVM_FALLTHROUGH;
16984   case MVT::nxv8i16:
16985     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
16986     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
16987     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
16988     break;
16989   }
16990 
16991   return convertFromScalableVector(DAG, VT, Val);
16992 }
16993 
16994 // Convert vector operation 'Op' to an equivalent predicated operation whereby
16995 // the original operation's type is used to construct a suitable predicate.
16996 // NOTE: The results for inactive lanes are undefined.
16997 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
16998                                                    SelectionDAG &DAG,
16999                                                    unsigned NewOp,
17000                                                    bool OverrideNEON) const {
17001   EVT VT = Op.getValueType();
17002   SDLoc DL(Op);
17003   auto Pg = getPredicateForVector(DAG, DL, VT);
17004 
17005   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
17006     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
17007 
17008     // Create list of operands by converting existing ones to scalable types.
17009     SmallVector<SDValue, 4> Operands = {Pg};
17010     for (const SDValue &V : Op->op_values()) {
17011       if (isa<CondCodeSDNode>(V)) {
17012         Operands.push_back(V);
17013         continue;
17014       }
17015 
17016       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
17017         EVT VTArg = VTNode->getVT().getVectorElementType();
17018         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
17019         Operands.push_back(DAG.getValueType(NewVTArg));
17020         continue;
17021       }
17022 
17023       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
17024              "Only fixed length vectors are supported!");
17025       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
17026     }
17027 
17028     if (isMergePassthruOpcode(NewOp))
17029       Operands.push_back(DAG.getUNDEF(ContainerVT));
17030 
17031     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
17032     return convertFromScalableVector(DAG, VT, ScalableRes);
17033   }
17034 
17035   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
17036 
17037   SmallVector<SDValue, 4> Operands = {Pg};
17038   for (const SDValue &V : Op->op_values()) {
17039     assert((!V.getValueType().isVector() ||
17040             V.getValueType().isScalableVector()) &&
17041            "Only scalable vectors are supported!");
17042     Operands.push_back(V);
17043   }
17044 
17045   if (isMergePassthruOpcode(NewOp))
17046     Operands.push_back(DAG.getUNDEF(VT));
17047 
17048   return DAG.getNode(NewOp, DL, VT, Operands);
17049 }
17050 
17051 // If a fixed length vector operation has no side effects when applied to
17052 // undefined elements, we can safely use scalable vectors to perform the same
17053 // operation without needing to worry about predication.
17054 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
17055                                                  SelectionDAG &DAG) const {
17056   EVT VT = Op.getValueType();
17057   assert(useSVEForFixedLengthVectorVT(VT) &&
17058          "Only expected to lower fixed length vector operation!");
17059   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
17060 
17061   // Create list of operands by converting existing ones to scalable types.
17062   SmallVector<SDValue, 4> Ops;
17063   for (const SDValue &V : Op->op_values()) {
17064     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
17065 
17066     // Pass through non-vector operands.
17067     if (!V.getValueType().isVector()) {
17068       Ops.push_back(V);
17069       continue;
17070     }
17071 
17072     // "cast" fixed length vector to a scalable vector.
17073     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
17074            "Only fixed length vectors are supported!");
17075     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
17076   }
17077 
17078   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
17079   return convertFromScalableVector(DAG, VT, ScalableRes);
17080 }
17081 
17082 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
17083     SelectionDAG &DAG) const {
17084   SDLoc DL(ScalarOp);
17085   SDValue AccOp = ScalarOp.getOperand(0);
17086   SDValue VecOp = ScalarOp.getOperand(1);
17087   EVT SrcVT = VecOp.getValueType();
17088   EVT ResVT = SrcVT.getVectorElementType();
17089 
17090   EVT ContainerVT = SrcVT;
17091   if (SrcVT.isFixedLengthVector()) {
17092     ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
17093     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
17094   }
17095 
17096   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
17097   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
17098 
17099   // Convert operands to Scalable.
17100   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
17101                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
17102 
17103   // Perform reduction.
17104   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
17105                             Pg, AccOp, VecOp);
17106 
17107   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
17108 }
17109 
17110 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
17111                                                        SelectionDAG &DAG) const {
17112   SDLoc DL(ReduceOp);
17113   SDValue Op = ReduceOp.getOperand(0);
17114   EVT OpVT = Op.getValueType();
17115   EVT VT = ReduceOp.getValueType();
17116 
17117   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
17118     return SDValue();
17119 
17120   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
17121 
17122   switch (ReduceOp.getOpcode()) {
17123   default:
17124     return SDValue();
17125   case ISD::VECREDUCE_OR:
17126     return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
17127   case ISD::VECREDUCE_AND: {
17128     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
17129     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
17130   }
17131   case ISD::VECREDUCE_XOR: {
17132     SDValue ID =
17133         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
17134     SDValue Cntp =
17135         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
17136     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
17137   }
17138   }
17139 
17140   return SDValue();
17141 }
17142 
17143 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
17144                                                    SDValue ScalarOp,
17145                                                    SelectionDAG &DAG) const {
17146   SDLoc DL(ScalarOp);
17147   SDValue VecOp = ScalarOp.getOperand(0);
17148   EVT SrcVT = VecOp.getValueType();
17149 
17150   if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
17151     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
17152     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
17153   }
17154 
17155   // UADDV always returns an i64 result.
17156   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
17157                                                    SrcVT.getVectorElementType();
17158   EVT RdxVT = SrcVT;
17159   if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
17160     RdxVT = getPackedSVEVectorVT(ResVT);
17161 
17162   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
17163   SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
17164   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
17165                             Rdx, DAG.getConstant(0, DL, MVT::i64));
17166 
17167   // The VEC_REDUCE nodes expect an element size result.
17168   if (ResVT != ScalarOp.getValueType())
17169     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
17170 
17171   return Res;
17172 }
17173 
17174 SDValue
17175 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
17176     SelectionDAG &DAG) const {
17177   EVT VT = Op.getValueType();
17178   SDLoc DL(Op);
17179 
17180   EVT InVT = Op.getOperand(1).getValueType();
17181   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
17182   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
17183   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
17184 
17185   // Convert the mask to a predicated (NOTE: We don't need to worry about
17186   // inactive lanes since VSELECT is safe when given undefined elements).
17187   EVT MaskVT = Op.getOperand(0).getValueType();
17188   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
17189   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
17190   Mask = DAG.getNode(ISD::TRUNCATE, DL,
17191                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
17192 
17193   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
17194                                 Mask, Op1, Op2);
17195 
17196   return convertFromScalableVector(DAG, VT, ScalableRes);
17197 }
17198 
17199 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
17200     SDValue Op, SelectionDAG &DAG) const {
17201   SDLoc DL(Op);
17202   EVT InVT = Op.getOperand(0).getValueType();
17203   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
17204 
17205   assert(useSVEForFixedLengthVectorVT(InVT) &&
17206          "Only expected to lower fixed length vector operation!");
17207   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
17208          "Expected integer result of the same bit length as the inputs!");
17209 
17210   // Expand floating point vector comparisons.
17211   if (InVT.isFloatingPoint())
17212     return SDValue();
17213 
17214   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
17215   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
17216   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
17217 
17218   EVT CmpVT = Pg.getValueType();
17219   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
17220                          {Pg, Op1, Op2, Op.getOperand(2)});
17221 
17222   EVT PromoteVT = ContainerVT.changeTypeToInteger();
17223   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
17224   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
17225 }
17226 
17227 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
17228                                                  SelectionDAG &DAG) const {
17229   SDLoc DL(Op);
17230   EVT InVT = Op.getValueType();
17231   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17232   (void)TLI;
17233 
17234   assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
17235          InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
17236          "Only expect to cast between legal scalable vector types!");
17237   assert((VT.getVectorElementType() == MVT::i1) ==
17238              (InVT.getVectorElementType() == MVT::i1) &&
17239          "Cannot cast between data and predicate scalable vector types!");
17240 
17241   if (InVT == VT)
17242     return Op;
17243 
17244   if (VT.getVectorElementType() == MVT::i1)
17245     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
17246 
17247   EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
17248   EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
17249   assert((VT == PackedVT || InVT == PackedInVT) &&
17250          "Cannot cast between unpacked scalable vector types!");
17251 
17252   // Pack input if required.
17253   if (InVT != PackedInVT)
17254     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
17255 
17256   Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
17257 
17258   // Unpack result if required.
17259   if (VT != PackedVT)
17260     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
17261 
17262   return Op;
17263 }
17264